diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5a1236d6..180729a4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,6 +71,57 @@ jobs: - run: cargo build --locked -p ide-host --bin openidea-server --target x86_64-unknown-linux-musl - run: target/x86_64-unknown-linux-musl/debug/openidea-server --version + # The plugin SDK, the official plugins and the test fixtures build in their + # own workspaces (the root excludes them), so the jobs above don't see them. + plugins: + name: Plugins (SDK, official, fixtures) + runs-on: ubuntu-22.04 + env: + CARGO_TARGET_DIR: ${{ github.workspace }}/target-plugins + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: { targets: wasm32-wasip2, components: "clippy, rustfmt" } + - uses: Swatinem/rust-cache@v2 + with: + key: plugins + cache-directories: target-plugins + save-if: ${{ github.ref == 'refs/heads/main' }} + - name: Format, lint (host and wasm) and test each crate + shell: bash + run: | + set -euo pipefail + for dir in sdk/rust/openidea-plugin plugins/official/*/ crates/ide-plugin/tests/fixtures/*/; do + [ -f "$dir/Cargo.toml" ] || continue + echo "::group::$dir" + cargo fmt --check --manifest-path "$dir/Cargo.toml" + cargo clippy --locked --all-targets --manifest-path "$dir/Cargo.toml" -- -D warnings + cargo clippy --locked --target wasm32-wasip2 --manifest-path "$dir/Cargo.toml" -- -D warnings + cargo test --locked --manifest-path "$dir/Cargo.toml" + echo "::endgroup::" + done + - uses: pnpm/action-setup@v4 + with: { version: 11 } + - uses: actions/setup-node@v4 + with: { node-version: 22 } + # Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test. + - name: Web pages typecheck and test + shell: bash + run: | + set -euo pipefail + for dir in plugins/official/*/web-src/; do + [ -f "$dir/package.json" ] || continue + echo "::group::$dir" + pnpm --dir "$dir" install --frozen-lockfile --ignore-workspace + pnpm --dir "$dir" exec tsc --noEmit + pnpm --dir "$dir" test + echo "::endgroup::" + done + # The host's tests run the checked-in components: they must be built from these sources. + # Web pages aren't checked in: this builds them and checks the result. + - name: Checked-in components are up to date, web pages build + run: plugins/build.sh --check + deny: name: Cargo deny runs-on: ubuntu-latest diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1527d20f..3874f17e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -180,6 +180,69 @@ jobs: if command -v sha256sum >/dev/null; then sha256sum "$ASSET"; else shasum -a 256 "$ASSET"; fi > "$ASSET.sha256" gh release upload "$TAG" "$ASSET" "$ASSET.sha256" --clobber + # The official plugins, signed, and the marketplace index released apps read + # (releases/latest/download/plugins-index.json). They are not in the + # installers: users install them from Settings › Plugins. Without the + # signing key (secret PLUGIN_SIGNING_KEY: the file `openidea-plugin keygen` + # writes) nothing is published and the release goes on. + plugins: + needs: create-release + name: Official plugins + runs-on: ubuntu-22.04 + env: + SIGNING_KEY: ${{ secrets.PLUGIN_SIGNING_KEY }} + steps: + - id: key + run: | + if [ -z "$SIGNING_KEY" ]; then + echo "::warning::PLUGIN_SIGNING_KEY is not set: the official plugins are not published" + echo "skip=true" >> "$GITHUB_OUTPUT" + fi + - uses: actions/checkout@v4 + if: steps.key.outputs.skip != 'true' + with: { ref: "${{ env.TAG }}" } + - uses: dtolnay/rust-toolchain@stable + if: steps.key.outputs.skip != 'true' + with: { targets: wasm32-wasip2 } + - uses: Swatinem/rust-cache@v2 + if: steps.key.outputs.skip != 'true' + with: { key: release-plugins } + - uses: pnpm/action-setup@v4 + if: steps.key.outputs.skip != 'true' + with: { version: 11 } + - uses: actions/setup-node@v4 + if: steps.key.outputs.skip != 'true' + with: { node-version: 22 } + # Builds the web pages; fails when a checked-in component isn't built from these sources. + - name: Build + if: steps.key.outputs.skip != 'true' + run: | + plugins/build.sh --check + cargo build --release --locked -p ide-host --bin openidea-plugin + - name: Pack, index and upload + if: steps.key.outputs.skip != 'true' + shell: bash + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + tool="$PWD/target/release/openidea-plugin" + key="$RUNNER_TEMP/openidea.key" + out="$RUNNER_TEMP/market" + (umask 077 && printf '%s' "$SIGNING_KEY" > "$key") + trap 'rm -f "$key"' EXIT + mkdir -p "$out" + for dir in plugins/official/*/; do + id="$(sed -n 's/^id *= *"\(.*\)".*/\1/p' "$dir/plugin.toml" | head -1)" + version="$(sed -n 's/^version *= *"\(.*\)".*/\1/p' "$dir/plugin.toml" | head -1)" + "$tool" pack "$dir" --key "$key" --publisher openidea --out "$out/$id-$version.oiplugin" + done + # The published index's revocations and earlier keys carry over. + curl -fsSL "https://github.com/$GITHUB_REPOSITORY/releases/latest/download/plugins-index.json" \ + -o "$out/plugins-index.json" || rm -f "$out/plugins-index.json" + "$tool" index "$out" --publisher openidea --name OpenIDEA --key "$key" --out "$out/plugins-index.json" + gh release upload "$TAG" "$out"/*.oiplugin "$out/plugins-index.json" --clobber + # The updater manifest (latest.json), built once from the signed bundles every build uploaded. # Fails when a platform is missing, so a release never ships a manifest without it. updater-manifest: @@ -243,7 +306,7 @@ jobs: core.info(`latest.json: ${Object.keys(platforms).sort().join(", ")}`); publish: - needs: [create-release, build, server, updater-manifest] + needs: [create-release, build, server, plugins, updater-manifest] runs-on: ubuntu-latest steps: - uses: actions/github-script@v7 diff --git a/.gitignore b/.gitignore index 88c7d40b..75785cf0 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,9 @@ lerna-debug.log* node_modules dist dist-ssr +# Plugin components are checked in (plugins/build.sh --check keeps them current). +!plugins/official/*/dist +!crates/ide-plugin/tests/fixtures/*/dist *.local # Editor directories and files diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 70f64132..0a0d7102 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -15,6 +15,8 @@ "pnpm-lock.yaml", "**/*.toml", "fixtures", + "plugins/*/web", + "plugins/official/*/web", "crates/**/tests/fixtures" ], "overrides": [ diff --git a/Cargo.lock b/Cargo.lock index a39ae699..4d308c5d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4181,6 +4181,26 @@ dependencies = [ "which", ] +[[package]] +name = "ide-extension" +version = "0.1.35" +dependencies = [ + "base64 0.22.1", + "blake3", + "ed25519-dalek", + "ide-core", + "parking_lot", + "semver", + "serde", + "serde_json", + "specta", + "specta-typescript", + "tempfile", + "toml 0.9.12+spec-1.1.0", + "tracing", + "zip", +] + [[package]] name = "ide-fonts" version = "0.1.35" @@ -4210,9 +4230,13 @@ dependencies = [ name = "ide-host" version = "0.1.35" dependencies = [ + "base64 0.22.1", + "criterion", "dirs 6.0.0", "dunce", "encoding_rs", + "getrandom 0.3.4", + "globset", "ide-agent", "ide-analysis", "ide-build", @@ -4220,12 +4244,14 @@ dependencies = [ "ide-coverage", "ide-dap", "ide-db", + "ide-extension", "ide-http", "ide-index", "ide-jsonrpc", "ide-language", "ide-lsp", "ide-notebook", + "ide-plugin", "ide-remote", "ide-run", "ide-sdk", @@ -4239,7 +4265,9 @@ dependencies = [ "ide-vcs", "ide-vfs", "ide-workspace", + "ignore", "parking_lot", + "reqwest", "rustix", "serde", "serde_json", @@ -4247,10 +4275,12 @@ dependencies = [ "specta-typescript", "tempfile", "tokio", + "toml 0.9.12+spec-1.1.0", "tracing", "tracing-subscriber", "uuid", "windows-sys 0.61.2", + "zip", ] [[package]] @@ -4316,6 +4346,7 @@ dependencies = [ "blake3", "criterion", "ide-core", + "ide-extension", "ide-text", "parking_lot", "regex-lite", @@ -4417,19 +4448,20 @@ dependencies = [ name = "ide-plugin" version = "0.1.35" dependencies = [ + "blake3", "ide-core", - "ide-language", + "ide-extension", "parking_lot", + "semver", "serde", "serde_json", "specta", "tempfile", "thiserror 2.0.21", - "toml 0.9.12+spec-1.1.0", + "tokio", "tracing", "wasmtime", "wasmtime-wasi", - "zip", ] [[package]] @@ -6150,6 +6182,7 @@ dependencies = [ name = "openidea" version = "0.1.35" dependencies = [ + "base64 0.22.1", "blake3", "block2 0.6.2", "dirs 6.0.0", @@ -6164,6 +6197,7 @@ dependencies = [ "ide-dap", "ide-db", "ide-docker", + "ide-extension", "ide-fonts", "ide-github", "ide-host", @@ -6195,6 +6229,8 @@ dependencies = [ "objc2-foundation 0.3.2", "objc2-web-kit 0.3.2", "parking_lot", + "percent-encoding", + "security-framework", "serde", "serde_json", "specta", diff --git a/Cargo.toml b/Cargo.toml index f306034e..a1c42bf2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,8 @@ [workspace] resolver = "3" members = ["crates/*", "src-tauri"] +# Plugins and the guest SDK build for wasm32-wasip2 in their own workspaces. +exclude = ["sdk", "plugins"] [workspace.package] version = "0.1.35" @@ -41,6 +43,8 @@ ide-ssh = { path = "crates/ide-ssh" } ide-remote = { path = "crates/ide-remote" } ide-host = { path = "crates/ide-host" } ide-notebook = { path = "crates/ide-notebook" } +ide-extension = { path = "crates/ide-extension" } +ide-plugin = { path = "crates/ide-plugin" } # serialization & IPC typing serde = { version = "1", features = ["derive"] } @@ -69,6 +73,7 @@ ropey = "1.6" encoding_rs = "0.8" chardetng = "0.1" ignore = "0.4" +base64 = "0.22" globset = "0.4" notify = "8" notify-debouncer-full = "0.6" diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index 95ba3f5f..ebb97835 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -61,6 +61,9 @@ pub struct Settings { pub cmake: CMakeSettings, /// Tools › Agents › Chat. pub agents: AgentSettings, + /// Plugin settings (`[contributes.settings]`): plugin id → its values by key. + #[specta(type = BTreeMap>)] + pub plugins: BTreeMap>, } /// What the meters in an agent task's header show. @@ -215,6 +218,7 @@ impl Default for Settings { run_targets: Vec::new(), cmake: CMakeSettings::default(), agents: AgentSettings::default(), + plugins: BTreeMap::new(), } } } @@ -323,7 +327,8 @@ impl Default for NotificationGroupSettings { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(default, rename_all = "camelCase")] pub struct AppearanceSettings { - /// `dark` | `light` | `system` | `dark-hc` (high-contrast dark) + /// A built-in theme id (`light`, `dark`, `dark-hc`, …), `system` (legacy + /// "Sync with OS"), or a plugin's theme: `plugin:/`. pub theme: String, pub accent: String, pub ui_font_size: f32, @@ -332,6 +337,8 @@ pub struct AppearanceSettings { pub sync_with_os: bool, pub preferred_light_theme: String, pub preferred_dark_theme: String, + /// A plugin's file icon theme (`/`); empty = the built-in icons. + pub file_icon_theme: String, /// IDE zoom in percent (50–300). pub zoom: u32, /// Apply `ui_font_family` / `ui_font_size` (otherwise the theme's). @@ -386,6 +393,7 @@ impl Default for AppearanceSettings { sync_with_os: false, preferred_light_theme: "light".into(), preferred_dark_theme: "dark".into(), + file_icon_theme: String::new(), zoom: 100, use_custom_font: false, ui_font_family: "Inter".into(), diff --git a/crates/ide-dap/src/adapter.rs b/crates/ide-dap/src/adapter.rs index 341e0663..2f4f88fc 100644 --- a/crates/ide-dap/src/adapter.rs +++ b/crates/ide-dap/src/adapter.rs @@ -8,7 +8,7 @@ use ide_core::process::executable_names; use ide_core::{IdeError, IdeResult}; -use ide_language::{DebuggerConfig, LanguageRegistry}; +use ide_language::{DebuggerConfig, LanguageRegistry, ProgramPin}; use std::future::Future; use std::path::{Path, PathBuf}; use std::pin::Pin; @@ -44,6 +44,8 @@ pub struct AdapterSpec { /// `host:port` of an adapter inside another program (the Godot editor): connected to /// when it accepts, else `command` is started. pub connect: Option, + /// A plugin language's adapter: start exactly this approved program. + pub pinned: Option, } /// Built-in adapters used when no language definition names `adapter`. @@ -55,6 +57,7 @@ fn builtin(adapter: &str) -> Option { transport: transport.to_owned(), connect: None, install_hint: Some(hint.to_owned()), + pinned: None, }; Some(match adapter { "codelldb" => cfg( @@ -133,6 +136,7 @@ pub fn resolve(config: &DebuggerConfig, cwd: PathBuf) -> AdapterSpec { env: Vec::new(), server_host: None, connect: config.connect.clone(), + pinned: config.pinned.clone(), } } @@ -426,12 +430,20 @@ impl AdapterLauncher for ProcessLauncher { if is_plugin_bundle(&spec.command) { return Err(not_standalone(&spec)); } - let (command, cwd) = (spec.command.clone(), spec.cwd.clone()); - let binary = tokio::task::spawn_blocking(move || resolve_binary(&command, &cwd)) - .await - .ok() - .flatten() - .ok_or_else(|| missing(&spec))?; + let binary = match spec.pinned.clone() { + Some(pin) => tokio::task::spawn_blocking(move || pin.verify().map(Path::to_path_buf)) + .await + .map_err(|e| IdeError::internal(e.to_string()))? + .map_err(|e| IdeError::new(ide_core::error::ErrorKind::PermissionDenied, e))?, + None => { + let (command, cwd) = (spec.command.clone(), spec.cwd.clone()); + tokio::task::spawn_blocking(move || resolve_binary(&command, &cwd)) + .await + .ok() + .flatten() + .ok_or_else(|| missing(&spec))? + } + }; let port = match spec.transport { // An embedded adapter started without `${port}` listens on its usual address. Transport::Tcp => match &embedded { diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rs index e1fb0eca..f108c0fb 100644 --- a/crates/ide-dap/src/tests.rs +++ b/crates/ide-dap/src/tests.rs @@ -915,6 +915,7 @@ fn godot_registry(port: u16, command: &str, args: &[&str]) -> Arc Risk { + match self { + Self::ProjectRead | Self::EditorRead | Self::Storage | Self::Events | Self::VcsRead => Risk::Low, + Self::EditorWrite | Self::VcsWrite | Self::Net(_) | Self::Secrets | Self::InputEvents | Self::Clipboard => { + Risk::Medium + } + Self::Process(_) | Self::FsRead(_) => Risk::High, + } + } + + /// Low-risk capabilities that the one-time migration of the 0.1 "declared + /// means granted" behaviour may grant automatically (plan 4.6). + pub fn auto_migrates(&self) -> bool { + self.risk() == Risk::Low + } + + /// Short user-facing description for install and grant pages. + pub fn describe(&self) -> String { + match self { + Self::ProjectRead => "Read files in the open project".into(), + Self::EditorRead => "Read the focused editor's file and selection".into(), + Self::EditorWrite => "Change text in the editor".into(), + Self::VcsRead => "Read version control state".into(), + Self::VcsWrite => "Change version control state (commit, fetch, checkout)".into(), + Self::Storage => "Store its own data".into(), + Self::Secrets => "Store secrets in the system keychain".into(), + Self::Events => "Observe workbench events (files opened, saved, focus)".into(), + Self::InputEvents => "Observe keystrokes and editor input".into(), + Self::Clipboard => "Read and write the clipboard from its web views".into(), + Self::Net(host) => format!("Connect to {host} (from the machine the project is on)"), + Self::Process(bin) => format!("Run {bin} — equivalent to running arbitrary code on this machine"), + Self::FsRead(path) => format!("Read files under {path}, outside the project"), + } + } + + /// Whether `self`, granted, also covers `wanted` (`net:*.x.com` covers `net:a.x.com`). + pub fn covers(&self, wanted: &Capability) -> bool { + match (self, wanted) { + (Self::Net(pattern), Self::Net(host)) => host_matches(pattern, host), + (Self::FsRead(base), Self::FsRead(path)) => { + std::path::Path::new(path).starts_with(std::path::Path::new(base)) + } + _ => self == wanted, + } + } +} + +/// `example.com` matches exactly; `*.example.com` matches any subdomain (not the apex). +pub fn host_matches(pattern: &str, host: &str) -> bool { + let host = host.trim_end_matches('.').to_ascii_lowercase(); + let pattern = pattern.to_ascii_lowercase(); + match pattern.strip_prefix("*.") { + Some(suffix) => host.len() > suffix.len() + 1 && host.ends_with(&format!(".{suffix}")), + None => host == pattern, + } +} + +impl fmt::Display for Capability { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::ProjectRead => f.write_str("project.read"), + Self::EditorRead => f.write_str("editor.read"), + Self::EditorWrite => f.write_str("editor.write"), + Self::VcsRead => f.write_str("vcs.read"), + Self::VcsWrite => f.write_str("vcs.write"), + Self::Storage => f.write_str("storage"), + Self::Secrets => f.write_str("secrets"), + Self::Events => f.write_str("events"), + Self::InputEvents => f.write_str("events.input"), + Self::Clipboard => f.write_str("clipboard"), + Self::Net(h) => write!(f, "net:{h}"), + Self::Process(b) => write!(f, "process:{b}"), + Self::FsRead(p) => write!(f, "fs.read:{p}"), + } + } +} + +impl FromStr for Capability { + type Err = String; + + fn from_str(s: &str) -> Result { + let s = s.trim(); + if let Some((kind, arg)) = s.split_once(':') { + let arg = arg.trim(); + if arg.is_empty() { + return Err(format!("capability {s:?} needs a value after ':'")); + } + return match kind { + "net" => { + let host = arg.strip_prefix("*.").unwrap_or(arg); + let valid = !host.is_empty() + && host.len() <= 253 + && host.split('.').all(|label| { + !label.is_empty() + && label.len() <= 63 + && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') + }); + if valid { Ok(Self::Net(arg.to_ascii_lowercase())) } else { Err(format!("invalid host in {s:?}")) } + } + "process" => { + if arg.contains(['/', '\\']) && !std::path::Path::new(arg).is_absolute() { + return Err(format!("{s:?}: use a program name or an absolute path")); + } + Ok(Self::Process(arg.to_owned())) + } + "fs.read" => { + if !std::path::Path::new(arg).is_absolute() && !arg.starts_with('~') { + return Err(format!("{s:?}: use an absolute path (or ~/…)")); + } + Ok(Self::FsRead(arg.to_owned())) + } + _ => Err(format!("unknown capability {s:?}")), + }; + } + Ok(match s { + "project.read" | "project-read" => Self::ProjectRead, + "editor.read" | "editor-read" => Self::EditorRead, + "editor.write" | "editor-write" => Self::EditorWrite, + "vcs.read" => Self::VcsRead, + "vcs.write" => Self::VcsWrite, + "storage" => Self::Storage, + "secrets" => Self::Secrets, + "events" => Self::Events, + "events.input" => Self::InputEvents, + "clipboard" => Self::Clipboard, + _ => return Err(format!("unknown capability {s:?}")), + }) + } +} + +impl Serialize for Capability { + fn serialize(&self, s: S) -> Result { + s.collect_str(self) + } +} + +impl<'de> Deserialize<'de> for Capability { + fn deserialize>(d: D) -> Result { + String::deserialize(d)?.parse().map_err(serde::de::Error::custom) + } +} + +/// A capability as the UI shows it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct CapabilityInfo { + /// `project.read`, `net:crates.io`, … + pub id: String, + pub risk: Risk, + pub description: String, + /// Declared under `optional`: the plugin runs without it. + pub optional: bool, + /// Currently granted. + pub granted: bool, +} + +impl CapabilityInfo { + pub fn new(cap: &Capability, optional: bool, granted: bool) -> Self { + Self { id: cap.to_string(), risk: cap.risk(), description: cap.describe(), optional, granted } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_and_prints() { + for s in [ + "project.read", + "editor.write", + "vcs.write", + "storage", + "secrets", + "events", + "events.input", + "net:crates.io", + "net:*.github.com", + "process:cargo", + ] { + assert_eq!(s.parse::().unwrap().to_string(), s); + } + // Absolute paths are the platform's. + let (git, etc) = if cfg!(windows) { + (r"process:C:\Program Files\Git\bin\git.exe", r"fs.read:C:\Windows") + } else { + ("process:/usr/bin/git", "fs.read:/etc") + }; + for s in [git, etc] { + assert_eq!(s.parse::().unwrap().to_string(), s); + } + assert_eq!("project-read".parse::().unwrap(), Capability::ProjectRead); + assert!("net:".parse::().is_err()); + assert!("net:a b".parse::().is_err()); + assert!("process:./evil".parse::().is_err()); + assert!("fs.read:rel".parse::().is_err()); + assert!("network".parse::().is_err()); + } + + #[test] + fn risk_levels() { + assert_eq!(Capability::ProjectRead.risk(), Risk::Low); + assert_eq!(Capability::Net("x".into()).risk(), Risk::Medium); + assert_eq!(Capability::InputEvents.risk(), Risk::Medium); + assert_eq!("clipboard".parse::().unwrap(), Capability::Clipboard); + assert_eq!(Capability::Clipboard.risk(), Risk::Medium); + assert_eq!(Capability::Process("cargo".into()).risk(), Risk::High); + assert!(Capability::Storage.auto_migrates() && !Capability::EditorWrite.auto_migrates()); + } + + #[test] + fn host_patterns() { + assert!(host_matches("crates.io", "crates.io")); + assert!(host_matches("crates.io", "CRATES.IO.")); + assert!(!host_matches("crates.io", "static.crates.io")); + assert!(host_matches("*.github.com", "api.github.com")); + assert!(!host_matches("*.github.com", "github.com")); + assert!(!host_matches("*.github.com", "evilgithub.com")); + let any_gh: Capability = "net:*.github.com".parse().unwrap(); + assert!(any_gh.covers(&"net:api.github.com".parse().unwrap())); + assert!(Capability::FsRead("/etc".into()).covers(&Capability::FsRead("/etc/hosts".into()))); + assert!(!Capability::FsRead("/etc".into()).covers(&Capability::FsRead("/etcx".into()))); + } +} diff --git a/crates/ide-extension/src/index.rs b/crates/ide-extension/src/index.rs new file mode 100644 index 00000000..cadc0ea9 --- /dev/null +++ b/crates/ide-extension/src/index.rs @@ -0,0 +1,104 @@ +//! The contribution index: validated UI +//! declarations of installed packages, kept on disk so start-up does not +//! validate them again (sanitising thousands of icon SVGs, say). +//! +//! Only packages with a [`Package::digest`] are indexed: installed copies, +//! which the host never modifies after install. An entry is keyed by that +//! digest, the extension point, the declaration and a salt naming the +//! validation logic (the IDE version), so a new package version, a changed +//! declaration or an IDE upgrade simply misses. A miss or an unreadable entry +//! only costs the validation. + +use crate::point::Package; +use crate::ui::UiDecl; +use std::collections::BTreeSet; +use std::path::PathBuf; + +/// Bumped when [`UiDecl`]'s serialized shape changes. +const FORMAT: u32 = 1; + +pub struct ContributionIndex { + dir: PathBuf, + salt: String, +} + +impl ContributionIndex { + /// `salt` names the validators' version (the IDE version). + pub fn new(dir: PathBuf, salt: &str) -> Self { + Self { dir, salt: format!("{FORMAT}:{salt}") } + } + + /// Entries start with a prefix of the package digest, for pruning. + fn file(&self, digest: &str, point: &str, decl: &toml::Value) -> PathBuf { + let mut h = blake3::Hasher::new(); + for part in [self.salt.as_str(), digest, point, &decl.to_string()] { + h.update(part.as_bytes()); + h.update(&[0]); + } + let key = h.finalize().to_hex(); + self.dir.join(format!("{}-{}.json", prefix(digest), &key[..32])) + } + + pub fn get(&self, pkg: &Package, point: &str, decl: &toml::Value) -> Option { + let digest = pkg.digest.as_deref()?; + let bytes = std::fs::read(self.file(digest, point, decl)).ok()?; + serde_json::from_slice(&bytes).ok() + } + + pub fn put(&self, pkg: &Package, point: &str, decl: &toml::Value, ui: &UiDecl) { + let Some(digest) = pkg.digest.as_deref() else { return }; + let Ok(bytes) = serde_json::to_vec(ui) else { return }; + let file = self.file(digest, point, decl); + let _ = std::fs::create_dir_all(&self.dir); + let tmp = file.with_extension(format!("tmp{}", std::process::id())); + if std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, &file)).is_err() { + let _ = std::fs::remove_file(&tmp); + } + } + + /// Removes entries of packages other than `live` (digests). + pub fn prune<'a>(&self, live: impl IntoIterator) { + let keep: BTreeSet = live.into_iter().map(|d| prefix(d).to_owned()).collect(); + let Ok(entries) = std::fs::read_dir(&self.dir) else { return }; + for e in entries.flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + if !name.split_once('-').is_some_and(|(p, _)| keep.contains(p)) { + let _ = std::fs::remove_file(e.path()); + } + } + } +} + +fn prefix(digest: &str) -> &str { + let d = digest.strip_prefix("blake3:").unwrap_or(digest); + let end = d.char_indices().nth(16).map_or(d.len(), |(i, _)| i); + &d[..end] +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::manifest::Manifest; + + #[test] + fn hits_only_the_same_package_point_declaration_and_salt() { + let tmp = tempfile::tempdir().unwrap(); + let index = ContributionIndex::new(tmp.path().join("idx"), "1.0"); + let manifest = + Manifest::parse("id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\n").unwrap(); + let pkg = Package::new(manifest, tmp.path().to_path_buf()).with_digest("blake3:00aa11bb22cc33dd44ee"); + let decl: toml::Value = toml::from_str("id = \"x\"").unwrap(); + let ui = UiDecl::new("x", "X", serde_json::json!({ "id": "x" })); + assert!(index.get(&pkg, "pt", &decl).is_none()); + index.put(&pkg, "pt", &decl, &ui); + assert_eq!(index.get(&pkg, "pt", &decl).unwrap().label, "X"); + assert!(index.get(&pkg, "other", &decl).is_none()); + assert!(index.get(&pkg, "pt", &toml::from_str("id = \"y\"").unwrap()).is_none()); + assert!(ContributionIndex::new(tmp.path().join("idx"), "1.1").get(&pkg, "pt", &decl).is_none()); + let unhashed = Package { digest: None, ..pkg.clone() }; + assert!(index.get(&unhashed, "pt", &decl).is_none(), "not an installed copy"); + + index.prune(["blake3:ffff"]); + assert!(index.get(&pkg, "pt", &decl).is_none()); + } +} diff --git a/crates/ide-extension/src/ledger.rs b/crates/ide-extension/src/ledger.rs new file mode 100644 index 00000000..9bed117b --- /dev/null +++ b/crates/ide-extension/src/ledger.rs @@ -0,0 +1,483 @@ +//! The grant ledger (plan 4.6): which capabilities the user granted to which +//! plugin, saved as `grants.json` next to the installed plugins. +//! +//! - Installed plugins are keyed by id and remember the version and package +//! hash they were confirmed for. An update that needs no new capability is +//! accepted silently; one that does must be confirmed again. +//! - Linked development plugins and project plugins (`.openidea/plugins/*`) +//! are keyed by their directory, not by hash, so rebuilding does not ask +//! again; new capabilities still do. +//! - `process:` grants record the program's absolute path and file +//! hash at grant time. Calls use that path, never a `PATH` lookup, and fail +//! when the file changed (re-confirmation needed). + +use crate::capability::{Capability, Risk}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; +use std::ffi::OsStr; +use std::path::{Path, PathBuf}; + +pub const LEDGER_FILE: &str = "grants.json"; +const FORMAT: u32 = 1; + +/// Whose grant an entry is. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(tag = "kind", content = "value", rename_all = "camelCase")] +pub enum Subject { + /// Installed under the plugins directory, by plugin id. + Installed(String), + /// A linked development plugin or a project plugin, by package directory. + Path(PathBuf), +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BinaryGrant { + pub path: PathBuf, + /// blake3 of the file when granted. + pub hash: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Grant { + pub plugin_id: String, + /// The version and package hash the user confirmed (installed plugins). + #[serde(default)] + pub version: String, + #[serde(default)] + pub package_hash: String, + /// The user confirmed the plugin (the install page or the project-plugin prompt). + #[serde(default)] + pub confirmed: bool, + /// Granted capabilities (`project.read`, `net:x`, …). + #[serde(default)] + pub granted: BTreeSet, + /// Optional capabilities the user declined (not asked again until re-confirmed). + #[serde(default)] + pub declined: BTreeSet, + /// `process:` → the program confirmed for it. + #[serde(default)] + pub binaries: BTreeMap, + /// Migrated from 0.1: capabilities not granted yet are asked for on first + /// use instead of blocking the plugin from loading. + #[serde(default)] + pub ask_on_use: bool, +} + +impl Grant { + pub fn has(&self, cap: &Capability) -> bool { + self.granted.iter().filter_map(|s| s.parse::().ok()).any(|g| g.covers(cap)) + } +} + +/// What a plugin (in its current form) needs, to compare with its grant. +#[derive(Clone, Debug)] +pub struct Request<'a> { + pub subject: Subject, + pub plugin_id: &'a str, + pub version: &'a str, + pub package_hash: &'a str, + pub required: Vec, + pub optional: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Decision { + /// Load with these capabilities. `pending` required ones are asked for when + /// the plugin is first used (plugins migrated from 0.1 only). + Allowed { granted: Vec, pending: Vec }, + /// Ask the user first. `new` lists what was never granted (all of it on first use). + NeedsConfirmation { new: Vec, first_time: bool }, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct File { + #[serde(default)] + format: u32, + /// The one-time migration from 0.1 ("declared means granted") ran. + #[serde(default)] + migrated: bool, + #[serde(default)] + grants: Vec<(Subject, Grant)>, +} + +/// The ledger, loaded into memory; [`Ledger::save`] writes it atomically. +#[derive(Debug, Default)] +pub struct Ledger { + path: Option, + migrated: bool, + grants: BTreeMap, +} + +impl Ledger { + /// Loads `/grants.json`; a missing or unreadable file gives an empty + /// ledger with `needs_migration()` true. + pub fn load(dir: &Path) -> Self { + let path = dir.join(LEDGER_FILE); + let file: Option = std::fs::read_to_string(&path).ok().and_then(|s| match serde_json::from_str(&s) { + Ok(f) => Some(f), + Err(e) => { + tracing::warn!("{}: {e}; starting with an empty grant ledger", path.display()); + None + } + }); + let existed = file.is_some(); + let file = file.unwrap_or_default(); + Self { path: Some(path), migrated: file.migrated || existed, grants: file.grants.into_iter().collect() } + } + + pub fn in_memory() -> Self { + Self { path: None, migrated: true, grants: BTreeMap::new() } + } + + pub fn save(&self) -> std::io::Result<()> { + let Some(path) = &self.path else { return Ok(()) }; + let file = File { + format: FORMAT, + migrated: self.migrated, + grants: self.grants.iter().map(|(s, g)| (s.clone(), g.clone())).collect(), + }; + let json = serde_json::to_string_pretty(&file).map_err(std::io::Error::other)?; + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, json)?; + std::fs::rename(&tmp, path) + } + + pub fn get(&self, subject: &Subject) -> Option<&Grant> { + self.grants.get(subject) + } + + pub fn remove(&mut self, subject: &Subject) -> Option { + self.grants.remove(subject) + } + + /// Puts back an earlier state of `subject`'s grant (`None`: none), e.g. + /// after rolling back an update. + pub fn restore(&mut self, subject: &Subject, grant: Option) { + match grant { + Some(g) => { + self.grants.insert(subject.clone(), g); + } + None => { + self.grants.remove(subject); + } + } + } + + /// The one-time migration of 0.1's "declared means granted" has not run yet. + pub fn needs_migration(&self) -> bool { + !self.migrated + } + + /// Migrates plugins installed before the ledger existed: low-risk + /// capabilities are granted, the rest are asked on first use. + pub fn migrate(&mut self, installed: &[Request<'_>]) { + for req in installed { + let granted: BTreeSet = + req.required.iter().chain(&req.optional).filter(|c| c.auto_migrates()).map(|c| c.to_string()).collect(); + self.grants.entry(req.subject.clone()).or_insert_with(|| Grant { + plugin_id: req.plugin_id.to_owned(), + version: req.version.to_owned(), + package_hash: req.package_hash.to_owned(), + confirmed: true, + granted, + ask_on_use: true, + ..Grant::default() + }); + } + self.migrated = true; + } + + /// Compares what the plugin needs with what was granted. + pub fn decide(&mut self, req: &Request<'_>) -> Decision { + let Some(grant) = self.grants.get_mut(&req.subject) else { + return Decision::NeedsConfirmation { new: req.required.clone(), first_time: true }; + }; + if !grant.confirmed { + return Decision::NeedsConfirmation { new: req.required.clone(), first_time: true }; + } + let new: Vec = req.required.iter().filter(|c| !grant.has(c)).cloned().collect(); + if !new.is_empty() && !grant.ask_on_use { + return Decision::NeedsConfirmation { new, first_time: false }; + } + // Same or fewer needs: accept an update silently (plan 4.6). + if grant.version != req.version || grant.package_hash != req.package_hash { + grant.version = req.version.to_owned(); + grant.package_hash = req.package_hash.to_owned(); + } + let granted = req.required.iter().chain(&req.optional).filter(|c| grant.has(c)).cloned().collect(); + Decision::Allowed { granted, pending: new } + } + + /// Records the user's confirmation: `required` plus the accepted optional capabilities. + pub fn confirm( + &mut self, + req: &Request<'_>, + accepted_optional: &[Capability], + binaries: BTreeMap, + ) { + let grant = self.grants.entry(req.subject.clone()).or_default(); + grant.plugin_id = req.plugin_id.to_owned(); + grant.version = req.version.to_owned(); + grant.package_hash = req.package_hash.to_owned(); + grant.confirmed = true; + grant.ask_on_use = false; + for cap in req.required.iter().chain(accepted_optional) { + grant.granted.insert(cap.to_string()); + } + for cap in &req.optional { + let s = cap.to_string(); + if accepted_optional.contains(cap) { + grant.declined.remove(&s); + } else if !grant.granted.contains(&s) { + grant.declined.insert(s); + } + } + grant.binaries.extend(binaries); + } + + /// Grants or revokes one capability (Settings › Plugins › permissions). + pub fn set(&mut self, subject: &Subject, cap: &Capability, granted: bool) -> bool { + let Some(grant) = self.grants.get_mut(subject) else { return false }; + let s = cap.to_string(); + if granted { + grant.declined.remove(&s); + grant.granted.insert(s) + } else { + if let Capability::Process(_) = cap { + grant.binaries.remove(&s); + } + grant.granted.remove(&s) + } + } + + /// Records the program approved for a `process:` grant. + pub fn set_binary(&mut self, subject: &Subject, cap: &Capability, binary: BinaryGrant) { + if let Some(grant) = self.grants.get_mut(subject) { + grant.binaries.insert(cap.to_string(), binary); + } + } + + /// Checks a `process:` grant at call time: the program confirmed for it, + /// unchanged since. Errors name what to do. + pub fn check_binary(&self, subject: &Subject, cap: &Capability) -> Result { + let Capability::Process(name) = cap else { return Err(format!("{cap} is not a process capability")) }; + let grant = self.grants.get(subject).ok_or_else(|| format!("{cap} was not granted"))?; + let key = cap.to_string(); + if !grant.granted.contains(&key) { + return Err(format!("{cap} was not granted")); + } + let bin = grant.binaries.get(&key).ok_or_else(|| format!("{cap}: no program was confirmed for {name}"))?; + match file_hash(&bin.path) { + Ok(hash) if hash == bin.hash => Ok(bin.path.clone()), + Ok(_) => Err(format!( + "{} changed since it was approved for {cap}; confirm the plugin's permissions again", + bin.path.display() + )), + Err(e) => Err(format!("{}: {e}; confirm the plugin's permissions again", bin.path.display())), + } + } + + /// The program approved for a granted `process:` capability, without + /// checking the file: whoever starts it verifies the hash then + /// ([`check_binary`](Self::check_binary) or the pin's own check). + pub fn pinned_binary(&self, subject: &Subject, cap: &Capability) -> Option { + let grant = self.grants.get(subject)?; + let key = cap.to_string(); + if !grant.granted.contains(&key) { + return None; + } + grant.binaries.get(&key).cloned() + } + + pub fn subjects(&self) -> impl Iterator { + self.grants.iter() + } +} + +/// What a confirmation page shows: every capability with its risk, high risk first. +pub fn by_risk(caps: &[Capability]) -> Vec<(Risk, Vec)> { + let mut groups: BTreeMap, Vec> = BTreeMap::new(); + for c in caps { + groups.entry(std::cmp::Reverse(c.risk())).or_default().push(c.clone()); + } + groups.into_iter().map(|(r, v)| (r.0, v)).collect() +} + +/// Resolves a `process:` program to an absolute path once, at grant time: +/// absolute names are taken as is, others are looked up in `path_var`. +pub fn resolve_program(name: &str, path_var: Option<&OsStr>) -> Result { + let candidate = Path::new(name); + if candidate.is_absolute() { + return if candidate.is_file() { Ok(candidate.to_path_buf()) } else { Err(format!("{name}: no such program")) }; + } + let exts: Vec = if cfg!(windows) { + std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into()).split(';').map(str::to_owned).collect() + } else { + vec![String::new()] + }; + for dir in std::env::split_paths(path_var.unwrap_or_default()) { + if !dir.is_absolute() { + continue; // `.` or relative entries could point into the project + } + for ext in &exts { + let p = dir.join(format!("{name}{ext}")); + if is_executable(&p) { + return Ok(dunce_canonical(&p)); + } + } + } + Err(format!("{name} was not found on PATH")) +} + +fn dunce_canonical(p: &Path) -> PathBuf { + std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()) +} + +fn is_executable(p: &Path) -> bool { + let Ok(meta) = std::fs::metadata(p) else { return false }; + if !meta.is_file() { + return false; + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + meta.permissions().mode() & 0o111 != 0 + } + #[cfg(not(unix))] + true +} + +/// blake3 of a file, hex. +pub fn file_hash(path: &Path) -> std::io::Result { + let mut hasher = blake3::Hasher::new(); + hasher.update_reader(std::fs::File::open(path)?)?; + Ok(hasher.finalize().to_hex().to_string()) +} + +/// blake3 over a package's files (sorted relative paths and contents). +pub fn package_hash(dir: &Path, files: &[PathBuf]) -> std::io::Result { + let mut sorted: Vec<&PathBuf> = files.iter().collect(); + sorted.sort(); + sorted.dedup(); + let mut hasher = blake3::Hasher::new(); + for rel in sorted { + hasher.update(rel.to_string_lossy().as_bytes()); + hasher.update(&[0]); + hasher.update_reader(std::fs::File::open(dir.join(rel))?)?; + hasher.update(&[0]); + } + Ok(hasher.finalize().to_hex().to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn caps(list: &[&str]) -> Vec { + list.iter().map(|s| s.parse().unwrap()).collect() + } + + fn req<'a>(version: &'a str, hash: &'a str, required: &[&str], optional: &[&str]) -> Request<'a> { + Request { + subject: Subject::Installed("p".into()), + plugin_id: "p", + version, + package_hash: hash, + required: caps(required), + optional: caps(optional), + } + } + + #[test] + fn confirmation_then_silent_update_then_reconfirm_on_new_capability() { + let mut l = Ledger::in_memory(); + let r1 = req("1.0.0", "h1", &["project.read"], &["net:crates.io"]); + assert_eq!(l.decide(&r1), Decision::NeedsConfirmation { new: caps(&["project.read"]), first_time: true }); + l.confirm(&r1, &[], BTreeMap::new()); + assert_eq!( + l.decide(&r1), + Decision::Allowed { granted: caps(&["project.read"]), pending: vec![] }, + "declined optional" + ); + assert!(l.get(&r1.subject).unwrap().declined.contains("net:crates.io")); + + // Same needs, new version: silent. + let r2 = req("1.1.0", "h2", &["project.read"], &["net:crates.io"]); + assert!(matches!(l.decide(&r2), Decision::Allowed { .. })); + assert_eq!(l.get(&r2.subject).unwrap().version, "1.1.0"); + + // A new required capability: ask again, only for it. + let r3 = req("1.2.0", "h3", &["project.read", "editor.write"], &[]); + assert_eq!(l.decide(&r3), Decision::NeedsConfirmation { new: caps(&["editor.write"]), first_time: false }); + l.confirm(&r3, &[], BTreeMap::new()); + assert!(matches!(l.decide(&r3), Decision::Allowed { .. })); + + // Revoking a required capability blocks loading again. + assert!(l.set(&r3.subject, &Capability::EditorWrite, false)); + assert!(matches!(l.decide(&r3), Decision::NeedsConfirmation { .. })); + } + + #[test] + fn migration_grants_low_risk_only() { + let tmp = tempfile::tempdir().unwrap(); + let mut l = Ledger::load(tmp.path()); + assert!(l.needs_migration()); + let r = req("0.1.0", "h", &["project.read", "editor.write"], &[]); + l.migrate(std::slice::from_ref(&r)); + // Loads with the low-risk part; the rest is asked for on first use. + assert_eq!( + l.decide(&r), + Decision::Allowed { granted: caps(&["project.read"]), pending: caps(&["editor.write"]) } + ); + l.confirm(&r, &[], BTreeMap::new()); + assert_eq!( + l.decide(&r), + Decision::Allowed { granted: caps(&["project.read", "editor.write"]), pending: vec![] } + ); + l.save().unwrap(); + let again = Ledger::load(tmp.path()); + assert!(!again.needs_migration()); + assert!(again.get(&r.subject).unwrap().has(&Capability::ProjectRead)); + } + + #[cfg(unix)] + #[test] + fn binaries_are_pinned_by_path_and_hash() { + use std::os::unix::fs::PermissionsExt; + let tmp = tempfile::tempdir().unwrap(); + let bin_dir = tmp.path().join("bin"); + std::fs::create_dir(&bin_dir).unwrap(); + let tool = bin_dir.join("tool"); + std::fs::write(&tool, "#!/bin/sh\necho v1\n").unwrap(); + std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap(); + let path_var = std::env::join_paths([PathBuf::from("relative"), bin_dir.clone()]).unwrap(); + let resolved = resolve_program("tool", Some(&path_var)).unwrap(); + assert!(resolved.is_absolute()); + assert!(resolve_program("missing", Some(&path_var)).is_err()); + + let mut l = Ledger::in_memory(); + let r = req("1.0.0", "h", &["process:tool"], &[]); + let cap: Capability = "process:tool".parse().unwrap(); + let bin = BinaryGrant { path: resolved.clone(), hash: file_hash(&resolved).unwrap() }; + l.confirm(&r, &[], [(cap.to_string(), bin)].into()); + assert_eq!(l.check_binary(&r.subject, &cap).unwrap(), resolved); + std::fs::write(&tool, "#!/bin/sh\necho evil\n").unwrap(); + assert!(l.check_binary(&r.subject, &cap).unwrap_err().contains("changed")); + } + + #[test] + fn hashes_and_grouping() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join("a"), "1").unwrap(); + std::fs::write(tmp.path().join("b"), "2").unwrap(); + let h1 = package_hash(tmp.path(), &["a".into(), "b".into()]).unwrap(); + assert_eq!(h1, package_hash(tmp.path(), &["b".into(), "a".into()]).unwrap()); + std::fs::write(tmp.path().join("b"), "3").unwrap(); + assert_ne!(h1, package_hash(tmp.path(), &["a".into(), "b".into()]).unwrap()); + let groups = by_risk(&caps(&["storage", "process:git", "net:x.io"])); + assert_eq!(groups.iter().map(|g| g.0).collect::>(), [Risk::High, Risk::Medium, Risk::Low]); + } +} diff --git a/crates/ide-extension/src/lib.rs b/crates/ide-extension/src/lib.rs new file mode 100644 index 00000000..9089067a --- /dev/null +++ b/crates/ide-extension/src/lib.rs @@ -0,0 +1,36 @@ +//! The plugin system's kernel, independent of the Wasm runtime: +//! +//! - [`Manifest`]: `plugin.toml` (0.2 format; 0.1 still parses); +//! - [`Capability`]: what a plugin may do, with its [`Risk`] level; +//! - [`ExtensionPoint`]: one kind of contribution, implemented by the crate that +//! owns the feature; [`ExtensionRegistry`] validates a package's declarations +//! ([`ExtensionRegistry::prepare`], no side effects), makes them take effect +//! all or nothing ([`ExtensionRegistry::commit`]) and withdraws them per plugin; +//! - [`UiStore`] / [`UiPoint`]: UI contributions, validated here and projected +//! by the client without the possibility to fail; +//! - [`ledger`]: which capabilities the user granted to which plugin; +//! - [`package`]: the package file, its signature and the marketplace index. +//! +//! Dependency direction: `ide-core` ← `ide-extension` ← feature crates (their +//! extension points) and `ide-plugin` (Wasm) ← `ide-host` (assembly). + +mod capability; +mod index; +pub mod ledger; +mod manifest; +pub mod package; +mod point; +mod registry; +mod ui; +mod when; + +pub use capability::{Capability, CapabilityInfo, Risk, host_matches}; +pub use index::ContributionIndex; +pub use manifest::{ + ActivationEvent, Capabilities, ENGINE_VERSION, EVENT_KINDS, LEGACY_API, MANIFEST_FILE, Manifest, check_relative, + engine_compatible, validate_item_id, validate_plugin_id, validate_point_id, +}; +pub use point::{Commit, Disposable, ExtensionPoint, MAX_PACKAGE_FILE, Package, Placement, Prepared, decode}; +pub use registry::{ContributionInfo, ExtensionRegistry, PreparedSet}; +pub use ui::{UiContribution, UiDecl, UiPoint, UiStore, to_json}; +pub use when::validate_when; diff --git a/crates/ide-extension/src/manifest.rs b/crates/ide-extension/src/manifest.rs new file mode 100644 index 00000000..99820d5f --- /dev/null +++ b/crates/ide-extension/src/manifest.rs @@ -0,0 +1,501 @@ +//! `plugin.toml`, the package manifest (plan 4.4). +//! +//! ```toml +//! id = "acme.rust-tools" # optional publisher namespace before the first '.' +//! name = "Rust Tools" +//! version = "1.2.0" +//! engines.openidea = "^1.0" +//! wasm = "plugin.wasm" +//! activation = ["on-language:rust", "on-command:check"] +//! +//! [capabilities] +//! required = ["project.read", "editor.write"] +//! optional = ["net:crates.io", "process:cargo"] +//! +//! [[contributes.commands]] +//! id = "check" +//! title = "Check" +//! ``` +//! +//! `contributes` is kept as raw TOML: each `contributes.` is parsed and +//! validated by the extension point registered under that id +//! ([`crate::ExtensionRegistry`]), so new contribution types need no change here. +//! +//! Manifests in the 0.1 format (`openidea-api = "0.1"`, `permissions = [...]`) +//! still parse: permissions become required capabilities and the plugin is +//! activated at start-up, as before. + +use crate::capability::Capability; +use serde::Deserialize; +use std::collections::BTreeSet; +use std::path::{Component, Path, PathBuf}; + +pub const MANIFEST_FILE: &str = "plugin.toml"; +/// The plugin API (engine) version this host implements. +pub const ENGINE_VERSION: &str = "1.0.0"; +/// The 0.1 API, still accepted for contribution-only packages and 0.1 components. +pub const LEGACY_API: &str = "0.1"; + +#[derive(Clone, Debug, PartialEq)] +pub struct Manifest { + pub id: String, + pub name: String, + pub version: String, + pub description: String, + pub authors: Vec, + pub homepage: Option, + pub license: Option, + /// Release notes of this version (Settings › Plugins › What's New). + pub change_notes: Option, + /// `engines.openidea` (a semver requirement), or the legacy `openidea-api`. + pub engine: String, + /// Written in the 0.1 format. + pub legacy: bool, + /// Component file relative to the package directory. + pub wasm: Option, + pub activation: Vec, + pub capabilities: Capabilities, + /// `contributes.` → its declarations, validated by the extension points. + pub contributes: toml::Table, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Capabilities { + pub required: Vec, + pub optional: Vec, +} + +impl Capabilities { + pub fn all(&self) -> impl Iterator { + self.required.iter().chain(&self.optional) + } + + pub fn is_optional(&self, cap: &Capability) -> bool { + self.optional.contains(cap) && !self.required.contains(cap) + } +} + +/// When a plugin's code is instantiated (plan 4.4). Contributions are live +/// without it; code only runs once one of these fires. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ActivationEvent { + /// One of the plugin's commands is run (`on-command:`; `*` = any). + Command(String), + /// A file of this language is opened. + Language(String), + /// A file matching this glob (project-relative) is opened. + File(String), + /// One of the plugin's views is shown. + View(String), + /// Periodically: `on-schedule:`. Does not keep the plugin alive. + Schedule(u32), + /// A workbench event of this kind (`on-event:file-saved`): the plugin is + /// subscribed from the start, and activated to receive it. + Event(String), + /// Shortly after the workbench is ready. + StartupFinished, +} + +impl ActivationEvent { + pub fn parse(s: &str) -> Result { + let s = s.trim(); + if s == "on-startup-finished" { + return Ok(Self::StartupFinished); + } + let (kind, arg) = s.split_once(':').ok_or_else(|| format!("unknown activation event {s:?}"))?; + let arg = arg.trim(); + if arg.is_empty() { + return Err(format!("activation event {s:?} needs a value")); + } + Ok(match kind { + "on-command" => Self::Command(arg.into()), + "on-language" => Self::Language(arg.into()), + "on-file" => Self::File(arg.into()), + "on-view" => Self::View(arg.into()), + "on-schedule" => { + let secs: u32 = + arg.trim_end_matches('s').parse().map_err(|_| format!("{s:?}: expected seconds, e.g. 300"))?; + if secs < 60 { + return Err(format!("{s:?}: the shortest schedule is 60 seconds")); + } + Self::Schedule(secs) + } + "on-event" => { + if !EVENT_KINDS.contains(&arg) { + return Err(format!("{s:?}: unknown event kind (one of {})", EVENT_KINDS.join(", "))); + } + Self::Event(arg.into()) + } + _ => return Err(format!("unknown activation event {s:?}")), + }) + } +} + +/// Workbench event kinds (`on-event:`, WIT `events.event-kind`). +/// `scheduled` comes from `on-schedule` instead. +pub const EVENT_KINDS: &[&str] = &["file-opened", "file-saved", "editor-focused", "action-performed", "vcs-changed"]; + +impl std::fmt::Display for ActivationEvent { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Command(c) => write!(f, "on-command:{c}"), + Self::Language(l) => write!(f, "on-language:{l}"), + Self::File(g) => write!(f, "on-file:{g}"), + Self::View(v) => write!(f, "on-view:{v}"), + Self::Schedule(s) => write!(f, "on-schedule:{s}"), + Self::Event(k) => write!(f, "on-event:{k}"), + Self::StartupFinished => f.write_str("on-startup-finished"), + } + } +} + +#[derive(Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +struct Raw { + id: String, + name: String, + version: String, + #[serde(default)] + description: String, + #[serde(default)] + authors: Vec, + #[serde(default)] + homepage: Option, + #[serde(default)] + license: Option, + #[serde(default)] + change_notes: Option, + #[serde(default)] + engines: Option, + /// 0.1 format. + #[serde(default)] + openidea_api: Option, + #[serde(default)] + wasm: Option, + #[serde(default)] + activation: Option>, + #[serde(default)] + capabilities: Option, + /// 0.1 format. + #[serde(default)] + permissions: Option>, + #[serde(default)] + contributes: toml::Table, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Engines { + openidea: String, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawCapabilities { + #[serde(default)] + required: Vec, + #[serde(default)] + optional: Vec, +} + +impl Manifest { + pub fn parse(src: &str) -> Result { + let raw: Raw = toml::from_str(src).map_err(|e| e.to_string())?; + let (engine, legacy) = match (raw.engines, raw.openidea_api) { + (Some(e), None) => (e.openidea, false), + (None, Some(api)) => (api, true), + (Some(_), Some(_)) => return Err("use `engines.openidea`, not `openidea-api`".into()), + (None, None) => return Err("missing `engines.openidea` (e.g. \"^1.0\")".into()), + }; + if legacy && raw.capabilities.is_some() { + return Err("`capabilities` requires `engines.openidea`; 0.1 manifests use `permissions`".into()); + } + if !legacy && raw.permissions.is_some() { + return Err("`permissions` is the 0.1 format; use `[capabilities] required = [...]`".into()); + } + let parse_caps = |list: Vec| -> Result, String> { + let mut out: Vec = Vec::new(); + for s in list { + let cap: Capability = s.parse()?; + if !out.contains(&cap) { + out.push(cap); + } + } + Ok(out) + }; + let capabilities = match (raw.capabilities, raw.permissions) { + (Some(c), _) => Capabilities { required: parse_caps(c.required)?, optional: parse_caps(c.optional)? }, + (None, Some(p)) => Capabilities { required: parse_caps(p)?, optional: Vec::new() }, + (None, None) => Capabilities::default(), + }; + let activation = match raw.activation { + Some(list) => list.iter().map(|s| ActivationEvent::parse(s)).collect::, _>>()?, + // 0.1 plugins were activated at start-up; keep that until they move to 1.0. + None if legacy && raw.wasm.is_some() => vec![ActivationEvent::StartupFinished], + None => Vec::new(), + }; + let m = Manifest { + id: raw.id, + name: raw.name, + version: raw.version, + description: raw.description, + authors: raw.authors, + homepage: raw.homepage, + license: raw.license, + change_notes: raw.change_notes, + engine, + legacy, + wasm: raw.wasm, + activation, + capabilities, + contributes: raw.contributes, + }; + m.validate()?; + Ok(m) + } + + pub fn load(dir: &Path) -> Result { + let path = dir.join(MANIFEST_FILE); + let src = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?; + Self::parse(&src).map_err(|e| format!("{}: {e}", path.display())) + } + + fn validate(&self) -> Result<(), String> { + validate_plugin_id(&self.id)?; + if self.name.trim().is_empty() { + return Err("`name` must not be empty".into()); + } + if semver::Version::parse(&self.version).is_err() { + return Err(format!("`version` must be a semantic version like 1.2.3, got {:?}", self.version)); + } + if !engine_compatible(&self.engine, self.legacy) { + return Err(if self.legacy { + format!( + "unsupported openidea-api {:?} (this IDE implements {LEGACY_API} and {ENGINE_VERSION})", + self.engine + ) + } else { + format!("engines.openidea {:?} does not match this IDE's plugin API {ENGINE_VERSION}", self.engine) + }); + } + if let Some(wasm) = &self.wasm { + check_relative(wasm, "wasm")?; + } + if self.wasm.is_none() && !self.activation.is_empty() { + return Err("`activation` needs `wasm`: there is no code to activate".into()); + } + let mut seen = BTreeSet::new(); + for event in &self.activation { + if !seen.insert(event) { + return Err(format!("duplicate activation event {event}")); + } + } + for (point, decls) in &self.contributes { + validate_point_id(point)?; + if !matches!(decls, toml::Value::Array(_) | toml::Value::Table(_)) { + return Err(format!("`contributes.{point}` must be a table or an array of tables")); + } + } + Ok(()) + } + + /// The declarations of one extension point: `[[contributes.x]]` gives + /// several, `[contributes.x]` one. + pub fn declarations(&self, point: &str) -> Vec { + match self.contributes.get(point) { + Some(toml::Value::Array(items)) => items.clone(), + Some(single @ toml::Value::Table(_)) => vec![single.clone()], + _ => Vec::new(), + } + } + + /// Number of declarations per extension point (for listings before loading). + pub fn declaration_counts(&self) -> Vec<(String, u32)> { + self.contributes.keys().map(|p| (p.clone(), self.declarations(p).len() as u32)).collect() + } + + /// Publisher namespace: the id's part before the first `.` (`acme` in `acme.tools`). + pub fn publisher(&self) -> Option<&str> { + self.id.split_once('.').map(|(p, _)| p) + } + + /// Whether `cap` is declared (required or optional). + pub fn declares(&self, cap: &Capability) -> bool { + self.capabilities.all().any(|c| c.covers(cap)) + } +} + +/// Whether this host can load a plugin written for `engine`. +pub fn engine_compatible(engine: &str, legacy: bool) -> bool { + if legacy { + return engine == LEGACY_API || engine.strip_prefix(LEGACY_API).is_some_and(|rest| rest.starts_with('.')); + } + let Ok(req) = semver::VersionReq::parse(engine) else { return false }; + let host = semver::Version::parse(ENGINE_VERSION).expect("valid engine version"); + req.matches(&host) +} + +/// Segments of `[a-z0-9][a-z0-9_-]*` joined by `.` (an optional publisher +/// namespace first), at most 64 chars. +pub fn validate_plugin_id(id: &str) -> Result<(), String> { + let ok = id.len() <= 64 && !id.is_empty() && id.split('.').all(segment_ok); + if ok { + Ok(()) + } else { + Err(format!( + "invalid plugin id {id:?}: use a-z, 0-9, '-', '_' in '.'-separated parts (e.g. acme.tools), max 64" + )) + } +} + +/// `[a-z0-9][a-z0-9._-]*`, at most 64 chars (commands, themes, views…). +pub fn validate_item_id(id: &str, what: &str) -> Result<(), String> { + let ok_first = id.chars().next().is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit()); + let ok_rest = id.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '-' | '_' | '.')); + if ok_first && ok_rest && id.len() <= 64 { + Ok(()) + } else { + Err(format!("invalid {what} {id:?}: use a-z, 0-9, '.', '-', '_', starting with a letter or digit (max 64)")) + } +} + +/// Extension point ids: `camelCase` or `kebab-case` words, dots allowed (`iconThemes`, `menus`). +pub fn validate_point_id(id: &str) -> Result<(), String> { + let ok = !id.is_empty() + && id.len() <= 64 + && id.starts_with(|c: char| c.is_ascii_lowercase()) + && id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.')); + if ok { Ok(()) } else { Err(format!("invalid contribution point {id:?}")) } +} + +fn segment_ok(s: &str) -> bool { + s.chars().next().is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) + && s.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_') +} + +/// Package paths must stay inside the package directory. +pub fn check_relative(path: &Path, what: &str) -> Result<(), String> { + let ok = !path.as_os_str().is_empty() && path.components().all(|c| matches!(c, Component::Normal(_))); + if ok { Ok(()) } else { Err(format!("{what} {:?} must be a relative path inside the plugin", path.display())) } +} + +#[cfg(test)] +mod tests { + use super::*; + + const FULL: &str = r#" + id = "acme.rust-tools" + name = "Rust Tools" + version = "1.2.0" + engines.openidea = "^1.0" + wasm = "plugin.wasm" + activation = ["on-language:rust", "on-command:check", "on-schedule:300"] + + [capabilities] + required = ["project.read", "editor.write"] + optional = ["net:crates.io", "process:cargo"] + + [[contributes.commands]] + id = "check" + title = "%check.title%" + + [[contributes.menus]] + menu = "editor.context" + command = "check" + when = "editorLang == rust" + + [contributes.settings] + schema = "settings.schema.json" + "#; + + #[test] + fn event_activation() { + assert_eq!(ActivationEvent::parse("on-event:file-saved"), Ok(ActivationEvent::Event("file-saved".into()))); + assert_eq!(ActivationEvent::Event("vcs-changed".into()).to_string(), "on-event:vcs-changed"); + let err = ActivationEvent::parse("on-event:keystroke").unwrap_err(); + assert!(err.contains("unknown event kind") && err.contains("action-performed"), "{err}"); + assert!(ActivationEvent::parse("on-event:scheduled").is_err(), "declared with on-schedule"); + } + + #[test] + fn parses_the_02_format() { + let m = Manifest::parse(FULL).unwrap(); + assert_eq!(m.publisher(), Some("acme")); + assert!(!m.legacy); + assert_eq!(m.activation.len(), 3); + assert_eq!(m.activation[2], ActivationEvent::Schedule(300)); + assert_eq!(m.capabilities.required, vec![Capability::ProjectRead, Capability::EditorWrite]); + assert!(m.capabilities.is_optional(&Capability::Process("cargo".into()))); + assert_eq!(m.declarations("commands").len(), 1); + assert_eq!(m.declarations("settings").len(), 1, "a single table is one declaration"); + assert!(m.declarations("nope").is_empty()); + let counts: Vec<_> = m.declaration_counts(); + assert!(counts.contains(&("menus".into(), 1))); + } + + #[test] + fn parses_the_01_format() { + let m = Manifest::parse( + "id = \"hello\"\nname = \"Hello\"\nversion = \"0.1.0\"\nopenidea-api = \"0.1\"\nwasm = \"dist/plugin.wasm\"\n\ + permissions = [\"project-read\", \"editor-write\"]\n[[contributes.commands]]\nid = \"x\"\ntitle = \"X\"", + ) + .unwrap(); + assert!(m.legacy); + assert_eq!(m.capabilities.required, vec![Capability::ProjectRead, Capability::EditorWrite]); + assert_eq!(m.activation, vec![ActivationEvent::StartupFinished]); + assert_eq!(m.publisher(), None); + } + + fn err(src: &str) -> String { + Manifest::parse(src).unwrap_err() + } + + #[test] + fn rejects_invalid_manifests() { + let base = |extra: &str| format!("id = \"ok\"\nname = \"N\"\nversion = \"1.0.0\"\n{extra}"); + assert!(err(&base("")).contains("engines.openidea")); + assert!(err(&base("engines.openidea = \"^0.3\"")).contains("does not match")); + assert!(err(&base("engines.openidea = \"^2\"")).contains("does not match")); + assert!(err(&base("engines.openidea = \"^0.2\"")).contains("does not match")); + assert!(err(&base("openidea-api = \"0.2\"")).contains("unsupported")); + assert!(err(&base("engines.openidea = \"^1.0\"\npermissions = [\"project-read\"]")).contains("0.1 format")); + assert!( + err(&base("engines.openidea = \"^1.0\"\n[capabilities]\nrequired = [\"network\"]")).contains("unknown") + ); + assert!(err(&base("engines.openidea = \"^1.0\"\nwasm = \"../x.wasm\"")).contains("relative path")); + assert!(err(&base("engines.openidea = \"^1.0\"\nactivation = [\"on-command:x\"]")).contains("needs `wasm`")); + assert!( + err(&base("engines.openidea = \"^1.0\"\nwasm = \"p.wasm\"\nactivation = [\"on-boot\"]")) + .contains("unknown") + ); + assert!( + err(&base("engines.openidea = \"^1.0\"\nwasm = \"p.wasm\"\nactivation = [\"on-schedule:5\"]")) + .contains("60 seconds") + ); + assert!(err(&base("engines.openidea = \"^1.0\"\nbogus = 1")).contains("unknown field")); + assert!(err(&base("engines.openidea = \"^1.0\"\ncontributes.commands = 3")).contains("table")); + assert!( + err("id = \"Bad\"\nname = \"N\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"").contains("plugin id") + ); + assert!( + err("id = \"a..b\"\nname = \"N\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"").contains("plugin id") + ); + assert!(err("id = \"ok\"\nname = \"N\"\nversion = \"1.0\"\nengines.openidea = \"^1.0\"").contains("version")); + } + + #[test] + fn ids() { + assert!(validate_plugin_id("openidea.material-icons").is_ok()); + assert!(validate_plugin_id("hello_2").is_ok()); + assert!(validate_plugin_id(".x").is_err()); + assert!(validate_item_id("word-count.v2_x", "command id").is_ok()); + assert!(validate_item_id("-x", "command id").is_err()); + assert!(validate_point_id("iconThemes").is_ok()); + assert!(validate_point_id("Icon").is_err()); + assert!(engine_compatible("1.0", false)); + assert!(engine_compatible(">=1.0, <2", false)); + assert!(!engine_compatible("^0.2", false), "0.x components don't run on 1.0"); + assert!(engine_compatible("0.1.3", true)); + assert!(!engine_compatible("0.10", true)); + } +} diff --git a/crates/ide-extension/src/package.rs b/crates/ide-extension/src/package.rs new file mode 100644 index 00000000..b8d3988d --- /dev/null +++ b/crates/ide-extension/src/package.rs @@ -0,0 +1,465 @@ +//! Plugin distribution: the package file, its +//! signature, and the static marketplace index. +//! +//! - **Package** (`-.oiplugin`): a zip of the manifest, the files +//! its declarations reference, the component and licence files, plus +//! [`SIGNATURE_FILE`] when signed. +//! - **Signature**: Ed25519 over `openidea-plugin/1\n\n\n`, +//! `digest` being [`package_digest`] of the unpacked files. A signature +//! proves who published the bytes; whether to trust that publisher is the +//! index's call. +//! - **Index** (`index.json`): the publishers and their keys (the trust root), +//! the published plugins, and revocations. A publisher owns the id prefix +//! `.`; a revoked key invalidates everything it signed, a +//! revoked plugin version is disabled where it is installed. + +use crate::MANIFEST_FILE; +use base64::Engine as _; +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use serde::{Deserialize, Serialize}; +use std::io::{Read, Write}; +use std::path::{Component, Path, PathBuf}; + +pub const SIGNATURE_FILE: &str = "SIGNATURE.json"; +pub const PACKAGE_EXTENSION: &str = "oiplugin"; +pub const INDEX_FORMAT: u32 = 1; +/// Limits when unpacking an untrusted package. +const MAX_ENTRIES: usize = 10_000; +const MAX_TOTAL: u64 = 512 << 20; + +const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD; + +/// Content digest of a package: the manifest plus `files` (relative paths). +pub fn package_digest(dir: &Path, files: &[PathBuf]) -> std::io::Result { + let mut all = files.to_vec(); + all.push(PathBuf::from(MANIFEST_FILE)); + crate::ledger::package_hash(dir, &all) +} + +fn signed_message(id: &str, version: &str, digest: &str) -> Vec { + format!("openidea-plugin/1\n{id}\n{version}\n{digest}").into_bytes() +} + +/// `SIGNATURE.json` of a signed package. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PackageSignature { + pub publisher: String, + /// Ed25519 public key, base64. + pub key: String, + /// Ed25519 signature, base64. + pub signature: String, +} + +/// A publisher's key pair (the 32-byte seed, base64, in a file only the publisher has). +pub struct PublisherKey(SigningKey); + +impl PublisherKey { + pub fn from_seed(seed: [u8; 32]) -> Self { + Self(SigningKey::from_bytes(&seed)) + } + + /// The seed as written by `openidea-plugin keygen`. + pub fn from_base64(text: &str) -> Result { + let bytes = B64.decode(text.trim()).map_err(|e| format!("key file: {e}"))?; + let seed: [u8; 32] = bytes.try_into().map_err(|_| "key file: expected a 32-byte key".to_owned())?; + Ok(Self::from_seed(seed)) + } + + pub fn seed_base64(&self) -> String { + B64.encode(self.0.to_bytes()) + } + + pub fn public_base64(&self) -> String { + B64.encode(self.0.verifying_key().to_bytes()) + } + + pub fn sign(&self, publisher: &str, id: &str, version: &str, digest: &str) -> PackageSignature { + let sig = self.0.sign(&signed_message(id, version, digest)); + PackageSignature { + publisher: publisher.into(), + key: self.public_base64(), + signature: B64.encode(sig.to_bytes()), + } + } +} + +impl PackageSignature { + /// Whether the signature is valid for `id`, `version` and `digest` (the + /// key's validity is checked against an [`Index`]). + pub fn check(&self, id: &str, version: &str, digest: &str) -> Result<(), String> { + let key: [u8; 32] = B64 + .decode(&self.key) + .ok() + .and_then(|b| b.try_into().ok()) + .ok_or_else(|| "signature: malformed public key".to_owned())?; + let key = VerifyingKey::from_bytes(&key).map_err(|_| "signature: invalid public key".to_owned())?; + let sig: [u8; 64] = B64 + .decode(&self.signature) + .ok() + .and_then(|b| b.try_into().ok()) + .ok_or_else(|| "signature: malformed".to_owned())?; + key.verify_strict(&signed_message(id, version, digest), &Signature::from_bytes(&sig)) + .map_err(|_| "the signature does not match the package (it was changed after signing)".to_owned()) + } +} + +/// Writes the package `out` from `dir`: the manifest, `files`, and the signature if any. +pub fn pack(dir: &Path, files: &[PathBuf], out: &Path, signature: Option<&PackageSignature>) -> Result<(), String> { + let io = |e: std::io::Error| e.to_string(); + let file = std::fs::File::create(out).map_err(io)?; + let mut zip = zip::ZipWriter::new(file); + let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + let mut names: Vec = std::iter::once(PathBuf::from(MANIFEST_FILE)).chain(files.iter().cloned()).collect(); + names.sort(); + names.dedup(); + for rel in names { + let name = rel.to_str().ok_or("non UTF-8 file name")?.replace('\\', "/"); + zip.start_file(name, options).map_err(|e| e.to_string())?; + let bytes = std::fs::read(dir.join(&rel)).map_err(|e| format!("{}: {e}", rel.display()))?; + zip.write_all(&bytes).map_err(io)?; + } + if let Some(sig) = signature { + zip.start_file(SIGNATURE_FILE, options).map_err(|e| e.to_string())?; + zip.write_all(serde_json::to_string_pretty(sig).map_err(|e| e.to_string())?.as_bytes()).map_err(io)?; + } + zip.finish().map_err(|e| e.to_string())?; + Ok(()) +} + +/// What [`unpack`] wrote. +#[derive(Debug)] +pub struct Unpacked { + /// Every file but the manifest and the signature, relative. + pub files: Vec, + pub signature: Option, +} + +/// `name` as a relative path that stays inside the package. +fn safe_path(name: &str) -> Option { + let p = Path::new(name); + (!name.is_empty() && p.components().all(|c| matches!(c, Component::Normal(_)))).then(|| p.to_path_buf()) +} + +/// Archiver metadata at the top of an archive, not part of a package +/// (`__MACOSX/…`, `.DS_Store`, AppleDouble `._…` files). +fn archiver_metadata(name: &str) -> bool { + let top = name.split('/').next().unwrap_or_default(); + top == "__MACOSX" || top == ".DS_Store" || (top.starts_with("._") && top.len() > 2) +} + +/// Where the package is inside an archive: at its root (`.oiplugin`, or a zip +/// of the package's contents) or in its only folder (a zip of the package +/// folder). `None` when neither holds a manifest. +fn package_prefix(names: &[String]) -> Option { + if names.iter().any(|n| n == MANIFEST_FILE) { + return Some(String::new()); + } + let mut tops = names.iter().filter(|n| !archiver_metadata(n)).map(|n| n.split('/').next().unwrap_or_default()); + let top = tops.next()?; + if tops.any(|t| t != top) { + return None; + } + let prefix = format!("{top}/"); + names.iter().any(|n| *n == format!("{prefix}{MANIFEST_FILE}")).then_some(prefix) +} + +/// Extracts the package `archive` (an `.oiplugin`, or a `.zip` of a package +/// folder or of its contents) into the empty directory `dest`, refusing +/// paths leaving it, links, and oversized contents. +pub fn unpack(archive: &Path, dest: &Path) -> Result { + let file = std::fs::File::open(archive).map_err(|e| format!("{}: {e}", archive.display()))?; + let mut zip = + zip::ZipArchive::new(file).map_err(|e| format!("{}: not a plugin package ({e})", archive.display()))?; + if zip.len() > MAX_ENTRIES { + return Err(format!("more than {MAX_ENTRIES} files")); + } + let mut names = Vec::with_capacity(zip.len()); + for i in 0..zip.len() { + let entry = zip.by_index(i).map_err(|e| e.to_string())?; + if !entry.is_dir() { + names.push(entry.name().map_err(|e| e.to_string())?.into_owned()); + } + } + // An IntelliJ plugin or any other zip: say what is missing rather than fail later. + let prefix = package_prefix(&names).ok_or_else(|| { + format!("{} is not an OpenIDEA plugin: no {MANIFEST_FILE} at its root or in its only folder", archive.display()) + })?; + std::fs::create_dir_all(dest).map_err(|e| e.to_string())?; + let (mut files, mut signature, mut total, mut manifest) = (Vec::new(), None, 0u64, false); + for i in 0..zip.len() { + let mut entry = zip.by_index(i).map_err(|e| e.to_string())?; + if entry.is_dir() { + continue; + } + let full = entry.name().map_err(|e| e.to_string())?.into_owned(); + // Outside the package folder there is only archiver metadata (`package_prefix` checked). + let Some(name) = full.strip_prefix(&prefix).map(str::to_owned) else { continue }; + if archiver_metadata(&name) { + continue; + } + if entry.is_symlink() { + return Err(format!("{full}: links are not allowed in packages")); + } + let rel = safe_path(&name).ok_or_else(|| format!("invalid path {full:?} in package"))?; + let mut bytes = Vec::new(); + entry.by_ref().take(MAX_TOTAL - total + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?; + total += bytes.len() as u64; + if total > MAX_TOTAL { + return Err(format!("the package unpacks to more than {} MiB", MAX_TOTAL >> 20)); + } + if rel == Path::new(SIGNATURE_FILE) { + signature = Some(serde_json::from_slice(&bytes).map_err(|e| format!("{SIGNATURE_FILE}: {e}"))?); + continue; + } + let to = dest.join(&rel); + if let Some(parent) = to.parent() { + std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + std::fs::write(&to, bytes).map_err(|e| e.to_string())?; + if rel == Path::new(MANIFEST_FILE) { + manifest = true; + } else { + files.push(rel); + } + } + if !manifest { + return Err(format!("the package has no {MANIFEST_FILE}")); + } + files.sort(); + Ok(Unpacked { files, signature }) +} + +// ---- index ------------------------------------------------------------------- + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct Index { + pub format: u32, + #[serde(default)] + pub publishers: Vec, + #[serde(default)] + pub plugins: Vec, + #[serde(default)] + pub revoked: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct Publisher { + /// Owns plugin ids `.…`. + pub id: String, + pub name: String, + pub keys: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct KeyEntry { + /// Ed25519 public key, base64. + pub key: String, + /// Packages signed with it are no longer trusted. + #[serde(default)] + pub revoked: bool, +} + +/// A published plugin version. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct IndexEntry { + pub id: String, + pub name: String, + pub version: String, + #[serde(default)] + pub description: String, + #[serde(default)] + pub authors: Vec, + pub publisher: String, + /// The package, relative to the index (or an absolute URL). + pub download: String, + /// [`package_digest`] of its contents. + pub digest: String, + #[serde(default)] + pub capabilities: Vec, +} + +/// A plugin (all versions when `versions` is empty) that must not run. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct Revocation { + pub id: String, + #[serde(default)] + pub versions: Vec, + pub reason: String, +} + +impl Index { + pub fn parse(text: &str) -> Result { + let index: Index = serde_json::from_str(text).map_err(|e| format!("index: {e}"))?; + if index.format != INDEX_FORMAT { + return Err(format!("index format {} is not supported (this IDE reads {INDEX_FORMAT})", index.format)); + } + Ok(index) + } + + /// The revocation that applies to `id` at `version`. + pub fn revocation(&self, id: &str, version: &str) -> Option<&Revocation> { + self.revoked.iter().find(|r| r.id == id && (r.versions.is_empty() || r.versions.iter().any(|v| v == version))) + } + + /// Whether `key` (base64) belongs to a publisher and was revoked. + pub fn key_revoked(&self, key: &str) -> bool { + self.publishers.iter().flat_map(|p| &p.keys).any(|k| k.key == key && k.revoked) + } + + /// The trusted publisher of a signed package: the signature is valid, its + /// key is one of the publisher's and not revoked, and the publisher owns + /// the plugin's id prefix. + pub fn verify(&self, sig: &PackageSignature, id: &str, version: &str, digest: &str) -> Result { + let publisher = self + .publishers + .iter() + .find(|p| p.id == sig.publisher) + .ok_or_else(|| format!("unknown publisher {:?}", sig.publisher))?; + let key = publisher + .keys + .iter() + .find(|k| k.key == sig.key) + .ok_or_else(|| format!("the key is not one of {}'s", publisher.name))?; + if key.revoked { + return Err(format!("{}'s signing key was revoked", publisher.name)); + } + if !id.starts_with(&format!("{}.", publisher.id)) { + return Err(format!("{} may only publish plugins named {}.*", publisher.name, publisher.id)); + } + sig.check(id, version, digest)?; + Ok(publisher.id.clone()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn package(dir: &Path) -> Vec { + std::fs::create_dir_all(dir.join("dist")).unwrap(); + std::fs::write(dir.join(MANIFEST_FILE), "id = \"acme.tools\"\nversion = \"1.0.0\"").unwrap(); + std::fs::write(dir.join("dist/plugin.wasm"), b"\0asm").unwrap(); + vec![PathBuf::from("dist/plugin.wasm")] + } + + fn index(key: &PublisherKey) -> Index { + Index { + format: INDEX_FORMAT, + publishers: vec![Publisher { + id: "acme".into(), + name: "ACME".into(), + keys: vec![KeyEntry { key: key.public_base64(), revoked: false }], + }], + plugins: Vec::new(), + revoked: vec![Revocation { + id: "acme.bad".into(), + versions: vec!["1.0.0".into()], + reason: "malware".into(), + }], + } + } + + #[test] + fn signed_packages_round_trip_and_tampering_is_caught() { + let tmp = tempfile::tempdir().unwrap(); + let src = tmp.path().join("src"); + let files = package(&src); + let digest = package_digest(&src, &files).unwrap(); + let key = PublisherKey::from_seed([7; 32]); + let sig = key.sign("acme", "acme.tools", "1.0.0", &digest); + let out = tmp.path().join("acme.tools-1.0.0.oiplugin"); + pack(&src, &files, &out, Some(&sig)).unwrap(); + + let dest = tmp.path().join("dest"); + let unpacked = unpack(&out, &dest).unwrap(); + assert_eq!(unpacked.files, files); + assert_eq!(package_digest(&dest, &unpacked.files).unwrap(), digest); + let index = index(&key); + assert_eq!(index.verify(unpacked.signature.as_ref().unwrap(), "acme.tools", "1.0.0", &digest).unwrap(), "acme"); + + // Changed bytes, another id, someone else's prefix, a revoked key. + assert!(index.verify(&sig, "acme.tools", "1.0.0", "0000").is_err()); + assert!(index.verify(&sig, "acme.tools", "1.0.1", &digest).is_err()); + let other = PublisherKey::from_seed([9; 32]).sign("acme", "acme.tools", "1.0.0", &digest); + assert!(index.verify(&other, "acme.tools", "1.0.0", &digest).unwrap_err().contains("not one of")); + let foreign = key.sign("acme", "evil.tools", "1.0.0", &digest); + assert!(index.verify(&foreign, "evil.tools", "1.0.0", &digest).unwrap_err().contains("acme.*")); + let mut revoked = index.clone(); + revoked.publishers[0].keys[0].revoked = true; + assert!(revoked.verify(&sig, "acme.tools", "1.0.0", &digest).unwrap_err().contains("revoked")); + assert!(revoked.key_revoked(&sig.key)); + assert_eq!(index.revocation("acme.bad", "1.0.0").unwrap().reason, "malware"); + assert!(index.revocation("acme.bad", "1.0.1").is_none()); + assert_eq!(PublisherKey::from_base64(&key.seed_base64()).unwrap().public_base64(), key.public_base64()); + } + + #[test] + fn unpacking_refuses_paths_leaving_the_package() { + let tmp = tempfile::tempdir().unwrap(); + let out = tmp.path().join("evil.oiplugin"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&out).unwrap()); + let o = zip::write::SimpleFileOptions::default(); + zip.start_file(MANIFEST_FILE, o).unwrap(); + zip.write_all(b"id = \"x\"").unwrap(); + zip.start_file("../outside.txt", o).unwrap(); + zip.write_all(b"x").unwrap(); + zip.finish().unwrap(); + let err = unpack(&out, &tmp.path().join("dest")).unwrap_err(); + assert!(err.contains("invalid path"), "{err}"); + assert!(!tmp.path().join("outside.txt").exists()); + assert!(Index::parse(r#"{"format": 2}"#).is_err()); + } + + fn zip_of(path: &Path, entries: &[(&str, &str)]) { + let mut zip = zip::ZipWriter::new(std::fs::File::create(path).unwrap()); + for (name, body) in entries { + zip.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(body.as_bytes()).unwrap(); + } + zip.finish().unwrap(); + } + + #[test] + fn a_zip_holds_the_package_at_its_root_or_in_its_only_folder() { + let tmp = tempfile::tempdir().unwrap(); + let manifest = "id = \"acme.tools\""; + let at_root = tmp.path().join("root.zip"); + zip_of(&at_root, &[(MANIFEST_FILE, manifest), ("dist/plugin.wasm", "w"), (".DS_Store", "x")]); + let got = unpack(&at_root, &tmp.path().join("a")).unwrap(); + assert_eq!(got.files, [PathBuf::from("dist/plugin.wasm")]); + + // What zipping the folder in Finder makes: the folder plus `__MACOSX`. + let folder = tmp.path().join("folder.zip"); + zip_of( + &folder, + &[ + ("acme-tools/plugin.toml", manifest), + ("acme-tools/dist/plugin.wasm", "w"), + ("__MACOSX/acme-tools/._plugin.toml", "x"), + ], + ); + let dest = tmp.path().join("b"); + let got = unpack(&folder, &dest).unwrap(); + assert_eq!(got.files, [PathBuf::from("dist/plugin.wasm")]); + assert!(dest.join(MANIFEST_FILE).is_file()); + assert!(!dest.join("__MACOSX").exists() && !dest.join("acme-tools").exists()); + + // Two folders, a manifest one level too deep, or none (an IntelliJ plugin): not a package. + for (name, entries) in [ + ("two.zip", &[("a/plugin.toml", manifest), ("b/x.txt", "x")][..]), + ("deep.zip", &[("a/b/plugin.toml", manifest)][..]), + ("intellij.zip", &[("my-plugin/lib/my-plugin.jar", "jar")][..]), + ] { + let path = tmp.path().join(name); + zip_of(&path, entries); + let err = unpack(&path, &tmp.path().join(name).with_extension("out")).unwrap_err(); + assert!(err.contains("is not an OpenIDEA plugin"), "{name}: {err}"); + } + } +} diff --git a/crates/ide-extension/src/point.rs b/crates/ide-extension/src/point.rs new file mode 100644 index 00000000..7a74ac0d --- /dev/null +++ b/crates/ide-extension/src/point.rs @@ -0,0 +1,175 @@ +//! The extension point contract (plan 4.1). + +use crate::capability::Capability; +use crate::manifest::{Manifest, check_relative}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +/// Where a contribution takes effect (plan 3, placement rules). +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub enum Placement { + /// Projected to the client (menus, keybindings, themes, icons). + Ui, + /// Takes effect on the machine the project is on (languages, LSP, run configurations). + Workspace, +} + +/// The package a declaration comes from, as extension points see it. +#[derive(Clone, Debug)] +pub struct Package { + pub manifest: Arc, + /// Package directory. + pub dir: PathBuf, + /// Hash of the package's files when they never change (an installed + /// copy): validated declarations are then reused from the + /// [`ContributionIndex`](crate::ContributionIndex). + pub digest: Option>, +} + +/// Largest single package file an extension point reads. +pub const MAX_PACKAGE_FILE: u64 = 8 << 20; + +impl Package { + pub fn new(manifest: Manifest, dir: PathBuf) -> Self { + Self { manifest: Arc::new(manifest), dir, digest: None } + } + + pub fn with_digest(mut self, digest: &str) -> Self { + self.digest = Some(digest.into()); + self + } + + pub fn id(&self) -> &str { + &self.manifest.id + } + + /// Resolves a package-relative path, refusing anything that leaves the + /// package (`..`, absolute paths, symlinks pointing outside). + pub fn resolve(&self, rel: &Path) -> Result { + check_relative(rel, "path")?; + let joined = self.dir.join(rel); + let real = joined.canonicalize().map_err(|_| format!("{}: no such file in the plugin", rel.display()))?; + let root = self.dir.canonicalize().map_err(|e| format!("plugin directory: {e}"))?; + if !real.starts_with(&root) { + return Err(format!("{}: points outside the plugin", rel.display())); + } + Ok(real) + } + + pub fn read_bytes(&self, rel: &Path) -> Result, String> { + let real = self.resolve(rel)?; + let meta = std::fs::metadata(&real).map_err(|e| format!("{}: {e}", rel.display()))?; + if !meta.is_file() { + return Err(format!("{}: not a file", rel.display())); + } + if meta.len() > MAX_PACKAGE_FILE { + return Err(format!("{}: larger than {} MiB", rel.display(), MAX_PACKAGE_FILE >> 20)); + } + std::fs::read(&real).map_err(|e| format!("{}: {e}", rel.display())) + } + + pub fn read_text(&self, rel: &Path) -> Result { + String::from_utf8(self.read_bytes(rel)?).map_err(|_| format!("{}: not UTF-8 text", rel.display())) + } +} + +/// Undoes one committed contribution. Dropping without [`dispose`](Self::dispose) also disposes. +#[must_use = "dropping a Disposable undoes the contribution"] +pub struct Disposable(Option>); + +impl Disposable { + pub fn new(f: impl FnOnce() + Send + 'static) -> Self { + Self(Some(Box::new(f))) + } + + /// A contribution with nothing to undo. + pub fn noop() -> Self { + Self(None) + } + + pub fn dispose(mut self) { + if let Some(f) = self.0.take() { + f(); + } + } +} + +impl Drop for Disposable { + fn drop(&mut self) { + if let Some(f) = self.0.take() { + f(); + } + } +} + +impl std::fmt::Debug for Disposable { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Disposable") + } +} + +pub type Commit = Box Result + Send>; + +/// A validated declaration, ready to take effect. +pub struct Prepared { + /// Capabilities this declaration needs (a language with an LSP → `process:`). + pub capabilities: Vec, + /// Package files the declaration references (copied on install). + pub files: Vec, + /// Identity within the point: a later declaration with the same key replaces + /// the earlier one of the same plugin (re-registering a command). + pub key: Option, + /// User-facing one-liner for the plugin details page ("Insert Date"). + pub label: String, + /// Makes it take effect. Must not fail for reasons `prepare` could have checked. + pub commit: Commit, +} + +impl Prepared { + pub fn new(label: impl Into, commit: impl FnOnce() -> Result + Send + 'static) -> Self { + Self { capabilities: Vec::new(), files: Vec::new(), key: None, label: label.into(), commit: Box::new(commit) } + } + + pub fn key(mut self, key: impl Into) -> Self { + self.key = Some(key.into()); + self + } + + pub fn file(mut self, path: impl Into) -> Self { + self.files.push(path.into()); + self + } + + pub fn capability(mut self, cap: Capability) -> Self { + if !self.capabilities.contains(&cap) { + self.capabilities.push(cap); + } + self + } +} + +impl std::fmt::Debug for Prepared { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Prepared").field("key", &self.key).field("label", &self.label).finish_non_exhaustive() + } +} + +/// A kind of contribution (`contributes.` in the manifest). Implemented by +/// the crate that owns the feature; registered once in an [`crate::ExtensionRegistry`]. +pub trait ExtensionPoint: Send + Sync { + /// `"languages"`, `"iconThemes"`, … + fn id(&self) -> &'static str; + + fn placement(&self) -> Placement; + + /// Parses and validates one declaration without side effects, and works + /// out the capabilities it needs. `Ui` points validate completely here: the + /// client's projection is not allowed to fail. + fn prepare(&self, pkg: &Package, decl: toml::Value) -> Result; +} + +/// Deserializes a declaration with serde, prefixing errors with the point id. +pub fn decode(point: &str, decl: toml::Value) -> Result { + decl.try_into().map_err(|e: toml::de::Error| format!("contributes.{point}: {}", e.message())) +} diff --git a/crates/ide-extension/src/registry.rs b/crates/ide-extension/src/registry.rs new file mode 100644 index 00000000..e8630fd8 --- /dev/null +++ b/crates/ide-extension/src/registry.rs @@ -0,0 +1,305 @@ +//! Extension points plus the contributions committed to them, accounted per plugin. + +use crate::capability::Capability; +use crate::point::{Disposable, ExtensionPoint, Package, Placement, Prepared}; +use parking_lot::{Mutex, RwLock}; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::Arc; + +/// A contribution as the plugin details page lists it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ContributionInfo { + pub point: String, + pub label: String, +} + +struct Entry { + point: &'static str, + key: Option, + label: String, + disposable: Disposable, +} + +/// Every declaration of a package, validated; nothing has taken effect yet. +pub struct PreparedSet { + pub plugin: String, + /// Union of what the declarations need (beyond the manifest's own list). + pub capabilities: Vec, + /// Package files the declarations reference. + pub files: Vec, + /// Declarations for extension points this host does not know (skipped). + pub warnings: Vec, + items: Vec<(&'static str, Prepared)>, +} + +impl PreparedSet { + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } + + pub fn len(&self) -> usize { + self.items.len() + } +} + +impl std::fmt::Debug for PreparedSet { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PreparedSet") + .field("plugin", &self.plugin) + .field("items", &self.items.len()) + .field("warnings", &self.warnings) + .finish() + } +} + +#[derive(Default)] +pub struct ExtensionRegistry { + points: RwLock>>, + /// plugin id → its contributions in commit order. + entries: Mutex>>, +} + +impl ExtensionRegistry { + pub fn new() -> Self { + Self::default() + } + + /// Adds an extension point. Ids are unique. + pub fn register(&self, point: Arc) -> Result<(), String> { + let id = point.id(); + crate::manifest::validate_point_id(id)?; + let mut points = self.points.write(); + if points.contains_key(id) { + return Err(format!("extension point {id:?} is already registered")); + } + points.insert(id, point); + Ok(()) + } + + pub fn point_ids(&self) -> Vec<&'static str> { + self.points.read().keys().copied().collect() + } + + pub fn placement(&self, point: &str) -> Option { + self.points.read().get(point).map(|p| p.placement()) + } + + fn point(&self, id: &str) -> Option> { + self.points.read().get(id).cloned() + } + + /// Validates every `contributes.` declaration of `pkg`. Fails as a + /// whole on the first invalid declaration; unknown points are skipped with + /// a warning (forward compatibility). + pub fn prepare(&self, pkg: &Package) -> Result { + let mut set = PreparedSet { + plugin: pkg.id().to_owned(), + capabilities: Vec::new(), + files: Vec::new(), + warnings: Vec::new(), + items: Vec::new(), + }; + for point_id in pkg.manifest.contributes.keys() { + let Some(point) = self.point(point_id) else { + let msg = format!("contributes.{point_id}: not supported by this version of the IDE; skipped"); + tracing::warn!(plugin = %pkg.id(), "{msg}"); + set.warnings.push(msg); + continue; + }; + for (i, decl) in pkg.manifest.declarations(point_id).into_iter().enumerate() { + let prepared = point + .prepare(pkg, decl) + .map_err(|e| format!("contributes.{point_id}[{i}]: {}", strip_prefix(&e, point_id)))?; + for cap in &prepared.capabilities { + if !set.capabilities.contains(cap) { + set.capabilities.push(cap.clone()); + } + } + for f in &prepared.files { + if !set.files.contains(f) { + set.files.push(f.clone()); + } + } + set.items.push((point.id(), prepared)); + } + } + Ok(set) + } + + /// Makes a prepared set take effect, all or nothing: if one commit fails, + /// the ones before it are disposed in reverse order. + pub fn commit(&self, set: PreparedSet) -> Result<(), String> { + let mut committed: Vec = Vec::with_capacity(set.items.len()); + for (point, prepared) in set.items { + let Prepared { key, label, commit, .. } = prepared; + match commit() { + Ok(disposable) => committed.push(Entry { point, key, label, disposable }), + Err(e) => { + tracing::error!(plugin = %set.plugin, "contributes.{point}: commit failed: {e}"); + while let Some(entry) = committed.pop() { + entry.disposable.dispose(); + } + return Err(format!("contributes.{point}: {e}")); + } + } + } + let replaced = { + let mut entries = self.entries.lock(); + let list = entries.entry(set.plugin).or_default(); + let mut replaced = Vec::new(); + for new in &committed { + if let Some(key) = &new.key + && let Some(pos) = list.iter().position(|e| e.point == new.point && e.key.as_ref() == Some(key)) + { + replaced.push(list.remove(pos)); + } + } + list.extend(committed); + replaced + }; + for old in replaced.into_iter().rev() { + old.disposable.dispose(); + } + Ok(()) + } + + /// Withdraws everything `plugin` contributed, newest first. + pub fn dispose_plugin(&self, plugin: &str) -> bool { + let list = self.entries.lock().remove(plugin).unwrap_or_default(); + let any = !list.is_empty(); + for entry in list.into_iter().rev() { + entry.disposable.dispose(); + } + any + } + + pub fn contributions(&self, plugin: &str) -> Vec { + self.entries + .lock() + .get(plugin) + .map(|list| { + list.iter().map(|e| ContributionInfo { point: e.point.into(), label: e.label.clone() }).collect() + }) + .unwrap_or_default() + } + + /// How many contributions `plugin` has at `point`. + pub fn count(&self, plugin: &str, point: &str) -> usize { + self.entries.lock().get(plugin).map_or(0, |list| list.iter().filter(|e| e.point == point).count()) + } + + /// Plugins with at least one contribution. + pub fn plugins(&self) -> Vec { + self.entries.lock().iter().filter(|(_, l)| !l.is_empty()).map(|(id, _)| id.clone()).collect() + } +} + +fn strip_prefix<'a>(e: &'a str, point: &str) -> &'a str { + e.strip_prefix(&format!("contributes.{point}: ")).unwrap_or(e) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::manifest::Manifest; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Records live items in a shared list; `fail = true` makes commit fail. + struct Recording { + id: &'static str, + live: Arc>>, + commits: Arc, + } + + impl ExtensionPoint for Recording { + fn id(&self) -> &'static str { + self.id + } + fn placement(&self) -> Placement { + Placement::Ui + } + fn prepare(&self, _pkg: &Package, decl: toml::Value) -> Result { + let name = decl.get("name").and_then(|v| v.as_str()).ok_or("missing name")?.to_owned(); + let fail = decl.get("fail").and_then(|v| v.as_bool()).unwrap_or(false); + let (live, commits) = (self.live.clone(), self.commits.clone()); + let label = name.clone(); + let mut p = Prepared::new(label, move || { + commits.fetch_add(1, Ordering::SeqCst); + if fail { + return Err("boom".into()); + } + live.lock().push(name.clone()); + Ok(Disposable::new(move || live.lock().retain(|n| *n != name))) + }); + if let Some(f) = decl.get("file").and_then(|v| v.as_str()) { + p = p.file(f); + } + if decl.get("key").and_then(|v| v.as_bool()).unwrap_or(false) { + p = p.key("k"); + } + Ok(p) + } + } + + fn setup() -> (ExtensionRegistry, Arc>>) { + let reg = ExtensionRegistry::new(); + let live = Arc::new(Mutex::new(Vec::new())); + let commits = Arc::new(AtomicUsize::new(0)); + reg.register(Arc::new(Recording { id: "things", live: live.clone(), commits: commits.clone() })).unwrap(); + reg.register(Arc::new(Recording { id: "others", live: live.clone(), commits })).unwrap(); + (reg, live) + } + + fn pkg(contributes: &str) -> Package { + let src = format!("id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\n{contributes}"); + Package::new(Manifest::parse(&src).unwrap(), PathBuf::from("/nonexistent")) + } + + #[test] + fn commits_and_disposes_per_plugin() { + let (reg, live) = setup(); + assert!( + reg.register(Arc::new(Recording { id: "things", live: live.clone(), commits: Default::default() })) + .is_err() + ); + let p = pkg( + "[[contributes.things]]\nname = \"a\"\nfile = \"x.json\"\n[[contributes.things]]\nname = \"b\"\n[contributes.others]\nname = \"c\"", + ); + let set = reg.prepare(&p).unwrap(); + assert_eq!(set.len(), 3); + assert_eq!(set.files, [PathBuf::from("x.json")]); + assert!(live.lock().is_empty(), "prepare has no side effects"); + reg.commit(set).unwrap(); + assert_eq!(*live.lock(), ["c", "a", "b"]); + assert_eq!(reg.count("p", "things"), 2); + assert_eq!(reg.contributions("p").len(), 3); + assert!(reg.dispose_plugin("p")); + assert!(live.lock().is_empty()); + } + + #[test] + fn a_failed_commit_rolls_back() { + let (reg, live) = setup(); + let p = pkg("[[contributes.things]]\nname = \"a\"\n[[contributes.things]]\nname = \"b\"\nfail = true"); + let err = reg.commit(reg.prepare(&p).unwrap()).unwrap_err(); + assert!(err.contains("boom")); + assert!(live.lock().is_empty(), "a was undone"); + assert!(reg.contributions("p").is_empty()); + } + + #[test] + fn invalid_declarations_fail_prepare_and_unknown_points_warn() { + let (reg, _) = setup(); + let err = reg.prepare(&pkg("[[contributes.things]]\nnope = 1")).unwrap_err(); + assert_eq!(err, "contributes.things[0]: missing name"); + let set = + reg.prepare(&pkg("[[contributes.futureThing]]\nx = 1\n[[contributes.things]]\nname = \"a\"")).unwrap(); + assert_eq!(set.len(), 1); + assert_eq!(set.warnings.len(), 1); + assert!(set.warnings[0].contains("futureThing")); + } +} diff --git a/crates/ide-extension/src/ui.rs b/crates/ide-extension/src/ui.rs new file mode 100644 index 00000000..9a59029b --- /dev/null +++ b/crates/ide-extension/src/ui.rs @@ -0,0 +1,247 @@ +//! UI contributions: validated declarations projected to the client. +//! +//! A `Ui` extension point validates a declaration completely in Rust and +//! commits it as JSON into the [`UiStore`]; the client receives the store's +//! snapshot and projects each item onto an existing `register*` function +//! (`defineUiPoint` in `src/features/plugins/projection.ts`). Large payloads +//! (icon SVGs) go into the store's assets and are fetched on demand. + +use crate::index::ContributionIndex; +use crate::point::{Disposable, ExtensionPoint, Package, Placement, Prepared}; +use parking_lot::RwLock; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// One projected declaration. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct UiContribution { + pub plugin_id: String, + /// Extension point id (`commands`, `iconThemes`, …). + pub point: String, + /// Stable within (plugin, point): the client keys its registrations on it. + pub key: String, + /// The validated declaration, shaped by the point. + #[specta(type = specta_typescript::Unknown)] + pub decl: serde_json::Value, +} + +struct Item { + seq: u64, + contribution: UiContribution, +} + +/// Committed UI contributions of all plugins. +#[derive(Default)] +pub struct UiStore { + items: RwLock>, + /// (plugin, asset id) → content. + assets: RwLock>>, + seq: AtomicU64, + revision: AtomicU64, + index: RwLock>>, +} + +impl UiStore { + pub fn new() -> Arc { + Arc::new(Self::default()) + } + + /// Adds an item; the returned disposable removes it. + pub fn insert(self: &Arc, contribution: UiContribution) -> Disposable { + let seq = self.seq.fetch_add(1, Ordering::Relaxed); + self.items.write().push(Item { seq, contribution }); + self.revision.fetch_add(1, Ordering::Release); + let store = Arc::downgrade(self); + Disposable::new(move || { + if let Some(store) = store.upgrade() { + store.items.write().retain(|i| i.seq != seq); + store.revision.fetch_add(1, Ordering::Release); + } + }) + } + + /// Stores assets of a plugin (ids are unique per plugin; later ones replace). + pub fn insert_assets(self: &Arc, plugin: &str, assets: Vec<(String, String)>) -> Disposable { + let keys: Vec<(String, String)> = assets.iter().map(|(id, _)| (plugin.to_owned(), id.clone())).collect(); + { + let mut map = self.assets.write(); + for (id, content) in assets { + map.insert((plugin.to_owned(), id), Arc::from(content)); + } + } + let store = Arc::downgrade(self); + Disposable::new(move || { + if let Some(store) = store.upgrade() { + let mut map = store.assets.write(); + for k in keys { + map.remove(&k); + } + } + }) + } + + pub fn asset(&self, plugin: &str, id: &str) -> Option> { + self.assets.read().get(&(plugin.to_owned(), id.to_owned())).cloned() + } + + /// Assets of `plugin` whose id starts with `prefix`. + pub fn assets_with_prefix(&self, plugin: &str, prefix: &str) -> Vec<(String, Arc)> { + self.assets + .read() + .range((plugin.to_owned(), prefix.to_owned())..) + .take_while(|((p, id), _)| p == plugin && id.starts_with(prefix)) + .map(|((_, id), v)| (id.clone(), v.clone())) + .collect() + } + + /// Where [`UiPoint`]s keep validated declarations of installed packages. + pub fn set_index(&self, index: Option>) { + *self.index.write() = index; + } + + /// Bumped on every change: clients compare it to skip re-projection. + pub fn revision(&self) -> u64 { + self.revision.load(Ordering::Acquire) + } + + pub fn snapshot(&self) -> Vec { + self.items.read().iter().map(|i| i.contribution.clone()).collect() + } + + /// Items of one point, optionally of one plugin. + pub fn items(&self, point: &str, plugin: Option<&str>) -> Vec { + self.items + .read() + .iter() + .filter(|i| i.contribution.point == point && plugin.is_none_or(|p| i.contribution.plugin_id == p)) + .map(|i| i.contribution.clone()) + .collect() + } +} + +/// What a [`UiPoint`]'s validator produces for one declaration. +#[derive(Debug, Serialize, Deserialize)] +pub struct UiDecl { + pub key: String, + pub label: String, + pub json: serde_json::Value, + /// Package files referenced (copied on install). + pub files: Vec, + /// Large validated payloads fetched separately by the client. + pub assets: Vec<(String, String)>, +} + +impl UiDecl { + pub fn new(key: impl Into, label: impl Into, json: serde_json::Value) -> Self { + Self { key: key.into(), label: label.into(), json, files: Vec::new(), assets: Vec::new() } + } +} + +type Validate = dyn Fn(&Package, toml::Value) -> Result + Send + Sync; + +/// A `Ui` extension point defined by a validator: committing stores the +/// validated JSON (and assets) in the [`UiStore`]. Most UI contribution types +/// (menus, keybindings, status bar items, icon themes) are one of these. +pub struct UiPoint { + id: &'static str, + store: Arc, + validate: Box, +} + +impl UiPoint { + pub fn new( + id: &'static str, + store: Arc, + validate: impl Fn(&Package, toml::Value) -> Result + Send + Sync + 'static, + ) -> Self { + Self { id, store, validate: Box::new(validate) } + } +} + +impl ExtensionPoint for UiPoint { + fn id(&self) -> &'static str { + self.id + } + + fn placement(&self) -> Placement { + Placement::Ui + } + + fn prepare(&self, pkg: &Package, decl: toml::Value) -> Result { + let index = pkg.digest.as_ref().and_then(|_| self.store.index.read().clone()); + let ui = match index.as_ref().and_then(|i| i.get(pkg, self.id, &decl)) { + Some(ui) => ui, + None => match &index { + Some(i) => { + let ui = (self.validate)(pkg, decl.clone())?; + i.put(pkg, self.id, &decl, &ui); + ui + } + None => (self.validate)(pkg, decl)?, + }, + }; + let UiDecl { key, label, json, files, assets } = ui; + let store = self.store.clone(); + let contribution = + UiContribution { plugin_id: pkg.id().to_owned(), point: self.id.to_owned(), key: key.clone(), decl: json }; + let plugin = pkg.id().to_owned(); + let mut prepared = Prepared::new(label, move || { + let item = store.insert(contribution); + if assets.is_empty() { + return Ok(item); + } + let assets = store.insert_assets(&plugin, assets); + Ok(Disposable::new(move || { + item.dispose(); + assets.dispose(); + })) + }) + .key(key); + prepared.files = files; + Ok(prepared) + } +} + +/// TOML declaration → JSON for the client. +pub fn to_json(v: &toml::Value) -> serde_json::Value { + serde_json::to_value(v).unwrap_or(serde_json::Value::Null) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::manifest::Manifest; + use crate::registry::ExtensionRegistry; + + #[test] + fn ui_point_projects_into_the_store() { + let store = UiStore::new(); + let reg = ExtensionRegistry::new(); + reg.register(Arc::new(UiPoint::new("badges", store.clone(), |_pkg, decl| { + let text = decl.get("text").and_then(|v| v.as_str()).ok_or("missing text")?.to_owned(); + let mut d = UiDecl::new(text.clone(), text.clone(), serde_json::json!({ "text": text })); + d.assets.push((format!("badge/{text}"), "".into())); + Ok(d) + }))) + .unwrap(); + let src = "id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\n\ + [[contributes.badges]]\ntext = \"hi\""; + let pkg = Package::new(Manifest::parse(src).unwrap(), PathBuf::from("/x")); + let rev = store.revision(); + reg.commit(reg.prepare(&pkg).unwrap()).unwrap(); + assert!(store.revision() > rev); + let items = store.items("badges", Some("p")); + assert_eq!(items.len(), 1); + assert_eq!(items[0].decl["text"], "hi"); + assert_eq!(store.asset("p", "badge/hi").as_deref(), Some("")); + assert_eq!(store.assets_with_prefix("p", "badge/").len(), 1); + reg.dispose_plugin("p"); + assert!(store.snapshot().is_empty()); + assert!(store.asset("p", "badge/hi").is_none()); + } +} diff --git a/crates/ide-extension/src/when.rs b/crates/ide-extension/src/when.rs new file mode 100644 index 00000000..98cd3c93 --- /dev/null +++ b/crates/ide-extension/src/when.rs @@ -0,0 +1,136 @@ +//! Syntax check for `when` clauses in UI declarations. The client evaluates +//! them (`src/platform/context.ts`); validating here keeps the client's +//! projection from failing. Grammar (same as the client): +//! +//! ```text +//! expr := or ; or := and ("||" and)* ; and := unary ("&&" unary)* +//! unary := "!" unary | "(" expr ")" | cmp ; cmp := key (("==" | "!=") value)? +//! ``` + +const MAX_LEN: usize = 512; + +#[derive(Debug, PartialEq)] +enum Tok<'a> { + Id(&'a str), + Str, + Op(&'a str), +} + +fn tokenize(src: &str) -> Result>, String> { + let mut out = Vec::new(); + let b = src.as_bytes(); + let mut i = 0; + while i < b.len() { + let c = b[i] as char; + if c.is_whitespace() { + i += 1; + } else if ["&&", "||", "==", "!="].iter().any(|op| src[i..].starts_with(op)) { + out.push(Tok::Op(&src[i..i + 2])); + i += 2; + } else if matches!(c, '!' | '(' | ')') { + out.push(Tok::Op(&src[i..i + 1])); + i += 1; + } else if c == '\'' || c == '"' { + let end = src[i + 1..].find(c).ok_or_else(|| format!("unterminated string in when clause: {src}"))?; + out.push(Tok::Str); + i += end + 2; + } else { + let len = src[i..] + .find(|ch: char| !(ch.is_alphanumeric() || matches!(ch, '_' | '.' | '-' | ':' | '/'))) + .unwrap_or(src.len() - i); + if len == 0 { + return Err(format!("unexpected '{c}' in when clause: {src}")); + } + out.push(Tok::Id(&src[i..i + len])); + i += len; + } + } + Ok(out) +} + +/// Checks a `when` clause; empty means "always". +pub fn validate_when(src: &str) -> Result<(), String> { + if src.len() > MAX_LEN { + return Err(format!("when clause longer than {MAX_LEN} bytes")); + } + if src.trim().is_empty() { + return Ok(()); + } + let toks = tokenize(src)?; + let mut p = 0; + parse_or(&toks, &mut p, src)?; + if p != toks.len() { + return Err(format!("unexpected token in when clause: {src}")); + } + Ok(()) +} + +fn parse_or(t: &[Tok], p: &mut usize, src: &str) -> Result<(), String> { + parse_and(t, p, src)?; + while t.get(*p) == Some(&Tok::Op("||")) { + *p += 1; + parse_and(t, p, src)?; + } + Ok(()) +} + +fn parse_and(t: &[Tok], p: &mut usize, src: &str) -> Result<(), String> { + parse_unary(t, p, src)?; + while t.get(*p) == Some(&Tok::Op("&&")) { + *p += 1; + parse_unary(t, p, src)?; + } + Ok(()) +} + +fn parse_unary(t: &[Tok], p: &mut usize, src: &str) -> Result<(), String> { + match t.get(*p) { + Some(Tok::Op("!")) => { + *p += 1; + parse_unary(t, p, src) + } + Some(Tok::Op("(")) => { + *p += 1; + parse_or(t, p, src)?; + if t.get(*p) != Some(&Tok::Op(")")) { + return Err(format!("missing ')' in when clause: {src}")); + } + *p += 1; + Ok(()) + } + Some(Tok::Id(_)) => { + *p += 1; + if matches!(t.get(*p), Some(Tok::Op("==" | "!="))) { + *p += 1; + match t.get(*p) { + Some(Tok::Id(_) | Tok::Str) => *p += 1, + _ => return Err(format!("missing value after comparison in when clause: {src}")), + } + } + Ok(()) + } + _ => Err(format!("expected a context key in when clause: {src}")), + } +} + +#[cfg(test)] +mod tests { + use super::validate_when; + + #[test] + fn accepts_the_client_grammar() { + for ok in [ + "", + "editorFocus", + "editorLang == rust", + "editorLang != 'rust' && !readOnly", + "(a || b) && toolWindow.project.active", + "resourceScheme == file:/x", + ] { + assert!(validate_when(ok).is_ok(), "{ok}"); + } + for bad in ["a &&", "(a", "a == ", "== a", "a b", "a $ b", "'x", "!()"] { + assert!(validate_when(bad).is_err(), "{bad}"); + } + } +} diff --git a/crates/ide-host/Cargo.toml b/crates/ide-host/Cargo.toml index 6f2c1ce5..e95aee03 100644 --- a/crates/ide-host/Cargo.toml +++ b/crates/ide-host/Cargo.toml @@ -30,15 +30,23 @@ ide-terminal.workspace = true ide-run.workspace = true ide-sdk.workspace = true ide-http.workspace = true +reqwest.workspace = true +ignore.workspace = true +base64.workspace = true +getrandom = "0.3" +globset.workspace = true ide-db.workspace = true ide-ssh.workspace = true ide-remote.workspace = true ide-jsonrpc.workspace = true ide-agent.workspace = true ide-notebook.workspace = true +ide-extension.workspace = true +ide-plugin.workspace = true ide-tools = { path = "../ide-tools" } serde.workspace = true serde_json.workspace = true +toml.workspace = true specta.workspace = true specta-typescript.workspace = true tokio = { workspace = true, features = ["io-std"] } @@ -53,9 +61,15 @@ tempfile.workspace = true [dev-dependencies] ide-ssh = { workspace = true, features = ["testing"] } tokio = { workspace = true, features = ["rt-multi-thread", "macros", "io-util", "test-util"] } +criterion = { version = "0.5", default-features = false } +zip.workspace = true [target.'cfg(unix)'.dependencies] rustix = { version = "1.1", features = ["fs", "process"] } [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] } + +[[bench]] +name = "plugins" +harness = false diff --git a/crates/ide-host/benches/plugins.rs b/crates/ide-host/benches/plugins.rs new file mode 100644 index 00000000..c7ba4f6c --- /dev/null +++ b/crates/ide-host/benches/plugins.rs @@ -0,0 +1,149 @@ +//! `cargo bench -p ide-host`: the plugin runtime budgets, checked by `pnpm perf:rust` against +//! `perf/budgets.json` › rust (`plugins/…`). +//! +//! - `load_50`: start-up load of 50 installed plugins (20 with code, 10 +//! languages with a syntax provider, 10 icon themes, 10 declarations only), +//! from the contribution index; no Wasm is instantiated. +//! - `cold_activation`: an idle-reclaimed plugin's next command: activation +//! from the precompiled component plus the call. +//! - `syntax_highlights_2k_lines`: an edit-path call (Solidity highlighting). + +use criterion::{Criterion, black_box, criterion_group, criterion_main}; +use ide_core::LanguageId; +use ide_host::plugins::{Consent, PluginHost}; +use ide_plugin::{Invocation, Limits}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +fn repo() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../..").canonicalize().unwrap() +} + +fn copy_dir(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for e in std::fs::read_dir(from).unwrap().flatten() { + let name = e.file_name(); + if matches!(name.to_str(), Some("target" | "src" | "Cargo.lock" | ".gitignore")) { + continue; + } + let dst = to.join(&name); + if e.path().is_dir() { copy_dir(&e.path(), &dst) } else { std::fs::copy(e.path(), &dst).map(|_| ()).unwrap() } + } +} + +/// A copy of `src` installed under a new id (and new language / theme ids). +fn variant(work: &Path, src: &Path, n: usize, rename: &[(&str, String)]) -> PathBuf { + let dir = work.join(format!("pkg{n}")); + copy_dir(src, &dir); + for file in ["plugin.toml", "languages/solidity.toml"] { + let path = dir.join(file); + if let Ok(mut text) = std::fs::read_to_string(&path) { + for (from, to) in rename { + text = text.replace(from, to); + } + std::fs::write(&path, text).unwrap(); + } + } + dir +} + +fn sink() -> Arc { + Arc::new(|_: Option<&str>, _| {}) +} + +fn install_50(plugins: &Path, work: &Path) { + let host = PluginHost::new(plugins.to_path_buf(), sink(), Limits::default()).unwrap(); + host.load_all(); + let root = repo(); + let mut n = 0; + let mut install = |src: PathBuf, rename: Vec<(&str, String)>| { + let pkg = variant(work, &src, n, &rename); + n += 1; + host.install_from_dir(&pkg, &Consent::default()).unwrap(); + }; + for i in 0..20 { + install( + root.join("crates/ide-plugin/tests/fixtures/hello"), + vec![("id = \"hello\"", format!("id = \"bench.hello{i}\""))], + ); + } + for i in 0..10 { + install( + root.join("plugins/official/solidity"), + vec![ + ("openidea.solidity", format!("bench.solidity{i}")), + ("id = \"solidity\"", format!("id = \"solidity{i}\"")), + ("extensions = [\"sol\"]", format!("extensions = [\"sol{i}\"]")), + ("on-language:solidity", format!("on-language:solidity{i}")), + ("id = \"forge-", format!("id = \"f{i}-")), + ("id = \"hardhat-", format!("id = \"h{i}-")), + ], + ); + } + for i in 0..10 { + install( + root.join("plugins/official/material-icons"), + vec![ + ("openidea.material-icons", format!("bench.icons{i}")), + ("id = \"material\"", format!("id = \"material{i}\"")), + ], + ); + } + for i in 0..10 { + let dir = work.join(format!("static{i}")); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("plugin.toml"), + format!( + "id = \"bench.static{i}\"\nname = \"Static {i}\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\n\ + [[contributes.commands]]\nid = \"a\"\ntitle = \"Static {i}: A\"\nwhen = \"editorLang == rust\"\n" + ), + ) + .unwrap(); + host.install_from_dir(&dir, &Consent::default()).unwrap(); + } +} + +fn bench(c: &mut Criterion) { + let tmp = tempfile::tempdir().unwrap(); + let plugins = tmp.path().join("plugins"); + install_50(&plugins, &tmp.path().join("work")); + + let mut g = c.benchmark_group("plugins"); + g.sample_size(20); + g.bench_function("load_50", |b| { + b.iter(|| { + let host = PluginHost::new(plugins.clone(), sink(), Limits::default()).unwrap(); + host.load_all(); + assert_eq!(host.instances(), 0, "start-up instantiates no Wasm"); + black_box(host.list(None).plugins.len()) + }) + }); + + let limits = Limits { idle_timeout: Some(Duration::ZERO), ..Limits::default() }; + let host = Arc::new(PluginHost::new(plugins.clone(), sink(), limits).unwrap()); + host.load_all(); + host.warm_component_cache(); + g.bench_function("cold_activation", |b| { + b.iter(|| { + host.tick(); + // Fails for want of an editor, after activating and running. + let r = host.run_command("bench.hello0", "word-count", None, Invocation::default()); + black_box(r.is_err()) + }) + }); + + let provider = host.syntax_provider(); + let lang = LanguageId::new("solidity0"); + let unit = "contract Token {\n uint256 public total;\n mapping(address => uint256) balances;\n event Sent(address to, uint256 v);\n function send(address to, uint256 v) public returns (bool) {\n // move funds\n balances[to] += v;\n emit Sent(to, v);\n return true;\n }\n}\n"; + let text = unit.repeat(2000 / unit.lines().count()); + assert!(provider.highlights(&lang, &text).is_some()); + g.bench_function("syntax_highlights_2k_lines", |b| { + b.iter(|| black_box(provider.highlights(&lang, &text).map(|t| t.len()))) + }); + g.finish(); +} + +criterion_group!(benches, bench); +criterion_main!(benches); diff --git a/crates/ide-host/src/bin/openidea-plugin/main.rs b/crates/ide-host/src/bin/openidea-plugin/main.rs new file mode 100644 index 00000000..99b73630 --- /dev/null +++ b/crates/ide-host/src/bin/openidea-plugin/main.rs @@ -0,0 +1,624 @@ +//! `openidea-plugin`: scaffolds, builds, checks and links OpenIDEA plugins. +//! +//! ```text +//! openidea-plugin new [--template command|theme|icon-theme|language] [--id ID] [--name NAME] [--sdk PATH] +//! openidea-plugin build [dir] [--debug] # cargo → dist/plugin.wasm, then `check` +//! openidea-plugin check [dir] # validate the package as the IDE would install it +//! openidea-plugin link [dir] # load the folder in the IDE without installing it +//! openidea-plugin unlink [dir] +//! openidea-plugin links # list linked folders +//! openidea-plugin keygen # a publisher's Ed25519 key +//! openidea-plugin pack [dir] [--key F --publisher ID] [--out FILE] # -.oiplugin +//! openidea-plugin index --publisher ID --name NAME --key F # marketplace index.json +//! ``` +//! +//! `link` writes `links.json` in the IDE's plugins directory +//! (`$OPENIDEA_PLUGINS_DIR`, or the app data directory); the IDE picks the +//! change up when Settings › Plugins is opened or refreshed. Linked plugins +//! are re-read from the folder, so `build` + refresh is the edit loop. + +mod templates; + +use ide_extension::{Manifest, validate_plugin_id}; +use ide_host::plugins::PluginHost; +use ide_plugin::{Limits, PluginEngine}; +use std::path::{Path, PathBuf}; +use std::process::{Command, ExitCode}; +use std::sync::Arc; + +const USAGE: &str = "\ +usage: openidea-plugin [options] + +commands: + new [--template T] [--id ID] [--name NAME] [--sdk PATH] + create a plugin; T = command (default), theme, icon-theme, language + build [dir] [--debug] compile a Rust plugin to dist/plugin.wasm and check it + check [dir] validate the package as the IDE would install it + link [dir] load the folder in the IDE without installing it + unlink [dir] stop loading a linked folder + links list linked folders + keygen create a publisher signing key (keep the file secret) + pack [dir] [--key F --publisher ID] [--out FILE] + write -.oiplugin, signed with the key + index --publisher ID --name NAME --key F [--out FILE] + write the marketplace index.json for the packages in dir + +environment: + OPENIDEA_PLUGINS_DIR the IDE's plugins directory (default: the app data directory)"; + +fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + let result = match args.first().map(String::as_str) { + Some("new") => cmd_new(&args[1..]), + Some("build") => cmd_build(&args[1..]), + Some("check") => dir_arg(&args[1..]).and_then(|d| check(&d)), + Some("link") => dir_arg(&args[1..]).and_then(|d| link(&d, true)), + Some("unlink") => dir_arg(&args[1..]).and_then(|d| link(&d, false)), + Some("links") => list_links(), + Some("keygen") => cmd_keygen(&args[1..]), + Some("pack") => cmd_pack(&args[1..]), + Some("index") => cmd_index(&args[1..]), + Some("--version" | "-V") => { + println!("openidea-plugin {} (plugin API {})", env!("CARGO_PKG_VERSION"), ide_extension::ENGINE_VERSION); + Ok(()) + } + Some("help" | "--help" | "-h") | None => { + println!("{USAGE}"); + Ok(()) + } + Some(other) => Err(format!("unknown command {other:?}\n\n{USAGE}")), + }; + match result { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("error: {e}"); + ExitCode::FAILURE + } + } +} + +/// Splits `args` into positionals and `--flag value` / `--switch` options. +struct Args { + positional: Vec, + options: Vec<(String, Option)>, +} + +impl Args { + fn parse(args: &[String], switches: &[&str], valued: &[&str]) -> Result { + let mut out = Args { positional: Vec::new(), options: Vec::new() }; + let mut it = args.iter(); + while let Some(a) = it.next() { + if let Some(name) = a.strip_prefix("--") { + let (name, inline) = match name.split_once('=') { + Some((n, v)) => (n, Some(v.to_owned())), + None => (name, None), + }; + if switches.contains(&name) && inline.is_none() { + out.options.push((name.into(), None)); + } else if valued.contains(&name) { + let v = inline.or_else(|| it.next().cloned()).ok_or_else(|| format!("--{name} needs a value"))?; + out.options.push((name.into(), Some(v))); + } else { + return Err(format!("unknown option --{name}")); + } + } else { + out.positional.push(a.clone()); + } + } + Ok(out) + } + + fn value(&self, name: &str) -> Option<&str> { + self.options.iter().rev().find(|(n, _)| n == name).and_then(|(_, v)| v.as_deref()) + } + + fn has(&self, name: &str) -> bool { + self.options.iter().any(|(n, _)| n == name) + } + + fn dir(&self) -> Result { + match self.positional.as_slice() { + [] => Ok(PathBuf::from(".")), + [d] => Ok(PathBuf::from(d)), + _ => Err("expected at most one directory".into()), + } + } +} + +fn dir_arg(args: &[String]) -> Result { + Args::parse(args, &[], &[])?.dir() +} + +fn canonical(dir: &Path) -> Result { + dunce::canonicalize(dir).map_err(|e| format!("{}: {e}", dir.display())) +} + +// ---------------------------------------------------------------- new + +fn cmd_new(args: &[String]) -> Result<(), String> { + let a = Args::parse(args, &[], &["template", "id", "name", "sdk"])?; + let [dir] = a.positional.as_slice() else { + return Err("usage: openidea-plugin new [--template T] [--id ID] [--name NAME]".into()); + }; + let dir = PathBuf::from(dir); + let template = templates::Template::parse(a.value("template").unwrap_or("command"))?; + let base = dir.file_name().and_then(|n| n.to_str()).ok_or("the directory needs a name")?; + let id = match a.value("id") { + Some(id) => id.to_owned(), + None => slugify(base), + }; + validate_plugin_id(&id)?; + let name = match a.value("name") { + Some(n) => n.to_owned(), + None => title_case(id.rsplit('.').next().unwrap_or(&id)), + }; + if name.trim().is_empty() || name.contains(['"', '\\', '\n']) { + return Err("--name must not be empty or contain quotes, backslashes or newlines".into()); + } + if dir.exists() && std::fs::read_dir(&dir).map_err(|e| e.to_string())?.next().is_some() { + return Err(format!("{} already exists and is not empty", dir.display())); + } + std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + let dir = canonical(&dir)?; + let sdk = match template { + templates::Template::Command => Some(sdk_path(a.value("sdk"), &dir)?), + _ => None, + }; + let vars = templates::Vars { id: &id, name: &name, sdk: sdk.as_deref() }; + let files = templates::render(template, &vars); + for (rel, content) in &files { + let path = dir.join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?; + } + std::fs::write(&path, content).map_err(|e| format!("{}: {e}", path.display()))?; + } + // Generated packages must be valid as written. + Manifest::load(&dir).map_err(|e| format!("internal error: the template is invalid: {e}"))?; + println!("created {} ({id}) in {}", template.label(), dir.display()); + let shown = std::env::current_dir().ok().and_then(|cwd| dir.strip_prefix(cwd).ok().map(Path::to_path_buf)); + let shown = shown.as_deref().unwrap_or(&dir).display().to_string(); + println!(); + println!("next:"); + if template == templates::Template::Command { + println!(" cargo test --manifest-path {shown}/Cargo.toml # unit tests against the mock host"); + println!(" openidea-plugin build {shown}"); + } else { + println!(" openidea-plugin check {shown}"); + } + println!(" openidea-plugin link {shown} # then Settings › Plugins"); + Ok(()) +} + +/// `My Cool_Plugin` → `my-cool-plugin`. +fn slugify(s: &str) -> String { + let mut out = String::new(); + for c in s.chars() { + match c { + 'a'..='z' | '0'..='9' | '.' => out.push(c), + 'A'..='Z' => out.push(c.to_ascii_lowercase()), + _ if !out.ends_with('-') && !out.is_empty() => out.push('-'), + _ => {} + } + } + out.trim_matches(['-', '.']).to_owned() +} + +/// `my-cool_plugin` → `My Cool Plugin`. +fn title_case(s: &str) -> String { + s.split(['-', '_']) + .filter(|w| !w.is_empty()) + .map(|w| { + let mut c = w.chars(); + c.next().map(|f| f.to_uppercase().chain(c).collect::()).unwrap_or_default() + }) + .collect::>() + .join(" ") +} + +/// The SDK dependency path written into a new plugin's Cargo.toml: `--sdk`, +/// or the SDK of the source tree this tool was built from. +fn sdk_path(explicit: Option<&str>, plugin_dir: &Path) -> Result { + let sdk = match explicit { + Some(p) => PathBuf::from(p), + None => PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/rust/openidea-plugin")), + }; + let sdk = dunce::canonicalize(&sdk).map_err(|_| { + format!("the plugin SDK was not found at {}; pass --sdk ", sdk.display()) + })?; + if !sdk.join("Cargo.toml").is_file() { + return Err(format!("{} is not the openidea-plugin SDK (no Cargo.toml)", sdk.display())); + } + let path = relative(plugin_dir, &sdk).unwrap_or(sdk); + Ok(path.to_string_lossy().replace('\\', "/")) +} + +/// `to` relative to `from` when they share a root (keeps packages in a repo movable). +fn relative(from: &Path, to: &Path) -> Option { + let (f, t): (Vec<_>, Vec<_>) = (from.components().collect(), to.components().collect()); + let common = f.iter().zip(&t).take_while(|(a, b)| a == b).count(); + if common <= 1 { + return None; + } + let mut out = PathBuf::new(); + for _ in common..f.len() { + out.push(".."); + } + for c in &t[common..] { + out.push(c); + } + Some(out) +} + +// ---------------------------------------------------------------- build / check + +fn cmd_build(args: &[String]) -> Result<(), String> { + let a = Args::parse(args, &["debug"], &[])?; + let dir = canonical(&a.dir()?)?; + let manifest = Manifest::load(&dir)?; + let cargo_toml = dir.join("Cargo.toml"); + if !cargo_toml.is_file() { + if manifest.wasm.is_some() { + return Err(format!( + "{} has no Cargo.toml: build the component with your toolchain, then run `check`", + dir.display() + )); + } + println!("{} has no code to build", manifest.id); + return check(&dir); + } + let wasm_rel = manifest.wasm.clone().ok_or("plugin.toml has no `wasm = \"dist/plugin.wasm\"`")?; + let crate_name = crate_name(&cargo_toml)?; + ensure_wasm_target(); + let release = !a.has("debug"); + let target_dir = std::env::var_os("CARGO_TARGET_DIR").map(PathBuf::from).unwrap_or_else(|| dir.join("target")); + let mut cmd = Command::new(std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into())); + cmd.arg("build").arg("--manifest-path").arg(&cargo_toml).args(["--target", "wasm32-wasip2"]); + if release { + cmd.arg("--release"); + } + cmd.env("CARGO_TARGET_DIR", &target_dir); + println!("building {crate_name} for wasm32-wasip2 ({})", if release { "release" } else { "debug" }); + let status = cmd.status().map_err(|e| format!("cannot run cargo: {e}"))?; + if !status.success() { + return Err("cargo build failed".into()); + } + let built = target_dir + .join("wasm32-wasip2") + .join(if release { "release" } else { "debug" }) + .join(format!("{}.wasm", crate_name.replace('-', "_"))); + if !built.is_file() { + return Err(format!("{} was not produced: is `crate-type = [\"cdylib\"]` set in Cargo.toml?", built.display())); + } + let out = dir.join(&wasm_rel); + if let Some(parent) = out.parent() { + std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?; + } + std::fs::copy(&built, &out).map_err(|e| format!("{}: {e}", out.display()))?; + let size = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0); + println!(" -> {} ({})", wasm_rel.display(), human_size(size)); + check(&dir) +} + +fn crate_name(cargo_toml: &Path) -> Result { + let src = std::fs::read_to_string(cargo_toml).map_err(|e| format!("{}: {e}", cargo_toml.display()))?; + let doc: toml::Table = src.parse().map_err(|e| format!("{}: {e}", cargo_toml.display()))?; + let package = doc.get("package").and_then(|p| p.as_table()); + let lib_name = doc.get("lib").and_then(|l| l.get("name")).and_then(|n| n.as_str()); + lib_name + .or_else(|| package.and_then(|p| p.get("name")).and_then(|n| n.as_str())) + .map(str::to_owned) + .ok_or_else(|| format!("{}: no [package] name", cargo_toml.display())) +} + +/// Installs the target through rustup when it is missing (no-op without rustup). +fn ensure_wasm_target() { + let Ok(out) = Command::new("rustup").args(["target", "list", "--installed"]).output() else { return }; + if String::from_utf8_lossy(&out.stdout).lines().any(|l| l.trim() == "wasm32-wasip2") { + return; + } + println!("installing the wasm32-wasip2 target"); + let _ = Command::new("rustup").args(["target", "add", "wasm32-wasip2"]).status(); +} + +/// Validates `dir` exactly as Install from Disk would, and checks the +/// component imports only the plugin API. +fn check(dir: &Path) -> Result<(), String> { + let dir = canonical(dir)?; + let scratch = std::env::temp_dir().join(format!("openidea-plugin-check-{}", std::process::id())); + let result = (|| { + let host = PluginHost::new(scratch.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()) + .map_err(|e| e.to_string())?; + let preview = host.preview_install(&dir).map_err(|e| e.to_string())?; + let manifest = Manifest::load(&dir)?; + println!("{} {} — {}", preview.id, preview.version, preview.name); + if manifest.legacy { + println!(" note: plugin.toml uses the 0.1 format (`openidea-api`); see plugins/README.md to move to 0.2"); + } + if let Some(wasm) = &manifest.wasm { + let engine = PluginEngine::new()?; + let component = engine.compile(&dir.join(wasm))?; + let built_for = engine.check_component(&component)?; + let size = std::fs::metadata(dir.join(wasm)).map(|m| m.len()).unwrap_or(0); + let api = built_for.map(|v| format!(", plugin API {}.{}", v.major, v.minor)).unwrap_or_default(); + println!(" code: {} ({}{api})", wasm.display(), human_size(size)); + } else { + println!(" code: none (contributions only)"); + } + if !manifest.activation.is_empty() { + let events: Vec = manifest.activation.iter().map(ToString::to_string).collect(); + println!(" activation: {}", events.join(", ")); + } + for c in &preview.contributions { + println!(" contributes {} × {}", c.count, c.point); + } + for c in &preview.capabilities { + let kind = if c.optional { "optional" } else { "required" }; + println!(" capability {} ({kind}, {:?} risk): {}", c.id, c.risk, c.description); + } + for w in &preview.warnings { + println!(" warning: {w}"); + } + println!("ok"); + Ok(()) + })(); + let _ = std::fs::remove_dir_all(&scratch); + result +} + +fn human_size(bytes: u64) -> String { + match bytes { + b if b >= 1 << 20 => format!("{:.1} MiB", b as f64 / (1 << 20) as f64), + b if b >= 1 << 10 => format!("{:.1} KiB", b as f64 / 1024.0), + b => format!("{b} B"), + } +} + +// ---------------------------------------------------------------- link + +fn plugins_dir() -> Result { + if let Some(dir) = std::env::var_os("OPENIDEA_PLUGINS_DIR") { + return Ok(PathBuf::from(dir)); + } + dirs::data_dir() + .map(|d| d.join("ai.l0ng.openidea").join("plugins")) + .ok_or_else(|| "cannot find the app data directory; set OPENIDEA_PLUGINS_DIR".into()) +} + +#[derive(Default, serde::Serialize, serde::Deserialize)] +struct Links { + #[serde(default)] + paths: Vec, +} + +fn read_links(file: &Path) -> Result { + match std::fs::read_to_string(file) { + Ok(s) => serde_json::from_str(&s).map_err(|e| format!("{}: {e}", file.display())), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Links::default()), + Err(e) => Err(format!("{}: {e}", file.display())), + } +} + +fn link(dir: &Path, add: bool) -> Result<(), String> { + let plugins = plugins_dir()?; + let file = plugins.join("links.json"); + let mut links = read_links(&file)?; + let dir = if add { + let dir = canonical(dir)?; + let m = Manifest::load(&dir)?; + if let Some(wasm) = &m.wasm + && !dir.join(wasm).is_file() + { + println!("note: {} does not exist yet; run `openidea-plugin build` first", wasm.display()); + } + if links.paths.contains(&dir) { + println!("{} is already linked", dir.display()); + return Ok(()); + } + println!("linked {} ({})", m.id, dir.display()); + links.paths.push(dir.clone()); + dir + } else { + let dir = dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()); + let before = links.paths.len(); + links.paths.retain(|p| p != &dir); + if links.paths.len() == before { + return Err(format!("{} is not linked", dir.display())); + } + println!("unlinked {}", dir.display()); + dir + }; + let _ = dir; + std::fs::create_dir_all(&plugins).map_err(|e| format!("{}: {e}", plugins.display()))?; + let json = serde_json::to_string_pretty(&links).map_err(|e| e.to_string())?; + let tmp = file.with_extension("json.tmp"); + std::fs::write(&tmp, json) + .and_then(|()| std::fs::rename(&tmp, &file)) + .map_err(|e| format!("{}: {e}", file.display()))?; + println!("open Settings › Plugins in OpenIDEA to load the change"); + Ok(()) +} + +fn list_links() -> Result<(), String> { + let links = read_links(&plugins_dir()?.join("links.json"))?; + if links.paths.is_empty() { + println!("no linked plugins"); + } + for p in links.paths { + let id = Manifest::load(&p).map(|m| m.id).unwrap_or_else(|e| format!("invalid: {e}")); + println!("{id}\t{}", p.display()); + } + Ok(()) +} + +// ---------------------------------------------------------------- distribution + +use ide_extension::package::{self, Index, IndexEntry, KeyEntry, PublisherKey}; + +fn read_key(path: &str) -> Result { + PublisherKey::from_base64(&std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?) +} + +fn cmd_keygen(args: &[String]) -> Result<(), String> { + let a = Args::parse(args, &[], &[])?; + let [file] = a.positional.as_slice() else { return Err("usage: openidea-plugin keygen ".into()) }; + if Path::new(file).exists() { + return Err(format!("{file} exists; not overwriting a key")); + } + let mut seed = [0u8; 32]; + getrandom::fill(&mut seed).map_err(|e| format!("random: {e}"))?; + let key = PublisherKey::from_seed(seed); + std::fs::write(file, key.seed_base64()).map_err(|e| format!("{file}: {e}"))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(file, std::fs::Permissions::from_mode(0o600)); + } + println!("public key: {}", key.public_base64()); + println!("register it with your publisher id in the marketplace index; keep {file} secret"); + Ok(()) +} + +/// A scratch host to list a package's files as the IDE would. +fn with_scratch_host(f: impl FnOnce(&PluginHost) -> Result) -> Result { + let scratch = std::env::temp_dir().join(format!("openidea-plugin-pack-{}", std::process::id())); + let result = PluginHost::new(scratch.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()) + .map_err(|e| e.to_string()) + .and_then(|h| f(&h)); + let _ = std::fs::remove_dir_all(&scratch); + result +} + +fn cmd_pack(args: &[String]) -> Result<(), String> { + let a = Args::parse(args, &[], &["key", "publisher", "out"])?; + let dir = canonical(&a.dir()?)?; + check(&dir)?; + let manifest = Manifest::load(&dir)?; + let mut files = with_scratch_host(|h| h.package_files_of(&dir).map_err(|e| e.to_string()))?; + let digest = package::package_digest(&dir, &files).map_err(|e| e.to_string())?; + let signature = match (a.value("key"), a.value("publisher")) { + (Some(key), Some(publisher)) => { + if !manifest.id.starts_with(&format!("{publisher}.")) { + return Err(format!("publisher {publisher:?} may only sign plugins named {publisher}.*")); + } + Some(read_key(key)?.sign(publisher, &manifest.id, &manifest.version, &digest)) + } + (None, None) => None, + _ => return Err("--key and --publisher go together".into()), + }; + for lic in ["LICENSE", "LICENSE.md", "LICENSE.txt", "NOTICE", "NOTICE.md", "COPYING", "README.md"] { + if dir.join(lic).is_file() { + files.push(PathBuf::from(lic)); + } + } + let out = a.value("out").map(PathBuf::from).unwrap_or_else(|| { + PathBuf::from(format!("{}-{}.{}", manifest.id, manifest.version, package::PACKAGE_EXTENSION)) + }); + package::pack(&dir, &files, &out, signature.as_ref())?; + let size = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0); + let signed = signature.as_ref().map_or("unsigned".to_owned(), |s| format!("signed by {}", s.publisher)); + println!("-> {} ({}, {signed})", out.display(), human_size(size)); + Ok(()) +} + +fn cmd_index(args: &[String]) -> Result<(), String> { + let a = Args::parse(args, &[], &["publisher", "name", "key", "out"])?; + let dir = canonical(&a.dir()?)?; + let publisher = a.value("publisher").ok_or("--publisher is required")?; + let name = a.value("name").unwrap_or(publisher); + let key = read_key(a.value("key").ok_or("--key is required")?)?; + let out = a.value("out").map(PathBuf::from).unwrap_or_else(|| dir.join("index.json")); + // Revocations and other publishers of an existing index are kept. + let mut index = match std::fs::read_to_string(&out) { + Ok(text) => Index::parse(&text)?, + Err(_) => Index { format: package::INDEX_FORMAT, ..Index::default() }, + }; + // Earlier keys of the publisher stay listed (packages they signed remain valid until revoked). + let current = key.public_base64(); + let earlier: Vec = index + .publishers + .iter() + .filter(|p| p.id == publisher) + .flat_map(|p| p.keys.iter().filter(|k| k.key != current).cloned()) + .collect(); + index.publishers.retain(|p| p.id != publisher); + let keys: Vec = std::iter::once(KeyEntry { key: current, revoked: false }).chain(earlier).collect(); + index.publishers.push(package::Publisher { id: publisher.into(), name: name.into(), keys }); + index.plugins.clear(); + let mut packages: Vec = std::fs::read_dir(&dir) + .map_err(|e| e.to_string())? + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == package::PACKAGE_EXTENSION)) + .collect(); + packages.sort(); + for path in packages { + let scratch = std::env::temp_dir().join(format!("openidea-plugin-index-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&scratch); + let unpacked = package::unpack(&path, &scratch)?; + let entry = (|| { + let m = Manifest::load(&scratch)?; + let files = with_scratch_host(|h| h.package_files_of(&scratch).map_err(|e| e.to_string()))?; + let digest = package::package_digest(&scratch, &files).map_err(|e| e.to_string())?; + let sig = unpacked.signature.as_ref().ok_or_else(|| format!("{}: not signed", path.display()))?; + sig.check(&m.id, &m.version, &digest).map_err(|e| format!("{}: {e}", path.display()))?; + Ok::<_, String>(IndexEntry { + id: m.id.clone(), + name: m.name.clone(), + version: m.version.clone(), + description: m.description.clone(), + authors: m.authors.clone(), + publisher: sig.publisher.clone(), + download: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), + digest, + capabilities: m.capabilities.all().map(|c| c.to_string()).collect(), + }) + })(); + let _ = std::fs::remove_dir_all(&scratch); + let entry = entry?; + println!(" {} {}", entry.id, entry.version); + index.plugins.push(entry); + } + let json = serde_json::to_string_pretty(&index).map_err(|e| e.to_string())?; + std::fs::write(&out, json).map_err(|e| format!("{}: {e}", out.display()))?; + println!("-> {} ({} plugins)", out.display(), index.plugins.len()); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names() { + assert_eq!(slugify("My Cool_Plugin"), "my-cool-plugin"); + assert_eq!(slugify("acme.Tools"), "acme.tools"); + assert_eq!(title_case("material-icons"), "Material Icons"); + assert_eq!( + relative(Path::new("/a/b/plugins/x"), Path::new("/a/b/sdk/rust/p")).unwrap(), + PathBuf::from("../../sdk/rust/p") + ); + assert_eq!(relative(Path::new("/x/y"), Path::new("/z")), None); + } + + #[test] + fn every_template_is_a_valid_package() { + for t in templates::Template::ALL { + let dir = + std::env::temp_dir().join(format!("openidea-plugin-template-{}-{}", t.label(), std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let vars = templates::Vars { id: "acme.sample", name: "Sample", sdk: Some("../sdk") }; + for (rel, content) in templates::render(t, &vars) { + let path = dir.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, content).unwrap(); + } + let m = Manifest::load(&dir).unwrap_or_else(|e| panic!("{}: {e}", t.label())); + assert_eq!(m.id, "acme.sample"); + if m.wasm.is_none() { + check(&dir).unwrap_or_else(|e| panic!("{}: {e}", t.label())); + } + std::fs::remove_dir_all(&dir).unwrap(); + } + } +} diff --git a/crates/ide-host/src/bin/openidea-plugin/templates.rs b/crates/ide-host/src/bin/openidea-plugin/templates.rs new file mode 100644 index 00000000..fc23cdd0 --- /dev/null +++ b/crates/ide-host/src/bin/openidea-plugin/templates.rs @@ -0,0 +1,278 @@ +//! The files of `openidea-plugin new`. Placeholders: `__ID__` (plugin id), +//! `__SLUG__` (last id segment), `__NAME__`, `__CRATE__`, `__SDK__`. + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Template { + Command, + Theme, + IconTheme, + Language, +} + +impl Template { + pub const ALL: [Template; 4] = [Self::Command, Self::Theme, Self::IconTheme, Self::Language]; + + pub fn parse(s: &str) -> Result { + Self::ALL + .into_iter() + .find(|t| t.label() == s) + .ok_or_else(|| format!("unknown template {s:?} (command, theme, icon-theme, language)")) + } + + pub fn label(self) -> &'static str { + match self { + Self::Command => "command", + Self::Theme => "theme", + Self::IconTheme => "icon-theme", + Self::Language => "language", + } + } +} + +pub struct Vars<'a> { + pub id: &'a str, + pub name: &'a str, + pub sdk: Option<&'a str>, +} + +/// `(relative path, contents)` of every file of the template. +pub fn render(template: Template, vars: &Vars) -> Vec<(String, String)> { + let slug = vars.id.rsplit('.').next().unwrap_or(vars.id).to_owned(); + let crate_name = format!("openidea-plugin-{}", vars.id.replace('.', "-")); + let fill = |s: &str| { + s.replace("__ID__", vars.id) + .replace("__SLUG__", &slug) + .replace("__NAME__", vars.name) + .replace("__CRATE__", &crate_name) + .replace("__SDK__", vars.sdk.unwrap_or("")) + // The theme files come from the Harbor Night plugin. + .replace("harbor-night", &slug) + .replace("Harbor Night", vars.name) + }; + let files: Vec<(String, &str)> = match template { + Template::Command => vec![ + ("plugin.toml".into(), COMMAND_MANIFEST), + ("Cargo.toml".into(), COMMAND_CARGO), + ("src/lib.rs".into(), COMMAND_LIB), + (".gitignore".into(), "/target\n"), + ("README.md".into(), COMMAND_README), + ], + Template::Theme => vec![ + ("plugin.toml".into(), THEME_MANIFEST), + (format!("themes/{slug}.theme.json"), THEME_UI), + (format!("themes/{slug}.scheme.json"), THEME_SCHEME), + ], + Template::IconTheme => vec![ + ("plugin.toml".into(), ICON_MANIFEST), + ("icons/theme.json".into(), ICON_THEME), + ("icons/file.svg".into(), ICON_FILE), + ("icons/folder.svg".into(), ICON_FOLDER), + ("icons/folder-open.svg".into(), ICON_FOLDER_OPEN), + ("icons/markdown.svg".into(), ICON_MARKDOWN), + ], + Template::Language => { + vec![("plugin.toml".into(), LANGUAGE_MANIFEST), (format!("languages/{slug}.toml"), LANGUAGE_DEF)] + } + }; + files.into_iter().map(|(path, content)| (path, fill(content))).collect() +} + +const COMMAND_MANIFEST: &str = r#"id = "__ID__" +name = "__NAME__" +version = "0.1.0" +description = "Adds two sample commands." +authors = [] +engines.openidea = "^1.0" +# Built by `openidea-plugin build`. The code is loaded the first time one of +# its commands runs; the commands below show in Find Action before that. +wasm = "dist/plugin.wasm" + +# What the code may do. The user approves these when installing. +[capabilities] +required = ["editor.read"] + +[[contributes.commands]] +id = "say-hello" +title = "__NAME__: Say Hello" +category = "__NAME__" + +[[contributes.commands]] +id = "line-count" +title = "__NAME__: Line Count of Active File" +category = "__NAME__" +"#; + +const COMMAND_CARGO: &str = r#"[package] +name = "__CRATE__" +version = "0.1.0" +edition = "2024" +publish = false + +# A plugin builds on its own (target wasm32-wasip2), outside any IDE workspace. +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "__SDK__" } + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" +"#; + +const COMMAND_LIB: &str = r#"//! __NAME__: an OpenIDEA plugin. + +use openidea_plugin::{Invocation, NotificationLevel, Plugin, host, register_plugin}; + +#[derive(Default)] +pub struct Main { + greetings: u32, +} + +impl Plugin for Main { + fn run_command(&mut self, id: &str, ctx: &Invocation, _arg: Option<&str>) -> Result, String> { + match id { + "say-hello" => { + // Instance state lasts until the plugin is idle for a while; + // keep what must survive in `host::storage`. + self.greetings += 1; + let body = format!("Hello #{} from __NAME__!", self.greetings); + host::notify(NotificationLevel::Info, "__NAME__", &body); + Ok(None) + } + "line-count" => { + let editor = ctx.editor().ok_or("no file is open")?; + let text = editor.document()?.text; + Ok(Some(format!("{} lines in {}", text.lines().count(), editor.path()))) + } + _ => Err(format!("unknown command {id}")), + } + } +} + +register_plugin!(Main); + +#[cfg(test)] +mod tests { + use super::*; + use openidea_plugin::mock::MockHost; + + #[test] + fn says_hello() { + let host = MockHost::install(); + let mut plugin = Main::default(); + plugin.run_command("say-hello", &host.invocation(), None).unwrap(); + plugin.run_command("say-hello", &host.invocation(), None).unwrap(); + assert_eq!(host.notifications()[1].body, "Hello #2 from __NAME__!"); + } + + #[test] + fn counts_lines() { + let host = MockHost::install(); + host.open_editor("/project/src/main.rs", "rust", "fn main() {\n}\n", &[]); + let out = Main::default().run_command("line-count", &host.invocation(), None).unwrap(); + assert_eq!(out.as_deref(), Some("2 lines in /project/src/main.rs")); + } +} +"#; + +const COMMAND_README: &str = r#"# __NAME__ + +An OpenIDEA plugin. + +```sh +cargo test # logic, against the SDK's mock host +openidea-plugin build # → dist/plugin.wasm, validated like an install +openidea-plugin link # load this folder in the IDE (Settings › Plugins) +``` + +`plugin.toml` declares the commands, so they appear in Find Action before the +code is loaded, and the capabilities the code needs. `src/lib.rs` implements +them with the `openidea-plugin` SDK. +"#; + +const THEME_MANIFEST: &str = r#"id = "__ID__" +name = "__NAME__" +version = "0.1.0" +description = "A dark theme." +authors = [] +engines.openidea = "^1.0" + +# One entry per theme. `editor-scheme` is optional: its tokens are merged over +# the theme's (IntelliJ's .theme.json + .icls pair). Reference: docs/plugins/themes.md. +[[contributes.themes]] +path = "themes/__SLUG__.theme.json" +editor-scheme = "themes/__SLUG__.scheme.json" +"#; + +const THEME_UI: &str = include_str!("../../../../../plugins/official/harbor-night/themes/harbor-night.theme.json"); +const THEME_SCHEME: &str = include_str!("../../../../../plugins/official/harbor-night/themes/harbor-night.scheme.json"); + +const ICON_MANIFEST: &str = r#"id = "__ID__" +name = "__NAME__" +version = "0.1.0" +description = "File and folder icons." +authors = [] +engines.openidea = "^1.0" + +# Apply it in Settings › Plugins › __NAME__. SVGs are sanitised on install: +# no scripts, event handlers, external references or entities. +[[contributes.iconThemes]] +id = "__SLUG__" +label = "__NAME__" +path = "icons/theme.json" +"#; + +const ICON_THEME: &str = r#"{ + "iconDefinitions": { + "file": "icons/file.svg", + "folder": "icons/folder.svg", + "folder-open": "icons/folder-open.svg", + "markdown": "icons/markdown.svg" + }, + "file": "file", + "folder": "folder", + "folderExpanded": "folder-open", + "fileExtensions": { "md": "markdown", "markdown": "markdown" }, + "fileNames": { "readme": "markdown" }, + "folderNames": {} +} +"#; + +const ICON_FILE: &str = r##" +"##; + +const ICON_FOLDER: &str = r##" +"##; + +const ICON_FOLDER_OPEN: &str = r##" +"##; + +const ICON_MARKDOWN: &str = r##" +"##; + +const LANGUAGE_MANIFEST: &str = r#"id = "__ID__" +name = "__NAME__" +version = "0.1.0" +description = "Language support for .__SLUG__ files: detection, comments and indentation." +authors = [] +engines.openidea = "^1.0" + +# Same format as languages/.toml in the IDE repository. +[[contributes.languages]] +path = "languages/__SLUG__.toml" +"#; + +const LANGUAGE_DEF: &str = r##"id = "__SLUG__" +name = "__NAME__" +extensions = ["__SLUG__"] +line-comment = "#" +indent = { tab-size = 2, insert-spaces = true } +# Borrow an existing CodeMirror mode for instant highlighting. +ui-mode = "Properties files" +"##; diff --git a/crates/ide-host/src/bin/server.rs b/crates/ide-host/src/bin/server.rs index ada210d8..6a1f2578 100644 --- a/crates/ide-host/src/bin/server.rs +++ b/crates/ide-host/src/bin/server.rs @@ -1,6 +1,8 @@ //! `openidea-server --stdio`: the IDE backend for remote development, serving //! one desktop client over stdin / stdout (started by the client over SSH). +use ide_host::plugins::remote::{RemotePluginLanguages, SYNC_COMMAND}; +use ide_host::plugins::remote_host::RemotePlugins; use ide_host::rpc::{self, Dispatcher}; use ide_host::{Host, HostConfig}; use ide_language::LanguageRegistry; @@ -51,8 +53,12 @@ async fn run(base: PathBuf) -> i32 { return 1; } }; + // The desktop's plugin languages (`plugin_sync_languages`); programs pinned on this machine. + let plugin_languages = RemotePluginLanguages::new(Some(&data_dir)); + languages.attach_plugins(plugin_languages.store().clone()); let peer = Arc::new(OnceLock::new()); let sink_peer = peer.clone(); + let plugins_data = data_dir.clone(); let host = Arc::new(Host::new(HostConfig { config_dir, local_data_dir: data_dir.clone(), @@ -64,8 +70,31 @@ async fn run(base: PathBuf) -> i32 { runtime: tokio::runtime::Handle::current(), project_environment: true, })); + // The desktop's code plugins run here, next to the project (`plugin_sync_packages`). + let plugins = match RemotePlugins::start(&plugins_data, &host, peer.clone()) { + Ok(p) => Some(p), + Err(e) => { + tracing::warn!("plugins are unavailable: {e}"); + None + } + }; tracing::info!("openidea-server {} ready", env!("CARGO_PKG_VERSION")); - rpc::serve(host.clone(), Dispatcher::standard(), peer, tokio::io::stdin(), tokio::io::stdout()).await; + let mut dispatcher = Dispatcher::standard(); + if let Some(plugins) = &plugins { + plugins.register(&mut dispatcher); + } + dispatcher.add(SYNC_COMMAND, move |c| { + let remote = plugin_languages.clone(); + async move { + let report = remote.sync(c.arg("languages")?); + c.host.plugin_languages_changed(); + Ok(report) + } + }); + rpc::serve(host.clone(), dispatcher, peer, tokio::io::stdin(), tokio::io::stdout()).await; + if let Some(plugins) = &plugins { + plugins.host().shutdown(); + } // `process::exit` skips destructors: nothing started for the client may outlive it. if tokio::time::timeout(std::time::Duration::from_secs(10), host.shutdown()).await.is_err() { tracing::warn!("language servers did not shut down in time"); diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index 898b2884..edaafb43 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -1,6 +1,6 @@ //! The IDE backend without a UI toolkit: open projects per window, terminals, //! processes, settings and the remote services. The desktop shell (`src-tauri`) -//! wraps one [`Host`] and adds windows, menus and plugins; `openidea-server` +//! wraps one [`Host`] and adds windows and menus; `openidea-server` //! runs one on a remote machine and serves it over JSON-RPC ([`rpc`]). pub mod data_dirs; @@ -10,6 +10,7 @@ mod java_runtime; mod kotlin_bridge; pub mod notebook; pub mod ops; +pub mod plugins; mod project; mod proxy; mod requests; @@ -133,6 +134,17 @@ impl Host { self.syntax.get_or_init(|| Arc::new(Syntax::new())).clone() } + /// Plugin languages or the servers they may start changed (they are part + /// of [`Self::languages`] and every project's fork): open documents are + /// detected again and language servers follow their new configuration. + pub fn plugin_languages_changed(&self) { + for project in self.projects() { + project.documents.redetect_languages(); + let lsp = project.lsp.clone(); + self.runtime.spawn(async move { lsp.reconfigure().await }); + } + } + /// Every open project (all windows). pub fn projects(&self) -> Vec> { self.projects.read().values().cloned().collect() diff --git a/crates/ide-host/src/ops/lsp.rs b/crates/ide-host/src/ops/lsp.rs index f84ab3c7..f8b27063 100644 --- a/crates/ide-host/src/ops/lsp.rs +++ b/crates/ide-host/src/ops/lsp.rs @@ -1,9 +1,11 @@ use super::doc::blocking; use crate::Host; use crate::apply_workspace_edit as apply_edit; +use crate::plugins::{ProviderKind, editor_providers_for as editor_providers}; use crate::rpc::Dispatcher; use ide_core::{DocId, IdeResult, Location, Pos, Range, RequestId, ServerId, TextEdit, WorkspaceEdit}; use ide_lsp::types::*; +use ide_plugin::ProviderDocument; async fn prepare_actions( project: std::sync::Arc, @@ -38,9 +40,99 @@ pub async fn lsp_completion( ) -> IdeResult { let lsp = host.project(window)?.lsp.clone(); let cancel = host.begin_request(request); - let result = lsp.completion(doc, pos, trigger, cancel).await; + let result = lsp.completion(doc, pos, trigger.clone(), cancel).await; host.end_request(request); - result + // Plugin providers (`[[contributes.providers]]`) add theirs. + let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Completion) else { return result }; + let items = plugin_call(move || plugins.provide_completion(&d, pos, trigger.as_deref())).await.unwrap_or_default(); + if items.is_empty() { + return result; + } + let mut list = result.unwrap_or(CompletionList { is_incomplete: false, items: Vec::new() }); + list.items.extend(items.into_iter().map(|(_, item)| plugin_completion(item))); + Ok(list) +} + +/// The plugin host and the document, when some plugin provides `kind`. +fn plugin_providers( + host: &Host, + window: &str, + doc: DocId, + kind: ProviderKind, +) -> Option<(std::sync::Arc, ProviderDocument)> { + let plugins = editor_providers(kind)?; + let snap = host.project(window).ok()?.documents.snapshot(doc).ok()?; + let d = ProviderDocument { + path: snap.path.0, + language: snap.language.0, + version: u64::from(snap.version), + text: snap.text, + }; + Some((plugins, d)) +} + +/// Plugin calls block (the plugin's actor thread does the work). +async fn plugin_call(f: impl FnOnce() -> T + Send + 'static) -> Option { + tokio::task::spawn_blocking(f).await.ok() +} + +/// Items from plugins carry no server (resolve and commands don't apply). +const PLUGIN_SERVER: ServerId = ServerId(0); + +/// A plugin's `completion-item.kind` (wit/providers.wit lists them). +fn plugin_completion_kind(kind: &str) -> Option { + Some(match kind { + "text" => CompletionKind::Text, + "method" => CompletionKind::Method, + "function" => CompletionKind::Function, + "constructor" => CompletionKind::Constructor, + "field" => CompletionKind::Field, + "variable" => CompletionKind::Variable, + "class" => CompletionKind::Class, + "interface" => CompletionKind::Interface, + "module" => CompletionKind::Module, + "property" => CompletionKind::Property, + "unit" => CompletionKind::Unit, + "value" => CompletionKind::Value, + "enum" => CompletionKind::Enum, + "keyword" => CompletionKind::Keyword, + "snippet" => CompletionKind::Snippet, + "color" => CompletionKind::Color, + "file" => CompletionKind::File, + "reference" => CompletionKind::Reference, + "folder" => CompletionKind::Folder, + "enum-member" => CompletionKind::EnumMember, + "constant" => CompletionKind::Constant, + "struct" => CompletionKind::Struct, + "event" => CompletionKind::Event, + "operator" => CompletionKind::Operator, + "type-parameter" => CompletionKind::TypeParameter, + _ => return None, + }) +} + +fn plugin_completion(item: ide_plugin::CompletionItem) -> CompletionItem { + let kind = item.kind.as_deref().and_then(plugin_completion_kind); + CompletionItem { + label: item.label, + label_detail: None, + detail: item.detail, + kind, + documentation: item.documentation.map(|value| Markup { kind: "markdown".into(), value }), + sort_text: item.sort_text, + filter_text: None, + preselect: false, + deprecated: false, + insert_text: item.insert_text, + is_snippet: false, + replace_range: item.replace, + replace_range_tab: None, + additional_edits: Vec::new(), + commit_characters: Vec::new(), + command: None, + data: None, + server: PLUGIN_SERVER, + } } /// Inline (ghost text) suggestions at `pos`; `automatic` when triggered by typing. @@ -54,9 +146,26 @@ pub async fn lsp_inline_completion( ) -> IdeResult> { let lsp = host.project(window)?.lsp.clone(); let cancel = host.begin_request(request); - let result = lsp.inline_completion(doc, pos, automatic, cancel).await; + let result = lsp.inline_completion(doc, pos, automatic, cancel.clone()).await; + // Plugins: cancelled (cooperatively) when the editor cancels the request. + let plugin = match plugin_providers(host, window, doc, ProviderKind::InlineCompletion) { + Some((plugins, d)) if !matches!(&result, Ok(items) if !items.is_empty()) => { + let cancel = cancel.clone(); + plugin_call(move || plugins.provide_inline_completion(&d, pos, &cancel)).await.flatten() + } + _ => None, + }; host.end_request(request); - result + match plugin { + Some((_, s)) => Ok(vec![InlineCompletionItem { + insert_text: s.insert_text, + range: s.replace, + filter_text: None, + command: None, + server: PLUGIN_SERVER, + }]), + None => result, + } } pub async fn lsp_resolve_completion( @@ -87,7 +196,40 @@ pub async fn lsp_signature_help(host: &Host, window: &str, doc: DocId, pos: Pos) } pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: GotoKind) -> IdeResult> { - host.project(window)?.lsp.goto(doc, pos, kind).await + let result = host.project(window)?.lsp.goto(doc, pos, kind).await; + if kind != GotoKind::Definition { + return result; + } + let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Definition) else { return result }; + let found = plugin_call(move || plugins.provide_definition(&d, pos)).await.unwrap_or_default(); + if found.is_empty() { + return result; + } + let mut out = result.unwrap_or_default(); + out.extend(found.into_iter().map(|l| Location { path: l.path.into(), range: l.range, uri: None })); + Ok(out) +} + +/// Gutter markers from plugins (`line-markers` providers) for `doc`. +pub async fn plugin_line_markers( + host: &Host, + window: &str, + doc: DocId, +) -> IdeResult> { + let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::LineMarkers) else { + return Ok(Vec::new()); + }; + let markers = plugin_call(move || plugins.provide_line_markers(&d)).await.unwrap_or_default(); + Ok(markers + .into_iter() + .map(|(plugin_id, m)| crate::plugins::LineMarkerInfo { + plugin_id, + line: m.line, + icon: m.icon, + tooltip: m.tooltip, + target: m.target.map(|l| Location { path: l.path.into(), range: l.range, uri: None }), + }) + .collect()) } /// Implementations of the symbols at `positions`, one list per position (the @@ -165,10 +307,47 @@ pub async fn lsp_code_actions( let project = host.project(window)?; let documents = project.documents.clone(); let version = blocking(move || documents.version(doc)).await?; - let actions = project.lsp.code_actions(doc, range, only).await?; + let result = project.lsp.code_actions(doc, range, only.clone()).await; + let plugin_actions = match plugin_providers(host, window, doc, ProviderKind::CodeActions) { + Some((plugins, d)) => plugin_call(move || plugins.provide_code_actions(&d, range)).await.unwrap_or_default(), + None => Vec::new(), + }; + let plugin_actions: Vec = plugin_actions + .into_iter() + .map(|(_, a)| plugin_code_action(a)) + .filter(|a| { + only.is_empty() + || a.kind.as_ref().is_some_and(|k| only.iter().any(|o| k == o || k.starts_with(&format!("{o}.")))) + }) + .collect(); + let actions = if plugin_actions.is_empty() { + result? + } else { + let mut out = result.unwrap_or_default(); + out.extend(plugin_actions); + out + }; prepare_actions(project, doc, version, actions).await } +fn plugin_code_action(a: ide_plugin::CodeAction) -> CodeAction { + let files = a + .edits + .into_iter() + .map(|(path, edits)| ide_core::FileEdit::Edit { path: path.into(), edits, version: None }) + .collect(); + CodeAction { + title: a.title, + kind: a.kind, + is_preferred: a.preferred, + disabled_reason: None, + edit: Some(WorkspaceEdit { files, preconditions: Vec::new() }), + command: None, + data: None, + server: PLUGIN_SERVER, + } +} + /// Cancellable code actions with the kinds the servers advertise (Refactor This, refactoring availability). pub async fn lsp_code_action_query( host: &Host, @@ -551,3 +730,28 @@ pub(crate) fn register(d: &mut Dispatcher) { lsp_execute_command(&c.host, &c.window, c.arg("doc")?, c.arg("command")?).await }); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_completion_kind_the_plugin_api_documents_is_understood() { + let wit = include_str!("../../../../wit/providers.wit"); + let doc: String = wit + .lines() + .map(|l| l.trim().trim_start_matches("///").trim()) + .skip_while(|l| !l.starts_with("Icon and sort group:")) + .take_while(|l| !l.starts_with("kind:")) + .collect::>() + .join(" "); + let list = doc.strip_prefix("Icon and sort group:").unwrap().split(". Unknown").next().unwrap(); + let list = list.replace(" or ", ", "); + let kinds: Vec<&str> = list.split(',').map(str::trim).filter(|k| !k.is_empty()).collect(); + assert_eq!(kinds.len(), 25, "{kinds:?}"); + for k in kinds { + assert!(plugin_completion_kind(k).is_some(), "{k:?}"); + } + assert_eq!(plugin_completion_kind("nonsense"), None); + } +} diff --git a/crates/ide-host/src/plugins/api.rs b/crates/ide-host/src/plugins/api.rs new file mode 100644 index 00000000..d1f8f1a1 --- /dev/null +++ b/crates/ide-host/src/plugins/api.rs @@ -0,0 +1,803 @@ +//! [`HostApi`] for one plugin's code: what its imports reach in the IDE. +//! Capabilities were checked by the runtime before any of this runs. + +use super::{PluginEvent, PluginEventSink}; +use ide_core::{CancellationToken, TextEdit}; +use ide_extension::Package; +use ide_language::ProgramPin; +use ide_plugin::{ + EventKind, HostApi, HostError, HttpRequest, HttpResponse, NotificationLevel, ProcessOutput, RepositoryStatus, + StatusItem, +}; +use parking_lot::{Mutex, RwLock}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +/// Largest storage of one plugin (keys + values). +const MAX_STORAGE: usize = 1 << 20; +const MAX_KEY: usize = 256; +/// Most status bar items per plugin. +const MAX_STATUS_ITEMS: usize = 8; + +/// What plugins see of the open projects; provided by the app +/// ([`super::PluginHost::set_workspace`]), over [`crate::Host`] on the desktop. +pub trait PluginWorkspace: Send + Sync { + /// Roots of the open projects. + fn projects(&self) -> Vec; + /// Unsaved text of the open document at `path`. + fn buffer_text(&self, path: &Path) -> Option; + /// Version and text of the open document at `path`. + fn document(&self, path: &Path) -> Option<(u64, String)>; + /// Applies `edits` to the open document at `path` if it is still at + /// `version`, as one change (one undo step in the editor). + fn apply_edits(&self, path: &Path, version: u64, edits: &[TextEdit]) -> Result; + /// Code from the project may run (git hooks and config on fetch). + fn trusted(&self, root: &Path) -> bool; + /// Root of the project open in `window`. + fn project_of(&self, window: &str) -> Option; + /// Shows `items` as producer `source`'s diagnostics of `path` (replacing earlier ones). + fn publish_diagnostics(&self, source: &str, path: &Path, items: Vec) + -> Result<(), HostError>; + /// The user's values of `plugin`'s settings: the project's at `root` + /// (over global), or global. + fn plugin_settings(&self, _plugin: &str, _root: Option<&Path>) -> serde_json::Map { + serde_json::Map::new() + } +} + +/// Where plugin secrets live (the OS keychain on the desktop). Plugins can +/// only ask whether one is set; values go out only inside `net` requests. +pub trait SecretStore: Send + Sync { + fn get(&self, plugin: &str, name: &str) -> Option; + /// Sets, or (`None`) deletes. + fn set(&self, plugin: &str, name: &str, value: Option<&str>) -> Result<(), String>; +} + +/// Fallback [`SecretStore`]: one file per plugin, readable only by the user. +pub struct FileSecretStore { + pub dir: PathBuf, +} + +impl FileSecretStore { + fn file(&self, plugin: &str) -> PathBuf { + self.dir.join(plugin).join("secrets.json") + } + + fn load(&self, plugin: &str) -> BTreeMap { + std::fs::read(self.file(plugin)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default() + } +} + +impl SecretStore for FileSecretStore { + fn get(&self, plugin: &str, name: &str) -> Option { + self.load(plugin).remove(name) + } + + fn set(&self, plugin: &str, name: &str, value: Option<&str>) -> Result<(), String> { + let mut map = self.load(plugin); + match value { + Some(v) => map.insert(name.to_owned(), v.to_owned()), + None => map.remove(name), + }; + let file = self.file(plugin); + std::fs::create_dir_all(file.parent().expect("has parent")).map_err(|e| e.to_string())?; + let bytes = serde_json::to_vec(&map).map_err(|e| e.to_string())?; + let tmp = file.with_extension("tmp"); + std::fs::write(&tmp, bytes).map_err(|e| e.to_string())?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600)); + } + std::fs::rename(&tmp, &file).map_err(|e| e.to_string()) + } +} + +/// Largest response body a plugin receives. +const MAX_RESPONSE: usize = 8 << 20; +/// Largest stdout / stderr kept from a process. +const MAX_OUTPUT: usize = 4 << 20; +/// Most files `find-files` walks before giving up. +const MAX_WALK: usize = 200_000; + +/// Runtime for plugin HTTP requests (actor threads block on it). +pub(super) fn net_runtime() -> &'static tokio::runtime::Runtime { + static RT: std::sync::OnceLock = std::sync::OnceLock::new(); + RT.get_or_init(|| { + tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .thread_name("plugin-net") + .enable_all() + .build() + .expect("plugin network runtime") + }) +} + +/// Replaces `{{secret:}}` in `value` with the plugin's secrets. +fn fill_secrets(value: &str, lookup: impl Fn(&str) -> Option) -> Result { + let mut out = String::with_capacity(value.len()); + let mut rest = value; + while let Some(i) = rest.find("{{secret:") { + out.push_str(&rest[..i]); + let after = &rest[i + "{{secret:".len()..]; + let end = after.find("}}").ok_or_else(|| HostError::Invalid("unterminated {{secret:…}}".into()))?; + let name = &after[..end]; + let secret = lookup(name).ok_or_else(|| HostError::NotFound(format!("secret {name:?} is not set")))?; + out.push_str(&secret); + rest = &after[end + 2..]; + } + out.push_str(rest); + Ok(out) +} + +/// A plugin task shown in the UI. +struct TaskEntry { + plugin: String, + cancel: CancellationToken, + cancelled: bool, +} + +/// State shared by the host and every plugin's [`PluginApi`]. +pub(super) struct Shared { + pub sink: Arc, + pub workspace: RwLock>>, + /// `/.data`: one directory per plugin id. + pub data_dir: PathBuf, + tasks: Mutex>, + next_task: AtomicU64, + /// (plugin, item id) → item, for windows opened later. + status: Mutex>, + /// plugin → kinds subscribed at run time (kept across idle reclaim). + pub subscriptions: Mutex>>, + /// plugin → files it shows problems for, withdrawn when it stops. + diagnostics: Mutex>>, + pub secrets: RwLock>, + /// (plugin, `process:` capability) → the approved program. + pub pins: Arc>>, + /// Validated UI declarations (settings schemas, declared views). + pub ui: Arc, +} + +impl Shared { + pub fn new( + sink: Arc, + data_dir: PathBuf, + pins: Arc>>, + ui: Arc, + ) -> Arc { + Arc::new(Self { + ui, + sink, + workspace: RwLock::new(None), + secrets: RwLock::new(Arc::new(FileSecretStore { dir: data_dir.clone() })), + pins, + data_dir, + tasks: Mutex::default(), + next_task: AtomicU64::new(1), + status: Mutex::default(), + subscriptions: Mutex::default(), + diagnostics: Mutex::default(), + }) + } + + fn workspace(&self) -> Option> { + self.workspace.read().clone() + } + + pub fn project_of(&self, window: &str) -> Option { + self.workspace()?.project_of(window) + } + + /// Shows `plugin`'s problems of `path`, remembering the file until they are + /// cleared (by the plugin, or when it stops). + fn publish_diagnostics( + &self, + plugin: &str, + path: &Path, + items: Vec, + ) -> Result<(), HostError> { + let workspace = self.workspace().ok_or_else(|| HostError::NotFound("no project is open".into()))?; + let empty = items.is_empty(); + workspace.publish_diagnostics(plugin, path, items)?; + let mut published = self.diagnostics.lock(); + if empty { + if let Some(paths) = published.get_mut(plugin) { + paths.remove(path); + if paths.is_empty() { + published.remove(plugin); + } + } + } else { + published.entry(plugin.to_owned()).or_default().insert(path.to_path_buf()); + } + Ok(()) + } + + pub fn status_items(&self) -> Vec<(String, String, StatusItem)> { + self.status.lock().iter().map(|((p, id), item)| (p.clone(), id.clone(), item.clone())).collect() + } + + /// Withdraws a plugin's run-time state (it stopped or failed). Its + /// subscriptions go only with `subscriptions`, as they survive restarts. + pub fn clear_plugin(&self, plugin: &str, subscriptions: bool) { + let removed: Vec = { + let mut status = self.status.lock(); + let ids: Vec = status.keys().filter(|(p, _)| p == plugin).map(|(_, id)| id.clone()).collect(); + for id in &ids { + status.remove(&(plugin.to_owned(), id.clone())); + } + ids + }; + for id in removed { + self.sink.emit(None, PluginEvent::StatusItemChanged { plugin_id: plugin.to_owned(), id, item: None }); + } + let tasks: Vec = self.tasks.lock().iter().filter(|(_, t)| t.plugin == plugin).map(|(id, _)| *id).collect(); + for id in tasks { + self.end_task(id); + } + // Its problems go with it (an idle reclaim keeps them: it isn't cleared then). + let paths = self.diagnostics.lock().remove(plugin).unwrap_or_default(); + if let Some(workspace) = self.workspace() { + for path in paths { + let _ = workspace.publish_diagnostics(plugin, &path, Vec::new()); + } + } + if subscriptions && self.subscriptions.lock().remove(plugin).is_some() { + self.sink.emit(None, PluginEvent::SubscriptionsChanged); + } + } + + /// The user cancelled a task in the UI. + pub fn cancel_task(&self, id: u64) -> bool { + let mut tasks = self.tasks.lock(); + let Some(t) = tasks.get_mut(&id) else { return false }; + t.cancelled = true; + t.cancel.cancel(); + true + } + + fn end_task(&self, id: u64) { + if let Some(t) = self.tasks.lock().remove(&id) { + self.sink.emit(None, PluginEvent::TaskEnded { plugin_id: t.plugin, task_id: id.to_string() }); + } + } + + pub fn storage_file(&self, plugin: &str) -> PathBuf { + self.data_dir.join(plugin).join("storage.json") + } +} + +pub(super) struct PluginApi { + pub pkg: Package, + pub shared: Arc, +} + +impl PluginApi { + fn id(&self) -> &str { + self.pkg.id() + } + + fn load_storage(&self) -> Result, HostError> { + match std::fs::read(self.shared.storage_file(self.id())) { + Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| HostError::Failed(format!("storage: {e}"))), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(BTreeMap::new()), + Err(e) => Err(HostError::Failed(format!("storage: {e}"))), + } + } + + fn save_storage(&self, map: &BTreeMap) -> Result<(), HostError> { + let file = self.shared.storage_file(self.id()); + let bytes = serde_json::to_vec(map).map_err(|e| HostError::Failed(e.to_string()))?; + let io = |e: std::io::Error| HostError::Failed(format!("storage: {e}")); + std::fs::create_dir_all(file.parent().expect("has parent")).map_err(io)?; + let tmp = file.with_extension("tmp"); + std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, &file)).map_err(io) + } + + /// The program approved for the (already checked) `process:` grant, + /// verified right before it starts. + fn approved_program(&self, program: &str) -> Result { + let cap = format!("process:{program}"); + // Granted without a pinned file: the program wasn't found when it was + // allowed, and installing it later approves nothing by itself. + let pin = self.shared.pins.read().get(&(self.id().to_owned(), cap.clone())).cloned().ok_or_else(|| { + HostError::Failed(format!( + "{cap}: `{program}` was not found when this permission was allowed; \ + install it, then allow {cap} again in Settings › Plugins" + )) + })?; + pin.verify().map(Path::to_path_buf).map_err(|e| HostError::Denied(format!("{cap}: {e}"))) + } +} + +fn failed(e: impl std::fmt::Display) -> HostError { + HostError::Failed(e.to_string()) +} + +impl HostApi for PluginApi { + fn notify(&self, client: Option<&str>, level: NotificationLevel, title: String, body: String) { + self.shared + .sink + .emit(client, PluginEvent::Notification { plugin_id: self.id().to_owned(), level, title, body }); + } + + fn status_item(&self, id: &str, item: Option) { + let key = (self.id().to_owned(), id.to_owned()); + { + let mut status = self.shared.status.lock(); + match &item { + Some(item) => { + let count = status.keys().filter(|(p, _)| p == self.id()).count(); + if !status.contains_key(&key) && count >= MAX_STATUS_ITEMS { + tracing::warn!(plugin = %self.id(), "more than {MAX_STATUS_ITEMS} status items; {id:?} ignored"); + return; + } + if status.get(&key) == Some(item) { + return; + } + status.insert(key, item.clone()); + } + None => { + if status.remove(&key).is_none() { + return; + } + } + } + } + self.shared + .sink + .emit(None, PluginEvent::StatusItemChanged { plugin_id: self.id().to_owned(), id: id.to_owned(), item }); + } + + fn projects(&self) -> Vec { + self.shared.workspace().map(|w| w.projects()).unwrap_or_default() + } + + fn buffer_text(&self, path: &Path) -> Option { + self.shared.workspace()?.buffer_text(path) + } + + fn document(&self, path: &Path) -> Option<(u64, String)> { + self.shared.workspace()?.document(path) + } + + fn apply_edits( + &self, + _client: Option<&str>, + path: &Path, + version: u64, + edits: Vec, + ) -> Result { + let workspace = self.shared.workspace().ok_or_else(|| HostError::NotFound("no project is open".into()))?; + workspace.apply_edits(path, version, &edits) + } + + fn storage_get(&self, key: &str) -> Result, HostError> { + Ok(self.load_storage()?.get(key).cloned()) + } + + fn storage_set(&self, key: &str, value: Option) -> Result<(), HostError> { + if key.is_empty() || key.len() > MAX_KEY { + return Err(HostError::Invalid(format!("keys are 1–{MAX_KEY} bytes"))); + } + let mut map = self.load_storage()?; + let changed = match value { + Some(v) => map.insert(key.to_owned(), v.clone()).as_ref() != Some(&v), + None => map.remove(key).is_some(), + }; + if !changed { + return Ok(()); + } + let size: usize = map.iter().map(|(k, v)| k.len() + v.len()).sum(); + if size > MAX_STORAGE { + return Err(HostError::Invalid(format!("storage is limited to {} KiB", MAX_STORAGE >> 10))); + } + self.save_storage(&map) + } + + fn storage_keys(&self, prefix: &str) -> Result, HostError> { + Ok(self.load_storage()?.into_keys().filter(|k| k.starts_with(prefix)).collect()) + } + + fn vcs_status(&self, root: &Path) -> Result, HostError> { + let Some(repo) = ide_vcs::Repo::discover(root).map_err(failed)? else { return Ok(None) }; + let info = repo.branch_info().map_err(failed)?; + let changed = repo.status().map_err(failed)?.len(); + Ok(Some(RepositoryStatus { + root: repo.root().to_string_lossy().into_owned(), + branch: info.head, + commit: info.head_commit, + upstream: info.upstream, + ahead: info.ahead, + behind: info.behind, + operation: info.operation, + changed_files: u32::try_from(changed).unwrap_or(u32::MAX), + })) + } + + fn vcs_fetch(&self, root: &Path, cancel: &CancellationToken) -> Result<(), HostError> { + let workspace = self.shared.workspace(); + if !workspace.is_some_and(|w| w.trusted(root)) { + return Err(HostError::Failed("the project is in Restricted Mode: git does not run there".into())); + } + let Some(repo) = ide_vcs::Repo::discover(root).map_err(failed)? else { + return Err(HostError::NotFound("the project is not in a git repository".into())); + }; + match repo.fetch(cancel, &|_| {}) { + Ok(()) => Ok(()), + Err(_) if cancel.is_cancelled() => Err(HostError::Cancelled), + Err(e) => Err(failed(e.message)), + } + } + + fn find_files(&self, root: &Path, glob: &str, limit: usize) -> Result, HostError> { + let matcher = globset::GlobBuilder::new(glob) + .literal_separator(true) + .build() + .map_err(|e| HostError::Invalid(format!("{glob:?}: {e}")))? + .compile_matcher(); + let mut out = Vec::new(); + for (n, entry) in ignore::WalkBuilder::new(root).hidden(true).build().flatten().enumerate() { + if n >= MAX_WALK || out.len() >= limit { + break; + } + if !entry.file_type().is_some_and(|t| t.is_file()) { + continue; + } + let Ok(rel) = entry.path().strip_prefix(root) else { continue }; + if matcher.is_match(rel) { + out.push(entry.path().to_string_lossy().into_owned()); + } + } + out.sort(); + Ok(out) + } + + fn publish_diagnostics(&self, path: &Path, items: Vec) -> Result<(), HostError> { + self.shared.publish_diagnostics(self.id(), path, items) + } + + fn fetch(&self, request: HttpRequest, cancel: &CancellationToken) -> Result { + let secrets = self.shared.secrets.read().clone(); + let id = self.id().to_owned(); + let mut headers = reqwest::header::HeaderMap::new(); + for (name, value) in &request.headers { + let value = fill_secrets(value, |n| secrets.get(&id, n))?; + let name = reqwest::header::HeaderName::from_bytes(name.as_bytes()) + .map_err(|e| HostError::Invalid(format!("header {name:?}: {e}")))?; + let mut value = reqwest::header::HeaderValue::from_str(&value) + .map_err(|e| HostError::Invalid(format!("header {name}: {e}")))?; + value.set_sensitive(true); + headers.append(name, value); + } + let method = reqwest::Method::from_bytes(request.method.to_ascii_uppercase().as_bytes()) + .map_err(|_| HostError::Invalid(format!("method {:?}", request.method)))?; + let client = ide_http::client::shared().map_err(|e| HostError::Failed(e.message))?; + // A redirect to another host is refused after the fact (the shared + // client follows redirects). + let builder = client.request(method, &request.url).headers(headers).timeout(request.timeout); + let builder = match request.body { + Some(body) => builder.body(body), + None => builder, + }; + let cancel = cancel.clone(); + let host = ide_plugin::net_host(&request.url).map_err(HostError::Invalid)?; + net_runtime().block_on(async move { + let send = async { + let response = builder.send().await.map_err(|e| HostError::Failed(e.to_string()))?; + if ide_plugin::net_host(response.url().as_str()).ok().as_deref() != Some(host.as_str()) { + return Err(HostError::Denied(format!( + "net:{} (redirected)", + response.url().host_str().unwrap_or("?") + ))); + } + let status = response.status().as_u16(); + let headers = response + .headers() + .iter() + .map(|(k, v)| (k.as_str().to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned())) + .collect(); + let mut body = Vec::new(); + let mut response = response; + while let Some(chunk) = response.chunk().await.map_err(|e| HostError::Failed(e.to_string()))? { + if body.len() + chunk.len() > MAX_RESPONSE { + return Err(HostError::Failed("response larger than 8 MiB".into())); + } + body.extend_from_slice(&chunk); + } + Ok(HttpResponse { status, headers, body }) + }; + tokio::select! { + r = send => r, + () = cancel.cancelled() => Err(HostError::Cancelled), + } + }) + } + + fn secret_is_set(&self, name: &str) -> bool { + self.shared.secrets.read().get(self.id(), name).is_some() + } + + fn run_process( + &self, + program: &str, + args: Vec, + cwd: Option<&Path>, + stdin: Option, + cancel: &CancellationToken, + timeout: Duration, + ) -> Result { + let binary = self.approved_program(program)?; + let cwd = cwd.map(Path::to_path_buf).unwrap_or_else(|| self.shared.data_dir.join(self.id())); + let _ = std::fs::create_dir_all(&cwd); + let mut child = std::process::Command::new(&binary) + .args(&args) + .current_dir(&cwd) + .stdin(if stdin.is_some() { std::process::Stdio::piped() } else { std::process::Stdio::null() }) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .map_err(|e| HostError::Failed(format!("{}: {e}", binary.display())))?; + if let (Some(input), Some(mut pipe)) = (stdin, child.stdin.take()) { + std::thread::spawn(move || { + use std::io::Write; + let _ = pipe.write_all(input.as_bytes()); + }); + } + let read = |pipe: Option>| { + std::thread::spawn(move || { + use std::io::Read; + let mut out = Vec::new(); + if let Some(p) = pipe { + let _ = p.take(MAX_OUTPUT as u64).read_to_end(&mut out); + } + String::from_utf8_lossy(&out).into_owned() + }) + }; + let stdout = read(child.stdout.take().map(|p| Box::new(p) as Box)); + let stderr = read(child.stderr.take().map(|p| Box::new(p) as Box)); + let deadline = Instant::now() + timeout; + let status = loop { + if let Some(status) = child.try_wait().map_err(|e| HostError::Failed(e.to_string()))? { + break status; + } + if cancel.is_cancelled() || Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); + return Err(if cancel.is_cancelled() { + HostError::Cancelled + } else { + HostError::Failed(format!("{program} timed out after {timeout:?}")) + }); + } + std::thread::sleep(Duration::from_millis(10)); + }; + Ok(ProcessOutput { + status: status.code(), + stdout: stdout.join().unwrap_or_default(), + stderr: stderr.join().unwrap_or_default(), + }) + } + + fn subscribe(&self, kind: EventKind, on: bool) { + let changed = { + let mut subs = self.shared.subscriptions.lock(); + let set = subs.entry(self.id().to_owned()).or_default(); + if on { set.insert(kind) } else { set.remove(&kind) } + }; + if changed { + self.shared.sink.emit(None, PluginEvent::SubscriptionsChanged); + } + } + + fn task_begin(&self, client: Option<&str>, title: String, cancellable: bool, cancel: CancellationToken) -> u64 { + let id = self.shared.next_task.fetch_add(1, Ordering::Relaxed); + self.shared.tasks.lock().insert(id, TaskEntry { plugin: self.id().to_owned(), cancel, cancelled: false }); + self.shared.sink.emit( + client, + PluginEvent::TaskStarted { plugin_id: self.id().to_owned(), task_id: id.to_string(), title, cancellable }, + ); + id + } + + fn task_report(&self, id: u64, done: u32, total: Option, message: Option) { + if !self.shared.tasks.lock().contains_key(&id) { + return; + } + self.shared.sink.emit( + None, + PluginEvent::TaskProgress { + plugin_id: self.id().to_owned(), + task_id: id.to_string(), + done, + total, + message, + }, + ); + } + + fn task_cancelled(&self, id: u64) -> bool { + self.shared.tasks.lock().get(&id).is_some_and(|t| t.cancelled) + } + + fn task_end(&self, id: u64) { + self.shared.end_task(id); + } + + fn refresh_view(&self, view: &str) { + self.shared + .sink + .emit(None, PluginEvent::ViewChanged { plugin_id: self.id().to_owned(), view: view.to_owned() }); + } + + fn post_view_message(&self, view: &str, message: String) -> Result<(), HostError> { + let declared = [super::ui_points::VIEWS, super::ui_points::CUSTOM_EDITORS] + .iter() + .any(|point| self.shared.ui.items(point, Some(self.id())).iter().any(|i| i.key == view)); + if !declared { + return Err(HostError::NotFound(format!("the plugin declares no view {view:?}"))); + } + let event = PluginEvent::ViewMessage { plugin_id: self.id().to_owned(), view: view.to_owned(), message }; + self.shared.sink.emit(None, event); + Ok(()) + } + + fn open_terminal( + &self, + client: Option<&str>, + title: String, + program: &str, + args: Vec, + cwd: Option<&Path>, + ) -> Result<(), HostError> { + let binary = self.approved_program(program)?; + let cwd = cwd.map(Path::to_path_buf).unwrap_or_else(|| self.shared.data_dir.join(self.id())); + let _ = std::fs::create_dir_all(&cwd); + let event = PluginEvent::OpenTerminal { + plugin_id: self.id().to_owned(), + title, + program: binary.into(), + args, + cwd: cwd.into(), + }; + self.shared.sink.emit(client, event); + Ok(()) + } + + fn setting(&self, root: Option<&Path>, key: &str) -> Option { + let schema: Vec = self + .shared + .ui + .items(super::ui_points::SETTINGS, Some(self.id())) + .into_iter() + .find_map(|i| serde_json::from_value(i.decl.get("properties")?.clone()).ok())?; + let setting = schema.into_iter().find(|s| s.key == key)?; + let user = self.shared.workspace().map(|w| w.plugin_settings(self.id(), root)).unwrap_or_default(); + let value = user.get(key).filter(|v| setting.accepts(v)).cloned().unwrap_or(setting.default); + serde_json::to_string(&value).ok() + } +} + +/// [`PluginWorkspace`] over the desktop host's open projects. +pub struct HostWorkspace(pub std::sync::Weak); + +impl HostWorkspace { + fn projects(&self) -> Vec> { + self.0.upgrade().map(|h| h.projects()).unwrap_or_default() + } + + /// The project holding an open document at `path`, and its id. + fn open_document(&self, path: &Path) -> Option<(Arc, ide_core::DocId)> { + self.projects().into_iter().find_map(|p| p.documents.by_path(path).map(|doc| (p, doc))) + } +} + +impl PluginWorkspace for HostWorkspace { + fn projects(&self) -> Vec { + let mut roots: Vec = HostWorkspace::projects(self).iter().map(|p| p.root.clone()).collect(); + roots.sort(); + roots.dedup(); + roots + } + + fn buffer_text(&self, path: &Path) -> Option { + HostWorkspace::projects(self).iter().find_map(|p| p.documents.text_of(path)) + } + + fn document(&self, path: &Path) -> Option<(u64, String)> { + let (project, doc) = self.open_document(path)?; + let snap = project.documents.snapshot(doc).ok()?; + Some((u64::from(snap.version), snap.text)) + } + + fn apply_edits(&self, path: &Path, version: u64, edits: &[TextEdit]) -> Result { + let (project, doc) = + self.open_document(path).ok_or_else(|| HostError::NotFound(format!("{} is not open", path.display())))?; + let version = u32::try_from(version).map_err(|_| HostError::Stale)?; + match project.documents.apply_edits_at(doc, version, edits) { + Ok(Some(v)) => Ok(u64::from(v)), + Ok(None) => Err(HostError::Stale), + Err(e) if e.kind == ide_core::error::ErrorKind::InvalidInput => Err(HostError::Invalid(e.message)), + Err(e) => Err(HostError::Failed(e.message)), + } + } + + fn trusted(&self, root: &Path) -> bool { + HostWorkspace::projects(self).iter().any(|p| p.root == root && p.is_trusted()) + } + + fn project_of(&self, window: &str) -> Option { + self.0.upgrade()?.project(window).ok().map(|p| p.root.clone()) + } + + fn publish_diagnostics( + &self, + source: &str, + path: &Path, + items: Vec, + ) -> Result<(), HostError> { + let projects = HostWorkspace::projects(self); + let project = projects + .iter() + .filter(|p| path.starts_with(&p.root)) + .max_by_key(|p| p.root.as_os_str().len()) + .ok_or_else(|| HostError::Invalid(format!("{} is not in an open project", path.display())))?; + project.sink.emit(ide_core::IdeEvent::Diagnostics { + path: path.to_path_buf().into(), + source: format!("plugin:{source}"), + items, + }); + Ok(()) + } + + fn plugin_settings(&self, plugin: &str, root: Option<&Path>) -> serde_json::Map { + let Some(host) = self.0.upgrade() else { return serde_json::Map::new() }; + let settings = match root.and_then(|r| host.projects().into_iter().find(|p| p.root == r)) { + Some(p) => p.settings.effective(), + None => host.global_settings.effective(), + }; + settings.plugins.get(plugin).cloned().unwrap_or_default() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn api(dir: &Path, pins: Arc>>) -> PluginApi { + let manifest = ide_extension::Manifest::parse( + "id = \"acme.lint\"\nname = \"Lint\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\n", + ) + .unwrap(); + let sink: Arc = Arc::new(|_: Option<&str>, _: PluginEvent| {}); + let shared = Shared::new(sink, dir.join(".data"), pins, ide_extension::UiStore::new()); + PluginApi { pkg: Package::new(manifest, dir.to_path_buf()), shared } + } + + #[test] + fn programs_run_only_as_approved() { + let tmp = tempfile::tempdir().unwrap(); + let bin = tmp.path().join("lint"); + std::fs::write(&bin, "#!/bin/sh\n").unwrap(); + let pins: Arc>> = Arc::default(); + let api = api(tmp.path(), pins.clone()); + + // Allowed while the program was missing: say how to fix it rather than "not granted". + let err = api.approved_program("lint").unwrap_err().to_string(); + assert!( + err.contains("was not found when this permission was allowed") && err.contains("allow process:lint again"), + "{err}" + ); + + pins.write().insert(("acme.lint".into(), "process:lint".into()), ProgramPin::approve(&bin).unwrap()); + assert_eq!(api.approved_program("lint").unwrap(), bin); + + std::fs::write(&bin, "#!/bin/sh\necho replaced\n").unwrap(); + assert!( + matches!(api.approved_program("lint"), Err(HostError::Denied(e)) if e.contains("changed since it was approved")) + ); + } +} diff --git a/crates/ide-host/src/plugins/icons.rs b/crates/ide-host/src/plugins/icons.rs new file mode 100644 index 00000000..729bf626 --- /dev/null +++ b/crates/ide-host/src/plugins/icons.rs @@ -0,0 +1,615 @@ +//! The `iconThemes` extension point: file and folder icons. +//! +//! ```toml +//! [[contributes.iconThemes]] +//! id = "material" +//! label = "Material Icons" +//! path = "icons/theme.json" +//! ``` +//! +//! `theme.json` (paths relative to the package): +//! +//! ```json +//! { +//! "iconDefinitions": { "rust": "icons/rust.svg", "folder-src": "icons/folder-src.svg" }, +//! "file": "file", "folder": "folder", "folderExpanded": "folder-open", +//! "fileExtensions": { "rs": "rust" }, +//! "fileNames": { "cargo.toml": "cargo" }, +//! "folderNames": { "src": "folder-src" } +//! } +//! ``` +//! +//! Every SVG is sanitised here (allow-listed elements and attributes, no +//! scripts, event handlers, external references or entities) and stored as an +//! asset; the client fetches the mapping and the icons only when the theme is +//! selected, so installed icon themes cost nothing at start-up. + +use ide_extension::{Package, UiDecl, check_relative, decode, validate_item_id}; +use serde::Deserialize; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::PathBuf; + +pub const POINT_ID: &str = "iconThemes"; +const MAX_ICONS: usize = 5000; +const MAX_SVG: usize = 64 << 10; +const MAX_MAPPINGS: usize = 20_000; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Decl { + id: String, + label: String, + path: PathBuf, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ThemeFile { + icon_definitions: BTreeMap, + #[serde(default)] + file: Option, + #[serde(default)] + folder: Option, + #[serde(default)] + folder_expanded: Option, + #[serde(default)] + file_extensions: BTreeMap, + #[serde(default)] + file_names: BTreeMap, + #[serde(default)] + folder_names: BTreeMap, +} + +/// Asset id of a theme's mapping (JSON). +pub fn map_asset(theme: &str) -> String { + format!("iconTheme/{theme}/map") +} + +/// Asset id prefix of a theme's SVGs (`…/svg/`). +pub fn svg_prefix(theme: &str) -> String { + format!("iconTheme/{theme}/svg/") +} + +/// An SVG icon of the package, size-checked and sanitised. +pub(super) fn read_icon(pkg: &Package, path: &std::path::Path) -> Result { + check_relative(path, "icon")?; + let svg = pkg.read_text(path)?; + if svg.len() > MAX_SVG { + return Err(format!("{}: larger than {} KiB", path.display(), MAX_SVG >> 10)); + } + sanitize_svg(&svg).map_err(|e| format!("{}: {e}", path.display())) +} + +pub(super) fn icon_theme(pkg: &Package, decl: toml::Value) -> Result { + let d: Decl = decode(POINT_ID, decl)?; + validate_item_id(&d.id, "icon theme id")?; + if d.label.trim().is_empty() { + return Err(format!("icon theme {:?} has an empty label", d.id)); + } + let src = pkg.read_text(&d.path)?; + let theme: ThemeFile = serde_json::from_str(&src).map_err(|e| format!("{}: {e}", d.path.display()))?; + let at = |what: &str| format!("{} ({what})", d.path.display()); + if theme.icon_definitions.len() > MAX_ICONS { + return Err(format!("{}: more than {MAX_ICONS} icons", d.path.display())); + } + let mappings = theme.file_extensions.len() + theme.file_names.len() + theme.folder_names.len(); + if mappings > MAX_MAPPINGS { + return Err(format!("{}: more than {MAX_MAPPINGS} mappings", d.path.display())); + } + let defined: BTreeSet<&str> = theme.icon_definitions.keys().map(String::as_str).collect(); + let check_ref = |icon: &str, what: &str| -> Result<(), String> { + if defined.contains(icon) { Ok(()) } else { Err(format!("{}: unknown icon {icon:?}", at(what))) } + }; + for (what, icon) in [("file", &theme.file), ("folder", &theme.folder), ("folderExpanded", &theme.folder_expanded)] { + if let Some(icon) = icon { + check_ref(icon, what)?; + } + } + // Extensions may be written with their dot (`.rs`); names keep theirs (`.github`, `.gitignore`). + let lower = |map: &BTreeMap, what: &str| -> Result, String> { + let mut out = BTreeMap::new(); + for (k, icon) in map { + check_ref(icon, what)?; + let key = k.trim(); + let key = if what == "fileExtensions" { key.trim_start_matches('.') } else { key }.to_lowercase(); + if key.is_empty() || key.contains(['/', '\\']) { + return Err(format!("{}: invalid key {k:?}", at(what))); + } + out.insert(key, icon.clone()); + } + Ok(out) + }; + let file_extensions = lower(&theme.file_extensions, "fileExtensions")?; + let file_names = lower(&theme.file_names, "fileNames")?; + let folder_names = lower(&theme.folder_names, "folderNames")?; + + let mut assets = Vec::with_capacity(theme.icon_definitions.len() + 1); + let mut files = vec![d.path.clone()]; + for (icon, path) in &theme.icon_definitions { + validate_item_id(icon, "icon id")?; + let clean = read_icon(pkg, path)?; + assets.push((format!("{}{icon}", svg_prefix(&d.id)), clean)); + files.push(path.clone()); + } + let map = serde_json::json!({ + "file": theme.file, + "folder": theme.folder, + "folderExpanded": theme.folder_expanded, + "fileExtensions": file_extensions, + "fileNames": file_names, + "folderNames": folder_names, + }); + assets.push((map_asset(&d.id), map.to_string())); + let json = serde_json::json!({ "id": d.id, "label": d.label, "icons": theme.icon_definitions.len() }); + let mut out = UiDecl::new(d.id.clone(), d.label, json); + out.files = files; + out.assets = assets; + Ok(out) +} + +// --------------------------------------------------------------------------- +// SVG sanitiser + +const ELEMENTS: &[&str] = &[ + "svg", + "g", + "path", + "circle", + "ellipse", + "line", + "polyline", + "polygon", + "rect", + "defs", + "lineargradient", + "radialgradient", + "stop", + "clippath", + "mask", + "use", + "symbol", + "pattern", + "text", + "tspan", + "filter", + "fegaussianblur", + "feoffset", + "feblend", + "fecolormatrix", + "feflood", + "fecomposite", + "femerge", + "femergenode", + "fedropshadow", +]; + +/// Dropped with their content: harmless metadata. +const STRIPPED: &[&str] = &["title", "desc", "metadata"]; + +const ATTRIBUTES: &[&str] = &[ + "id", + "class", + "viewbox", + "width", + "height", + "x", + "y", + "x1", + "y1", + "x2", + "y2", + "cx", + "cy", + "r", + "rx", + "ry", + "fx", + "fy", + "d", + "points", + "transform", + "fill", + "fill-opacity", + "fill-rule", + "clip-rule", + "clip-path", + "mask", + "stroke", + "stroke-width", + "stroke-linecap", + "stroke-linejoin", + "stroke-miterlimit", + "stroke-dasharray", + "stroke-dashoffset", + "stroke-opacity", + "opacity", + "offset", + "stop-color", + "stop-opacity", + "gradientunits", + "gradienttransform", + "spreadmethod", + "patternunits", + "patterncontentunits", + "patterntransform", + "clippathunits", + "maskunits", + "maskcontentunits", + "preserveaspectratio", + "style", + "href", + "xlink:href", + "xmlns", + "xmlns:xlink", + "version", + "font-family", + "font-size", + "font-weight", + "text-anchor", + "dominant-baseline", + "letter-spacing", + "display", + "visibility", + "color", + "filter", + "in", + "in2", + "result", + "stddeviation", + "dx", + "dy", + "mode", + "operator", + "values", + "type", + "flood-color", + "flood-opacity", + "k1", + "k2", + "k3", + "k4", + "filterunits", + "primitiveunits", + "vector-effect", + "shape-rendering", + "isolation", + "mix-blend-mode", +]; + +/// Parses `src` and re-serialises the allow-listed subset. Fails on anything +/// that could execute, fetch or escape (scripts, `foreignObject`, event +/// handlers, external `href`s, `url()` to anything but a local fragment, +/// DTDs, entities, CDATA). +pub fn sanitize_svg(src: &str) -> Result { + let mut out = String::with_capacity(src.len()); + let mut stack: Vec = Vec::new(); + // Depth inside a stripped element (its content is skipped). + let mut skip_depth = 0usize; + let mut seen_root = false; + let mut rest = src; + while !rest.is_empty() { + let Some(lt) = rest.find('<') else { + if skip_depth == 0 && !stack.is_empty() { + out.push_str(&text(rest)?); + } else if !rest.trim().is_empty() && stack.is_empty() { + return Err("text outside the element".into()); + } + break; + }; + if lt > 0 { + let t = &rest[..lt]; + if skip_depth == 0 && !stack.is_empty() { + out.push_str(&text(t)?); + } else if stack.is_empty() && !t.trim().is_empty() { + return Err("text outside the element".into()); + } + } + rest = &rest[lt..]; + if let Some(after) = rest.strip_prefix("").ok_or("unterminated comment")?; + rest = &after[end + 3..]; + continue; + } + if rest.starts_with("").ok_or("unterminated processing instruction")?; + rest = &rest[end + 2..]; + continue; + } + if rest.starts_with("').ok_or("unterminated closing tag")?; + let name = after[..end].trim().to_ascii_lowercase(); + rest = &after[end + 1..]; + let open = stack.pop().ok_or_else(|| format!("unexpected "))?; + if open != name { + return Err(format!(" does not close <{open}>")); + } + if skip_depth > 0 { + skip_depth -= 1; + } else { + out.push_str(&format!("")); + } + continue; + } + // Start tag. + let end = tag_end(rest).ok_or("unterminated tag")?; + let inner = &rest[1..end]; + rest = &rest[end + 1..]; + let self_closing = inner.trim_end().ends_with('/'); + let inner = inner.trim_end().trim_end_matches('/'); + let name_end = inner.find(|c: char| c.is_whitespace()).unwrap_or(inner.len()); + let raw_name = &inner[..name_end]; + let name = raw_name.to_ascii_lowercase(); + if name.is_empty() { + return Err("empty tag".into()); + } + if stack.is_empty() { + if seen_root || name != "svg" { + return Err("the file must contain exactly one element".into()); + } + seen_root = true; + } + if !self_closing { + stack.push(name.clone()); + } + if skip_depth > 0 { + if !self_closing { + skip_depth += 1; + } + continue; + } + if STRIPPED.contains(&name.as_str()) || name.contains(':') { + // Editor metadata (sodipodi:namedview) or descriptive text. + if !self_closing { + skip_depth = 1; + } + continue; + } + if !ELEMENTS.contains(&name.as_str()) { + return Err(format!("<{raw_name}> is not allowed")); + } + out.push('<'); + out.push_str(raw_name); + for (attr, value) in attributes(&inner[name_end..])? { + let key = attr.to_ascii_lowercase(); + if key.starts_with("on") { + return Err(format!("event handler {attr} is not allowed")); + } + if key.contains(':') && !matches!(key.as_str(), "xlink:href" | "xmlns:xlink") { + continue; // inkscape:label, sodipodi:docname, … + } + if !ATTRIBUTES.contains(&key.as_str()) && !key.starts_with("data-") && !key.starts_with("aria-") { + return Err(format!("attribute {attr} is not allowed")); + } + check_value(&key, &value).map_err(|e| format!("{attr}: {e}"))?; + out.push(' '); + out.push_str(&attr); + out.push_str("=\""); + out.push_str(&escape(&value)); + out.push('"'); + } + out.push_str(if self_closing { "/>" } else { ">" }); + } + if !stack.is_empty() { + return Err(format!("<{}> is not closed", stack.last().map(String::as_str).unwrap_or("?"))); + } + if !seen_root { + return Err("no element".into()); + } + Ok(out) +} + +/// Index of the `>` ending the tag at the start of `s`, skipping quoted values. +fn tag_end(s: &str) -> Option { + let mut quote: Option = None; + for (i, c) in s.char_indices().skip(1) { + match (quote, c) { + (Some(q), c) if c == q => quote = None, + (Some(_), _) => {} + (None, '"' | '\'') => quote = Some(c), + (None, '>') => return Some(i), + (None, '<') => return None, + _ => {} + } + } + None +} + +fn attributes(s: &str) -> Result, String> { + let mut out = Vec::new(); + let mut rest = s.trim_start(); + while !rest.is_empty() { + let eq = rest.find('=').ok_or_else(|| format!("attribute without value near {:?}", clip(rest)))?; + let name = rest[..eq].trim(); + if name.is_empty() || name.contains(|c: char| c.is_whitespace() || c == '"' || c == '\'') { + return Err(format!("malformed attribute near {:?}", clip(rest))); + } + let after = rest[eq + 1..].trim_start(); + let quote = after.chars().next().filter(|c| *c == '"' || *c == '\'').ok_or("unquoted attribute value")?; + let close = after[1..].find(quote).ok_or("unterminated attribute value")?; + let value = decode_entities(&after[1..1 + close])?; + if out.iter().any(|(n, _): &(String, String)| n.eq_ignore_ascii_case(name)) { + return Err(format!("duplicate attribute {name}")); + } + out.push((name.to_owned(), value)); + rest = after[close + 2..].trim_start(); + } + Ok(out) +} + +fn check_value(key: &str, value: &str) -> Result<(), String> { + let lower = value.to_ascii_lowercase(); + if matches!(key, "href" | "xlink:href") { + return if value.starts_with('#') { Ok(()) } else { Err("only local references (#id) are allowed".into()) }; + } + if key == "xmlns" || key == "xmlns:xlink" { + return Ok(()); + } + if lower.contains("javascript:") + || lower.contains("expression(") + || lower.contains("@import") + || value.contains('\\') + { + return Err("unsafe value".into()); + } + let mut rest = lower.as_str(); + while let Some(i) = rest.find("url(") { + let inner = rest[i + 4..].trim_start().trim_start_matches(['"', '\'']); + if !inner.starts_with('#') { + return Err("url() may only reference a local fragment".into()); + } + rest = &rest[i + 4..]; + } + Ok(()) +} + +fn decode_entities(s: &str) -> Result { + if !s.contains('&') { + return Ok(s.to_owned()); + } + let mut out = String::with_capacity(s.len()); + let mut rest = s; + while let Some(i) = rest.find('&') { + out.push_str(&rest[..i]); + let semi = rest[i..].find(';').ok_or("unterminated entity")?; + let ent = &rest[i + 1..i + semi]; + let c = match ent { + "amp" => '&', + "lt" => '<', + "gt" => '>', + "quot" => '"', + "apos" => '\'', + _ => { + let code = if let Some(hex) = ent.strip_prefix("#x").or_else(|| ent.strip_prefix("#X")) { + u32::from_str_radix(hex, 16).ok() + } else if let Some(dec) = ent.strip_prefix('#') { + dec.parse().ok() + } else { + None + }; + code.and_then(char::from_u32).ok_or_else(|| format!("entity &{ent}; is not allowed"))? + } + }; + out.push(c); + rest = &rest[i + semi + 1..]; + } + out.push_str(rest); + Ok(out) +} + +fn text(t: &str) -> Result { + Ok(escape(&decode_entities(t)?)) +} + +fn escape(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +fn clip(s: &str) -> &str { + let mut end = s.len().min(24); + while !s.is_char_boundary(end) { + end -= 1; + } + &s[..end] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keeps_ordinary_icons() { + let src = r##" + + + rust + + + +"##; + let out = sanitize_svg(src).unwrap(); + assert!(out.starts_with("")); + } + + #[test] + fn rejects_active_content() { + let bad = [ + r##""##, + r##""##, + r##""##, + r##""##, + r##""##, + r##""##, + r##""##, + r##"]>"##, + r##"x"##, + r##""##, + r##""##, + r##""##, + r##""##, + r##""##, + r##""##, + r##"hello"##, + r##""##, + ]; + for src in bad { + assert!(sanitize_svg(src).is_err(), "accepted: {src}"); + } + } + + #[test] + fn theme_files_validate_and_produce_assets() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + std::fs::create_dir_all(dir.join("icons")).unwrap(); + std::fs::write(dir.join("icons/rust.svg"), r#""#) + .unwrap(); + std::fs::write(dir.join("icons/file.svg"), r#""#) + .unwrap(); + std::fs::write( + dir.join("theme.json"), + r#"{"iconDefinitions":{"rust":"icons/rust.svg","file":"icons/file.svg"},"file":"file", + "fileExtensions":{".RS":"rust"},"fileNames":{"Cargo.toml":"rust",".gitignore":"file"}, + "folderNames":{".GitHub":"file","src":"rust"}}"#, + ) + .unwrap(); + let manifest = ide_extension::Manifest::parse( + "id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"", + ) + .unwrap(); + let pkg = Package::new(manifest, dir.to_path_buf()); + let decl = |path: &str| { + let mut t = toml::Table::new(); + t.insert("id".into(), "m".into()); + t.insert("label".into(), "M".into()); + t.insert("path".into(), path.into()); + toml::Value::Table(t) + }; + let d = icon_theme(&pkg, decl("theme.json")).unwrap(); + assert_eq!(d.json["icons"], 2); + assert_eq!(d.files.len(), 3); + let map: serde_json::Value = + serde_json::from_str(&d.assets.iter().find(|(k, _)| *k == map_asset("m")).unwrap().1).unwrap(); + assert_eq!(map["fileExtensions"]["rs"], "rust"); + assert_eq!(map["fileNames"]["cargo.toml"], "rust"); + // Names keep their leading dot (only extensions drop it). + assert_eq!(map["fileNames"][".gitignore"], "file"); + assert_eq!(map["folderNames"][".github"], "file"); + assert_eq!(map["folderNames"]["src"], "rust"); + assert!(map["folderNames"].get("github").is_none()); + assert!(d.assets.iter().any(|(k, _)| *k == format!("{}rust", svg_prefix("m")))); + + std::fs::write(dir.join("bad.json"), r#"{"iconDefinitions":{},"fileExtensions":{"rs":"nope"}}"#).unwrap(); + assert!(icon_theme(&pkg, decl("bad.json")).unwrap_err().contains("unknown icon")); + std::fs::write(dir.join("icons/evil.svg"), r#""#).unwrap(); + std::fs::write(dir.join("evil.json"), r#"{"iconDefinitions":{"e":"icons/evil.svg"}}"#).unwrap(); + assert!(icon_theme(&pkg, decl("evil.json")).unwrap_err().contains("evil.svg")); + assert!(icon_theme(&pkg, decl("../x.json")).is_err()); + } +} diff --git a/crates/ide-host/src/plugins/install.rs b/crates/ide-host/src/plugins/install.rs new file mode 100644 index 00000000..5056300a --- /dev/null +++ b/crates/ide-host/src/plugins/install.rs @@ -0,0 +1,288 @@ +//! Copying a package into the plugins directory without ever leaving the +//! plugin missing. Installed plugins are versioned: +//! `///` plus an `active` pointer file (and `previous`, +//! the version to roll back to). A new version is written to a staging +//! directory, renamed into place, and only then made active by replacing the +//! pointer; a swap interrupted by a crash is undone on the next start +//! ([`recover`]). Older installs used `//` directly; they are +//! moved into the versioned layout on their next update. + +use std::io; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// Top-level files copied with a package besides those its declarations reference. +pub const LICENSE_FILES: &[&str] = + &["LICENSE", "LICENSE.md", "LICENSE.txt", "NOTICE", "NOTICE.md", "NOTICE.txt", "COPYING", "README.md"]; +/// Written into an installed package: the package hash the grant ledger compares. +pub const HASH_FILE: &str = ".package-hash"; + +const STAGING: &str = ".staging-"; +const OLD: &str = ".old-"; +/// `/active`: the version in use. +pub const ACTIVE_FILE: &str = "active"; +/// `/previous`: the version an update replaced (for rollback). +pub const PREVIOUS_FILE: &str = "previous"; + +fn nonce() -> String { + let n = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default(); + format!("{n:x}-{}", std::process::id()) +} + +/// Copies `files` (plus manifest and licence files) from `src` into `target` +/// atomically, recording `hash`. +pub fn install_package(src: &Path, target: &Path, files: &[PathBuf], hash: &str) -> io::Result<()> { + let parent = target.parent().ok_or_else(|| io::Error::other("plugin target has no parent"))?; + let name = target.file_name().and_then(|n| n.to_str()).ok_or_else(|| io::Error::other("bad target"))?; + std::fs::create_dir_all(parent)?; + let staging = parent.join(format!("{STAGING}{name}-{}", nonce())); + let result = (|| { + std::fs::create_dir_all(&staging)?; + std::fs::copy(src.join(ide_extension::MANIFEST_FILE), staging.join(ide_extension::MANIFEST_FILE))?; + for file in files { + let to = staging.join(file); + if let Some(dir) = to.parent() { + std::fs::create_dir_all(dir)?; + } + std::fs::copy(src.join(file), to)?; + } + for lic in LICENSE_FILES { + if src.join(lic).is_file() { + std::fs::copy(src.join(lic), staging.join(lic))?; + } + } + std::fs::write(staging.join(HASH_FILE), hash)?; + swap(&staging, target, |from, to| std::fs::rename(from, to)) + })(); + if result.is_err() { + let _ = std::fs::remove_dir_all(&staging); + } + result +} + +/// A version as a directory name (semver: `[0-9A-Za-z.+-]`). +fn version_dir(version: &str) -> io::Result<&str> { + let ok = !version.is_empty() + && version.len() <= 64 + && !version.starts_with('.') + && version.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '+' | '-')); + if ok { Ok(version) } else { Err(io::Error::other(format!("version {version:?} cannot name a directory"))) } +} + +fn read_pointer(root: &Path, name: &str) -> Option { + let v = std::fs::read_to_string(root.join(name)).ok()?; + let v = v.trim(); + (!v.is_empty() && version_dir(v).is_ok()).then(|| v.to_owned()) +} + +/// Replaces the pointer file `name` atomically. +fn write_pointer(root: &Path, name: &str, version: &str) -> io::Result<()> { + let tmp = root.join(format!(".{name}.tmp")); + std::fs::write(&tmp, version)?; + std::fs::rename(&tmp, root.join(name)) +} + +/// The directory of a plugin's active version under its `root` +/// (`/`): `/`, or `root` itself in the flat layout. +pub fn active_dir(root: &Path) -> Option { + if let Some(v) = read_pointer(root, ACTIVE_FILE) { + let dir = root.join(v); + return dir.join(ide_extension::MANIFEST_FILE).is_file().then_some(dir); + } + root.join(ide_extension::MANIFEST_FILE).is_file().then(|| root.to_path_buf()) +} + +/// The version an update replaced, if it is still there. +pub fn previous_version(root: &Path) -> Option { + read_pointer(root, PREVIOUS_FILE).filter(|v| root.join(v).join(ide_extension::MANIFEST_FILE).is_file()) +} + +/// Moves a flat install (`/plugin.toml`) to `//`. +fn migrate_flat(root: &Path, version_of: impl Fn(&Path) -> Option) -> io::Result<()> { + if read_pointer(root, ACTIVE_FILE).is_some() || !root.join(ide_extension::MANIFEST_FILE).is_file() { + return Ok(()); + } + let version = version_of(root).unwrap_or_else(|| "0.0.0".into()); + let version = version_dir(&version).map(str::to_owned).unwrap_or_else(|_| "0.0.0".into()); + let parent = root.parent().unwrap_or(Path::new(".")); + let name = root.file_name().and_then(|n| n.to_str()).ok_or_else(|| io::Error::other("bad plugin directory"))?; + // `.old--…` is restored by `recover` if this is interrupted. + let old = parent.join(format!("{OLD}{name}-{}", nonce())); + std::fs::rename(root, &old)?; + std::fs::create_dir_all(root)?; + std::fs::rename(&old, root.join(&version))?; + write_pointer(root, ACTIVE_FILE, &version) +} + +/// Installs `files` of `src` as `/` and makes it the active +/// version. Returns the version it replaced (now `previous`). +pub fn install_version( + src: &Path, + root: &Path, + version: &str, + files: &[PathBuf], + hash: &str, + version_of: impl Fn(&Path) -> Option, +) -> io::Result> { + let version = version_dir(version)?; + std::fs::create_dir_all(root)?; + migrate_flat(root, version_of)?; + install_package(src, &root.join(version), files, hash)?; + let previous = read_pointer(root, ACTIVE_FILE).filter(|v| v != version); + if let Some(p) = &previous { + write_pointer(root, PREVIOUS_FILE, p)?; + } + write_pointer(root, ACTIVE_FILE, version)?; + Ok(previous) +} + +/// Makes `version` active again (rollback). The replaced version stays until [`prune`]. +pub fn activate_version(root: &Path, version: &str) -> io::Result<()> { + let version = version_dir(version)?; + if !root.join(version).join(ide_extension::MANIFEST_FILE).is_file() { + return Err(io::Error::other(format!("version {version} is not installed"))); + } + let _ = std::fs::remove_file(root.join(PREVIOUS_FILE)); + write_pointer(root, ACTIVE_FILE, version) +} + +/// Removes versions other than the active and the previous one. +pub fn prune(root: &Path) { + let keep: Vec = [ACTIVE_FILE, PREVIOUS_FILE].iter().filter_map(|f| read_pointer(root, f)).collect(); + if keep.is_empty() { + return; + } + let Ok(entries) = std::fs::read_dir(root) else { return }; + for e in entries.flatten() { + let path = e.path(); + let name = e.file_name().to_string_lossy().into_owned(); + if path.is_dir() && !keep.contains(&name) { + let _ = std::fs::remove_dir_all(&path); + } + } +} + +/// Moves `staging` to `target`, keeping the old `target` until the new one is in place. +fn swap(staging: &Path, target: &Path, rename: impl Fn(&Path, &Path) -> io::Result<()>) -> io::Result<()> { + if !target.exists() { + return rename(staging, target); + } + let parent = target.parent().unwrap_or(Path::new(".")); + let name = target.file_name().and_then(|n| n.to_str()).unwrap_or("plugin"); + let old = parent.join(format!("{OLD}{name}-{}", nonce())); + rename(target, &old)?; + if let Err(e) = rename(staging, target) { + // Put the previous version back. + rename(&old, target)?; + return Err(e); + } + if let Err(e) = std::fs::remove_dir_all(&old) { + tracing::warn!("removing the previous version {}: {e}", old.display()); + } + Ok(()) +} + +/// Undoes interrupted installs in `dir`: restores `.old--*` when +/// `` is missing, and removes leftover staging and old directories. +pub fn recover(dir: &Path) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + // Inside a versioned plugin: staging and old versions of a version swap. + if path.is_dir() && read_pointer(&path, ACTIVE_FILE).is_some() { + recover(&path); + continue; + } + let Some(file) = path.file_name().and_then(|n| n.to_str()).map(str::to_owned) else { continue }; + if file.starts_with(STAGING) { + let _ = std::fs::remove_dir_all(&path); + } else if let Some(rest) = file.strip_prefix(OLD) { + // `--`: the name is everything before the last two parts. + let parts: Vec<&str> = rest.rsplitn(3, '-').collect(); + let name = parts.get(2).copied().unwrap_or_default(); + let target = dir.join(name); + // A layout migration interrupted after creating the new root: it is still empty. + if !name.is_empty() && target.is_dir() && active_dir(&target).is_none() { + let _ = std::fs::remove_dir_all(&target); + } + if !name.is_empty() && !target.exists() { + tracing::warn!("restoring {} after an interrupted install", target.display()); + let _ = std::fs::rename(&path, &target); + } else { + let _ = std::fs::remove_dir_all(&path); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn failed_swap_keeps_the_old_version() { + let tmp = tempfile::tempdir().unwrap(); + let target = tmp.path().join("p"); + let staging = tmp.path().join(".staging-p-1"); + std::fs::create_dir_all(&target).unwrap(); + std::fs::write(target.join("v"), "1").unwrap(); + std::fs::create_dir_all(&staging).unwrap(); + std::fs::write(staging.join("v"), "2").unwrap(); + let calls = std::cell::Cell::new(0); + let err = swap(&staging, &target, |a, b| { + calls.set(calls.get() + 1); + if calls.get() == 2 { Err(io::Error::other("disk full")) } else { std::fs::rename(a, b) } + }); + assert!(err.is_err()); + assert_eq!(std::fs::read_to_string(target.join("v")).unwrap(), "1"); + swap(&staging, &target, |a, b| std::fs::rename(a, b)).unwrap(); + assert_eq!(std::fs::read_to_string(target.join("v")).unwrap(), "2"); + assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 1, "old version removed"); + } + + #[test] + fn versions_are_installed_side_by_side_and_rolled_back() { + let tmp = tempfile::tempdir().unwrap(); + let src = tmp.path().join("src"); + std::fs::create_dir_all(&src).unwrap(); + let root = tmp.path().join("plugins/acme.tools"); + let version_of = |_: &Path| Some("0.9.0".to_owned()); + // A flat install from before versioning. + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(root.join(ide_extension::MANIFEST_FILE), "v0.9").unwrap(); + assert_eq!(active_dir(&root), Some(root.clone())); + + std::fs::write(src.join(ide_extension::MANIFEST_FILE), "v1").unwrap(); + assert_eq!(install_version(&src, &root, "1.0.0", &[], "h1", version_of).unwrap().as_deref(), Some("0.9.0")); + assert_eq!(active_dir(&root), Some(root.join("1.0.0"))); + std::fs::write(src.join(ide_extension::MANIFEST_FILE), "v2").unwrap(); + assert_eq!(install_version(&src, &root, "2.0.0", &[], "h2", version_of).unwrap().as_deref(), Some("1.0.0")); + assert_eq!(previous_version(&root).as_deref(), Some("1.0.0")); + prune(&root); + assert!(!root.join("0.9.0").exists(), "older than previous: pruned"); + + activate_version(&root, "1.0.0").unwrap(); + assert_eq!( + std::fs::read_to_string(active_dir(&root).unwrap().join(ide_extension::MANIFEST_FILE)).unwrap(), + "v1" + ); + assert_eq!(previous_version(&root), None); + assert!(install_version(&src, &root, "../x", &[], "h", version_of).is_err()); + } + + #[test] + fn recover_restores_an_interrupted_swap() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(tmp.path().join(".old-acme.tools-1a2b-77")).unwrap(); + std::fs::write(tmp.path().join(".old-acme.tools-1a2b-77/v"), "1").unwrap(); + std::fs::create_dir_all(tmp.path().join(".staging-acme.tools-1a2c-77")).unwrap(); + std::fs::create_dir_all(tmp.path().join("x")).unwrap(); + std::fs::create_dir_all(tmp.path().join(".old-x-1-2")).unwrap(); + recover(tmp.path()); + assert_eq!(std::fs::read_to_string(tmp.path().join("acme.tools/v")).unwrap(), "1"); + let mut names: Vec<_> = + std::fs::read_dir(tmp.path()).unwrap().flatten().map(|e| e.file_name().into_string().unwrap()).collect(); + names.sort(); + assert_eq!(names, ["acme.tools", "x"]); + } +} diff --git a/crates/ide-host/src/plugins/market.rs b/crates/ide-host/src/plugins/market.rs new file mode 100644 index 00000000..a9e045c1 --- /dev/null +++ b/crates/ide-host/src/plugins/market.rs @@ -0,0 +1,314 @@ +//! The marketplace: a static index (`index.json` + +//! packages, served from any URL or folder) lists publishers and their keys, +//! plugins, and revocations. The host keeps the last index it read +//! (`market-index.json`), checks signatures against it, and disables what it +//! revokes — at start-up and on every refresh (the desktop refreshes daily). + +use super::{PluginHost, PluginSource, PluginStatus}; +use ide_core::{IdeError, IdeResult}; +use ide_extension::Manifest; +use ide_extension::package::{self, Index, IndexEntry, PackageSignature, SIGNATURE_FILE}; +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; + +/// The official marketplace: the index the release workflow publishes with +/// the app, next to the signed packages of the official plugins. +pub const OFFICIAL_INDEX: &str = "https://github.com/l0ng-ai/openidea/releases/latest/download/plugins-index.json"; + +/// The last index read, in the plugins directory. +pub const INDEX_FILE: &str = "market-index.json"; +const DOWNLOADS: &str = ".downloads"; +const MAX_INDEX: usize = 16 << 20; +const MAX_PACKAGE: usize = 256 << 20; + +/// A marketplace entry with what is installed. +#[derive(Clone, Debug, Serialize, Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct MarketPlugin { + #[serde(flatten)] + pub entry: IndexEntry, + /// Installed version, if any. + pub installed: Option, +} + +/// Reads `url`: `http(s)://…`, `file://…` or a local path. +pub fn read_url(url: &str, max: usize) -> Result, String> { + if url.starts_with("https://") || url.starts_with("http://") { + let client = ide_http::client::shared().map_err(|e| e.message)?; + let url = url.to_owned(); + return super::api::net_runtime().block_on(async move { + let response = client.get(&url).send().await.map_err(|e| format!("{url}: {e}"))?; + if !response.status().is_success() { + return Err(format!("{url}: HTTP {}", response.status())); + } + let bytes = response.bytes().await.map_err(|e| format!("{url}: {e}"))?; + if bytes.len() > max { + return Err(format!("{url}: larger than {} MiB", max >> 20)); + } + Ok(bytes.to_vec()) + }); + } + let path = url.strip_prefix("file://").unwrap_or(url); + let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?; + if bytes.len() > max { + return Err(format!("{path}: larger than {} MiB", max >> 20)); + } + Ok(bytes) +} + +/// `href` relative to the index at `base`: a URL, or a local path (with the +/// platform's separators, e.g. `C:\\market\\index.json`). +pub fn resolve(base: &str, href: &str) -> String { + if href.contains("://") || href.starts_with('/') || Path::new(href).is_absolute() { + return href.to_owned(); + } + if base.contains("://") { + return match base.rfind('/') { + Some(i) => format!("{}/{href}", &base[..i]), + None => href.to_owned(), + }; + } + match Path::new(base).parent() { + Some(dir) => dir.join(href).to_string_lossy().into_owned(), + None => href.to_owned(), + } +} + +impl PluginHost { + pub(super) fn load_market_index(dir: &Path) -> Option { + let text = std::fs::read_to_string(dir.join(INDEX_FILE)).ok()?; + Index::parse(&text).map_err(|e| tracing::warn!("{INDEX_FILE}: {e}")).ok() + } + + /// The marketplace index URL: the user's, else the default (none: no marketplace). + pub fn market_url(&self) -> Option { + self.state.lock().market_url.clone().or_else(|| self.default_market_url.read().clone()) + } + + /// The marketplace used while the user has set none. + pub fn set_default_market_url(&self, url: Option) { + *self.default_market_url.write() = url.filter(|u| !u.trim().is_empty()); + } + + pub fn set_market_url(&self, url: Option) { + self.state.lock().market_url = url.filter(|u| !u.trim().is_empty()); + self.save_state(); + } + + /// Reads the index again, keeps it, and applies its revocations. + pub fn refresh_market(&self) -> IdeResult> { + let url = self.market_url().ok_or_else(|| IdeError::unavailable("no plugin marketplace is configured"))?; + let bytes = read_url(&url, MAX_INDEX).map_err(IdeError::unavailable)?; + let text = String::from_utf8(bytes).map_err(|_| IdeError::invalid("the index is not UTF-8"))?; + let index = Index::parse(&text).map_err(IdeError::invalid)?; + let _ = std::fs::write(self.plugins_dir.join(INDEX_FILE), &text); + *self.market.write() = Some(index); + // Trust may have changed: who signed what, what is revoked. + let installed: Vec<_> = + self.plugins.read().values().filter(|p| p.source == PluginSource::Installed).cloned().collect(); + for plugin in installed { + let publisher = self.verified_publisher(plugin.dir()); + plugin.meta.lock().publisher = publisher; + } + self.apply_revocations(); + Ok(self.market_plugins()) + } + + /// The plugins of the last index read. + pub fn market_plugins(&self) -> Vec { + let Some(index) = self.market.read().clone() else { return Vec::new() }; + let plugins = self.plugins.read(); + index + .plugins + .iter() + .filter(|e| index.revocation(&e.id, &e.version).is_none()) + .cloned() + .map(|entry| { + let installed = plugins + .get(&entry.id) + .filter(|p| p.source == PluginSource::Installed) + .map(|p| p.manifest().version.clone()); + MarketPlugin { entry, installed } + }) + .collect() + } + + /// Downloads a marketplace plugin, checks it against the index (digest and + /// signature), and unpacks it for the install page. Returns the folder to + /// install from. + pub fn download_market_plugin(&self, id: &str) -> IdeResult { + let url = self.market_url().ok_or_else(|| IdeError::unavailable("no plugin marketplace is configured"))?; + let index = self.market.read().clone().ok_or_else(|| IdeError::unavailable("refresh the marketplace first"))?; + let entry = index + .plugins + .iter() + .find(|e| e.id == id) + .cloned() + .ok_or_else(|| IdeError::not_found(format!("{id} is not in the marketplace")))?; + let bytes = read_url(&resolve(&url, &entry.download), MAX_PACKAGE).map_err(IdeError::unavailable)?; + let downloads = self.plugins_dir.join(DOWNLOADS); + std::fs::create_dir_all(&downloads)?; + let archive = downloads.join(format!("{}-{}.{}", entry.id, entry.version, package::PACKAGE_EXTENSION)); + std::fs::write(&archive, bytes)?; + let dir = self.unpack_package(&archive)?; + let _ = std::fs::remove_file(&archive); + let manifest = Manifest::load(&dir).map_err(IdeError::invalid)?; + let files = self.package_files_in(&dir)?; + let digest = package::package_digest(&dir, &files)?; + if (manifest.id.as_str(), manifest.version.as_str(), digest.as_str()) + != (&entry.id, &entry.version, &entry.digest) + { + let _ = std::fs::remove_dir_all(&dir); + return Err(IdeError::invalid("the download does not match the marketplace's entry")); + } + if self.verified_publisher(&dir).is_none() { + let _ = std::fs::remove_dir_all(&dir); + return Err(IdeError::invalid("the marketplace package is not signed by a trusted publisher")); + } + Ok(dir) + } + + /// Unpacks a package file (`.oiplugin`, or a `.zip` of a package) next to the downloads; returns the folder. + pub fn unpack_package(&self, archive: &Path) -> IdeResult { + let stem = archive.file_stem().and_then(|s| s.to_str()).unwrap_or("package"); + let dir = self.plugins_dir.join(DOWNLOADS).join(format!("{stem}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let unpacked = package::unpack(archive, &dir).map_err(IdeError::invalid)?; + // Kept with the files: install checks it and keeps it with the installed copy. + if let Some(sig) = unpacked.signature { + let json = serde_json::to_string_pretty(&sig).map_err(|e| IdeError::internal(e.to_string()))?; + std::fs::write(dir.join(SIGNATURE_FILE), json)?; + } + Ok(dir) + } + + /// Files of the package in `dir` (what its declarations reference, and + /// the component): what a package file holds besides the manifest. + pub fn package_files_of(&self, dir: &Path) -> IdeResult> { + self.package_files_in(dir) + } + + pub(super) fn package_files_in(&self, dir: &Path) -> IdeResult> { + let manifest = Manifest::load(dir).map_err(IdeError::invalid)?; + let pkg = ide_extension::Package::new(manifest, dir.to_path_buf()); + let set = self.registry.prepare(&pkg).map_err(IdeError::invalid)?; + Ok(set.files.into_iter().chain(pkg.manifest.wasm.clone()).collect()) + } + + /// The publisher whose valid, trusted signature the package in `dir` carries. + pub(super) fn verified_publisher(&self, dir: &Path) -> Option { + let sig = read_signature(dir)?; + let index = self.market.read().clone()?; + let manifest = Manifest::load(dir).ok()?; + let files = self.package_files_in(dir).ok()?; + let digest = package::package_digest(dir, &files).ok()?; + index + .verify(&sig, &manifest.id, &manifest.version, &digest) + .map_err(|e| tracing::warn!("{}: {e}", dir.display())) + .ok() + } + + /// A signature that is present but doesn't verify (tampered, foreign prefix, + /// revoked or unknown key): installing is refused. + pub(super) fn signature_problem(&self, dir: &Path) -> Option { + let sig = read_signature(dir)?; + let manifest = Manifest::load(dir).ok()?; + let files = self.package_files_in(dir).ok()?; + let digest = package::package_digest(dir, &files).ok()?; + if let Err(e) = sig.check(&manifest.id, &manifest.version, &digest) { + return Some(e); + } + let index = self.market.read().clone()?; + index.verify(&sig, &manifest.id, &manifest.version, &digest).err() + } + + /// Why an installed plugin must not run (index revocations, revoked signing key). + pub(super) fn revoked_reason(&self, id: &str, version: &str, dir: &Path) -> Option { + let market = self.market.read(); + let index = market.as_ref()?; + if let Some(r) = index.revocation(id, version) { + return Some(r.reason.clone()); + } + let sig = read_signature(dir)?; + index.key_revoked(&sig.key).then(|| "its publisher's signing key was revoked".to_owned()) + } + + /// Disables installed plugins the index revokes (telling the user once), + /// and starts again those it no longer revokes. + pub(super) fn apply_revocations(&self) { + let installed: Vec<_> = + self.plugins.read().values().filter(|p| p.source == PluginSource::Installed).cloned().collect(); + let mut changed = false; + for plugin in installed { + let reason = self.revoked_reason(plugin.id(), &plugin.manifest().version, plugin.dir()); + let current = plugin.meta.lock().error.clone().filter(|e| e.starts_with("revoked: ")); + match (reason, current) { + (Some(r), Some(c)) if c == format!("revoked: {r}") => {} + (Some(reason), was) => { + self.stop(&plugin); + { + let mut meta = plugin.meta.lock(); + meta.status = PluginStatus::Failed; + meta.error = Some(format!("revoked: {reason}")); + } + if was.is_none() { + self.emit( + None, + super::PluginEvent::Notification { + plugin_id: plugin.id().to_owned(), + level: ide_plugin::NotificationLevel::Warning, + title: format!("{} was disabled", plugin.manifest().name), + body: format!("The marketplace revoked this plugin: {reason}"), + }, + ); + } + changed = true; + } + (None, Some(_)) => { + { + let mut meta = plugin.meta.lock(); + meta.status = PluginStatus::Inactive; + meta.error = None; + } + if !self.state.lock().disabled.contains(plugin.id()) { + self.start(&plugin); + } + changed = true; + } + (None, None) => {} + } + } + if changed { + self.changed(); + } + } +} + +pub(super) fn read_signature(dir: &Path) -> Option { + let text = std::fs::read_to_string(dir.join(SIGNATURE_FILE)).ok()?; + serde_json::from_str(&text).ok() +} + +/// Keeps the signature of a package with its installed copy. +pub(super) fn copy_signature(src: &Path, installed: &Path) { + if src.join(SIGNATURE_FILE).is_file() { + let _ = std::fs::copy(src.join(SIGNATURE_FILE), installed.join(SIGNATURE_FILE)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn downloads_resolve_against_the_index() { + assert_eq!(resolve("https://x.dev/market/index.json", "p/a.oiplugin"), "https://x.dev/market/p/a.oiplugin"); + assert_eq!( + Path::new(&resolve("/srv/market/index.json", "a.oiplugin")), + Path::new("/srv/market").join("a.oiplugin") + ); + #[cfg(windows)] + assert_eq!(resolve(r"C:\market\index.json", "a.oiplugin"), r"C:\market\a.oiplugin"); + assert_eq!(resolve("https://x.dev/index.json", "https://cdn.dev/a"), "https://cdn.dev/a"); + } +} diff --git a/crates/ide-host/src/plugins/mod.rs b/crates/ide-host/src/plugins/mod.rs new file mode 100644 index 00000000..bc0beba1 --- /dev/null +++ b/crates/ide-host/src/plugins/mod.rs @@ -0,0 +1,2288 @@ +//! The plugin host: assembles the extension +//! registry (`ide-extension`), the grant ledger and the Wasm runtime +//! (`ide-plugin`). It runs where the project is — in the desktop app for local +//! projects, in `openidea-server` for remote ones; the desktop shell only adapts +//! it to Tauri commands. +//! +//! Lifecycle of a package: its manifest is parsed and every declaration +//! validated by its extension point (no side effects); the grant ledger decides +//! whether it may load (project and new plugins wait for the user's consent); +//! then its contributions are committed all or nothing. Code is instantiated +//! only when one of its activation events fires (a command runs, or start-up +//! finished for `on-startup-finished`). +//! +//! Sources: `//` (installed), `/.openidea/plugins/*/` +//! (project plugins, loaded by [`PluginHost::sync_project`] for trusted +//! projects) and folders linked with `openidea-plugin link` (`links.json`). + +mod api; +mod icons; +mod install; +mod market; +mod points; +mod providers; +pub mod remote; +pub mod remote_host; +mod run_detectors; +mod theme; +mod types; +pub mod ui_points; +pub mod views; +pub mod web; + +pub use api::{FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore}; +pub use icons::{map_asset as icon_theme_map_asset, sanitize_svg, svg_prefix as icon_theme_svg_prefix}; +pub use market::{INDEX_FILE as MARKET_INDEX_FILE, MarketPlugin, OFFICIAL_INDEX as OFFICIAL_MARKET_INDEX}; +pub use points::{COMMANDS, CommandDecl, register_builtin_points}; +pub(crate) use providers::editor_providers as editor_providers_for; +pub use providers::{ProviderKind, set_editor_providers}; +pub use theme::{ThemeDef, ThemeKind}; +pub use types::*; + +use ide_core::{IdeError, IdeResult, LanguageId}; +use ide_extension::ledger::{self, BinaryGrant, Decision, Ledger, Request, Subject}; +use ide_extension::{ + ActivationEvent, Capability, CapabilityInfo, ContributionIndex, ExtensionRegistry, MANIFEST_FILE, Manifest, + Package, UiContribution, UiStore, +}; +use ide_language::plugin_point::PluginLanguages; +use ide_language::{LanguageConfig, ProgramPin}; +use ide_plugin::{ + Actor, ActorError, CANCELLED, CallError, HostApi, Invocation, Limits, PluginEngine, Runtime, RuntimeSetup, +}; +use parking_lot::{Condvar, Mutex, RwLock}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; +use std::ffi::OsString; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +const STATE_FILE: &str = "state.json"; +const LINKS_FILE: &str = "links.json"; +/// Project plugins live here, relative to a project root. +pub const DEV_PLUGINS_DIR: &str = ".openidea/plugins"; + +#[derive(Default, Serialize, Deserialize)] +struct PersistedState { + #[serde(default)] + disabled: BTreeSet, + #[serde(default)] + theme: Option, + /// Marketplace index URL (or folder path). + #[serde(default, skip_serializing_if = "Option::is_none")] + market_url: Option, +} + +#[derive(Clone, PartialEq, Serialize, Deserialize)] +struct ThemeRef { + plugin: String, + theme: String, + /// The theme's window frame colour as the UI resolved it (`#rrggbb[aa]`), so + /// new windows open in it before the plugin is loaded. + #[serde(default, skip_serializing_if = "Option::is_none")] + frame: Option, +} + +#[derive(Default, Serialize, Deserialize)] +struct Links { + #[serde(default)] + paths: Vec, +} + +struct Meta { + status: PluginStatus, + error: Option, + warnings: Vec, + /// Capabilities the ledger granted (valid while live). + granted: Vec, + /// Required capabilities still awaiting consent (`NeedsConsent`). + pending: Vec, + /// Capabilities the declarations need beyond the manifest (`process:` of a language server). + declared_extra: Vec, + stats: PluginStats, + /// Durations of the recent calls (ms), for the p95. + latencies: VecDeque, + /// Consecutive crashes; reset by a call that returns. + failures: u32, + /// No restart before this (backoff after a crash). + retry_at: Option, + /// The component exports `syntax-provider` (known once activated). + has_syntax: bool, + /// Next `on-schedule` activation. + next_schedule: Option, + /// The trusted publisher of a signed installed package. + publisher: Option, +} + +impl Meta { + fn new() -> Self { + Self { + status: PluginStatus::Disabled, + error: None, + warnings: Vec::new(), + granted: Vec::new(), + pending: Vec::new(), + declared_extra: Vec::new(), + stats: PluginStats::default(), + latencies: VecDeque::new(), + failures: 0, + retry_at: None, + has_syntax: false, + publisher: None, + next_schedule: None, + } + } + + fn record_call(&mut self, elapsed: Duration, ok: bool) { + let ms = elapsed.as_secs_f64() * 1000.0; + self.stats.calls += 1; + self.stats.max_call_ms = self.stats.max_call_ms.max(ms); + if !ok { + self.stats.errors += 1; + } + if self.latencies.len() == LATENCY_WINDOW { + self.latencies.pop_front(); + } + self.latencies.push_back(ms as f32); + } + + fn p95(&self) -> f64 { + if self.latencies.is_empty() { + return 0.0; + } + let mut sorted: Vec = self.latencies.iter().copied().collect(); + sorted.sort_by(f32::total_cmp); + f64::from(sorted[(sorted.len() * 95).div_ceil(100).saturating_sub(1)]) + } +} + +/// Calls kept for the latency percentile. +const LATENCY_WINDOW: usize = 128; + +/// Events waiting for one plugin (from one window). +struct EventQueue { + since: Instant, + events: Vec, +} + +/// Most events queued per plugin and window; older ones are dropped. +const MAX_QUEUED_EVENTS: usize = 500; +/// How long events for a plugin that is not running are collected before it +/// is activated to receive them. +const IDLE_BATCH: Duration = Duration::from_secs(2); + +struct LoadedPlugin { + pkg: Package, + /// The manifest failed to parse: `pkg` is a placeholder. + invalid: bool, + source: PluginSource, + /// Project that owns a project plugin. + dev_root: Option, + meta: Mutex, + /// The running instance, on its own thread. + runtime: Mutex>>, + /// Event batches handed to the actor and not finished yet. + batches: Arc>, +} + +#[derive(Default)] +struct Batches { + /// Posted, not finished. + pending: u32, + /// Kinds of the batch being handled right now. + running: Option>, +} + +impl LoadedPlugin { + /// Statistics of one call; a call that returned (`healthy`) ends a crash streak. + fn record_call(&self, elapsed: Duration, ok: bool, healthy: bool) { + let mut meta = self.meta.lock(); + meta.record_call(elapsed, ok); + if healthy && meta.failures > 0 { + meta.failures = 0; + meta.retry_at = None; + meta.error = None; + } + } + + fn id(&self) -> &str { + self.pkg.id() + } + + fn manifest(&self) -> &Manifest { + &self.pkg.manifest + } + + fn dir(&self) -> &Path { + &self.pkg.dir + } + + fn status(&self) -> PluginStatus { + self.meta.lock().status + } + + fn subject(&self) -> Subject { + match self.source { + PluginSource::Installed => Subject::Installed(self.id().to_owned()), + PluginSource::Dev | PluginSource::Linked => Subject::Path(self.dir().to_path_buf()), + } + } +} + +/// The user's answer on an install or consent page. +#[derive(Clone, Debug, Default, Serialize, Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct Consent { + /// Optional capabilities the user accepted (`net:crates.io`, …). Required + /// ones are implied by consenting at all. + pub optional: Vec, +} + +impl Consent { + /// Accept everything the plugin asks for (tests, trusted official plugins). + pub fn all() -> Self { + Self { optional: vec!["*".into()] } + } + + fn accepts(&self, cap: &Capability) -> bool { + self.optional.iter().any(|s| s == "*" || s.parse::().is_ok_and(|c| c == *cap)) + } +} + +/// What the install page shows before anything is copied. +#[derive(Clone, Debug, Serialize, Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct InstallPreview { + pub id: String, + pub name: String, + pub version: String, + pub description: String, + pub authors: Vec, + pub has_code: bool, + pub capabilities: Vec, + pub contributions: Vec, + pub warnings: Vec, + /// Version currently installed under the same id. + pub replaces: Option, + /// Not signed by a publisher the marketplace index trusts: warn the user. + pub unsigned: bool, + /// The verified publisher. + pub publisher: Option, +} + +type ProjectPolicy = Arc bool + Send + Sync>; +/// (plugin, window) of a batch of workbench events. +type QueueKey = (String, Option); +type PathVar = Arc Option + Send + Sync>; + +pub struct PluginHost { + project_policy: RwLock, + engine: PluginEngine, + plugins_dir: PathBuf, + sink: Arc, + limits: Limits, + registry: Arc, + ui: Arc, + languages: Arc, + run_detectors: Arc, + /// `[[contributes.providers]]` of enabled plugins. + providers: Arc, + /// Validated UI declarations of installed packages (start-up reuses them). + index: Arc, + ledger: Mutex, + plugins: RwLock>>, + state: Mutex, + /// What every plugin's [`api::PluginApi`] shares: sink, registry, + /// workspace, status items, tasks, subscriptions. + shared: Arc, + /// Workbench events waiting for delivery: (plugin, window) → batch. + queues: Mutex>, + /// Serializes loading / unloading so concurrent windows can't race. + lifecycle: Mutex<()>, + /// Set once the first [`load_all`](Self::load_all) has finished. + initial_load: (Mutex, Condvar), + /// `on-startup-finished` has fired. + startup_finished: AtomicBool, + /// The theme last announced with `ThemeChanged`. + announced_theme: Mutex>, + /// [`PluginLanguages::revision`] last announced with `LanguagesChanged`. + announced_languages: AtomicU64, + /// `PATH` used to resolve `process:` programs at grant time. + path_var: RwLock, + /// (plugin id, `process:` capability) → the approved program; read by the + /// language store's policy (plugin language servers and debug adapters). + pins: Arc>>, + /// The last marketplace index read: trust root for signatures, revocations. + market: RwLock>, + /// The marketplace used while the user has set none (the app's official one). + default_market_url: RwLock>, + /// Updates not confirmed yet (the new version hasn't started once): what + /// to roll back to. + updates: Mutex>, +} + +struct PendingUpdate { + previous: String, + grant: Option, +} + +impl PluginHost { + /// Creates the host; call [`load_all`](Self::load_all) to load installed plugins. + pub fn new(plugins_dir: PathBuf, sink: Arc, limits: Limits) -> IdeResult { + std::fs::create_dir_all(&plugins_dir)?; + install::recover(&plugins_dir); + let state = std::fs::read_to_string(plugins_dir.join(STATE_FILE)) + .ok() + .and_then(|s| serde_json::from_str(&s).ok()) + .unwrap_or_default(); + let registry = Arc::new(ExtensionRegistry::new()); + let ui = UiStore::new(); + let index = Arc::new(ContributionIndex::new( + plugins_dir.join(".cache").join("contributions"), + env!("CARGO_PKG_VERSION"), + )); + ui.set_index(Some(index.clone())); + let languages = PluginLanguages::new(); + let run_detectors: Arc = Arc::default(); + let providers: Arc = Arc::default(); + register_builtin_points(®istry, &ui, &languages, &run_detectors, &providers).map_err(IdeError::internal)?; + let pins: Arc>> = Arc::default(); + let policy_pins = pins.clone(); + languages.set_process_policy(Arc::new(move |plugin, cap| { + policy_pins.read().get(&(plugin.to_owned(), cap.to_string())).cloned() + })); + let shared = api::Shared::new(sink.clone(), plugins_dir.join(".data"), pins.clone(), ui.clone()); + let market = RwLock::new(Self::load_market_index(&plugins_dir)); + let host = Self { + market, + default_market_url: RwLock::new(None), + updates: Mutex::default(), + project_policy: RwLock::new(Arc::new(|_| false)), + engine: PluginEngine::new().map_err(IdeError::internal)?, + ledger: Mutex::new(Ledger::load(&plugins_dir)), + plugins_dir, + sink, + limits, + registry, + ui, + languages, + run_detectors, + providers, + index, + plugins: RwLock::default(), + state: Mutex::new(state), + shared, + queues: Mutex::default(), + lifecycle: Mutex::new(()), + initial_load: (Mutex::new(false), Condvar::new()), + startup_finished: AtomicBool::new(false), + announced_theme: Mutex::new(None), + announced_languages: AtomicU64::new(0), + path_var: RwLock::new(Arc::new(|| std::env::var_os("PATH"))), + pins, + }; + host.refresh_pins(&host.ledger.lock()); + Ok(host) + } + + pub fn plugins_dir(&self) -> &Path { + &self.plugins_dir + } + + /// The extension registry: feature crates register their points here. + pub fn registry(&self) -> &Arc { + &self.registry + } + + /// `PATH` for resolving `process:` programs when they are granted. + pub fn set_program_path(&self, path: PathVar) { + *self.path_var.write() = path; + } + + /// Loads every installed and linked package (already loaded ones are kept). + /// Instantiates no Wasm: code runs on its activation events. + pub fn load_all(&self) { + let _guard = self.lifecycle.lock(); + let dirs = package_dirs(&self.plugins_dir); + self.migrate_grants(&dirs); + for dir in dirs { + if !self.is_loaded_from(&dir) { + self.load_dir(&dir, PluginSource::Installed, None); + } + } + for dir in self.links().paths { + if !self.is_loaded_from(&dir) && dir.join(MANIFEST_FILE).is_file() { + self.load_dir(&dir, PluginSource::Linked, None); + } + } + let (done, cv) = &self.initial_load; + *done.lock() = true; + cv.notify_all(); + self.changed(); + } + + /// Fires `on-startup-finished`: activates the plugins waiting for it. + /// Plugins loaded afterwards with that event activate right away. + pub fn startup_finished(&self) { + if self.startup_finished.swap(true, Ordering::AcqRel) { + return; + } + let waiting: Vec<_> = self + .plugins + .read() + .values() + .filter(|p| { + p.status() == PluginStatus::Inactive + && p.manifest().activation.contains(&ActivationEvent::StartupFinished) + }) + .cloned() + .collect(); + for p in waiting { + let _ = self.ensure_active(&p, None); + } + self.changed(); + } + + /// Where compiled components are kept between runs. + fn component_cache(&self) -> PathBuf { + self.plugins_dir.join(".cache").join("components") + } + + /// Precompiles every loaded plugin's component that is not cached yet and + /// drops cache entries no loaded plugin uses (after an engine upgrade or an + /// uninstall), compiled components and indexed contributions alike. Slow; + /// call it on a background thread after start-up. + pub fn warm_component_cache(&self) { + let digests: Vec> = self.plugins.read().values().filter_map(|p| p.pkg.digest.clone()).collect(); + self.index.prune(digests.iter().map(|d| &**d)); + let cache = self.component_cache(); + let wasm: Vec = self + .plugins + .read() + .values() + .filter(|p| p.status() != PluginStatus::Disabled) + .filter_map(|p| p.manifest().wasm.as_ref().map(|w| p.dir().join(w))) + .collect(); + let mut keep = BTreeSet::new(); + for file in wasm { + match self.engine.precompile(&file, &cache) { + Ok(name) => { + keep.insert(name); + } + Err(e) => tracing::debug!("precompiling {}: {e}", file.display()), + } + } + if let Ok(entries) = std::fs::read_dir(&cache) { + for e in entries.flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + if !keep.contains(&name) { + let _ = std::fs::remove_file(e.path()); + } + } + } + } + + /// Fires an activation event from the UI (`on-language:rust`, `on-file:…`, `on-view:…`). + pub fn activation_event(&self, event: &ActivationEvent, project: Option<&Path>) { + let targets: Vec<_> = self + .plugins + .read() + .values() + .filter(|p| p.status() == PluginStatus::Inactive) + .filter(|p| p.dev_root.is_none() || p.dev_root.as_deref() == project) + .filter(|p| p.manifest().activation.iter().any(|a| activation_matches(a, event))) + .cloned() + .collect(); + if targets.is_empty() { + return; + } + for p in targets { + let _ = self.ensure_active(&p, None); + } + self.changed(); + } + + /// Waits (at most `timeout`) for the first [`load_all`](Self::load_all), so a + /// listing made at startup already holds the installed plugins and the + /// selected theme. Returns whether loading has finished. + pub fn wait_initial_load(&self, timeout: Duration) -> bool { + let (done, cv) = &self.initial_load; + let mut done = done.lock(); + if !*done { + cv.wait_while_for(&mut done, |d| !*d, timeout); + } + *done + } + + /// Whether project plugins of a root may load (project trust). + pub fn set_project_policy(&self, policy: ProjectPolicy) { + *self.project_policy.write() = policy; + } + + /// Unloads the project plugins of `root` (the project became untrusted or closed). + pub fn restrict_project(&self, root: &Path) { + let _guard = self.lifecycle.lock(); + let ids: Vec<_> = self + .plugins + .read() + .iter() + .filter(|(_, p)| p.dev_root.as_deref() == Some(root)) + .map(|(id, _)| id.clone()) + .collect(); + for id in ids { + self.unload(&id); + } + self.changed(); + } + + /// Loads new project plugins from `/.openidea/plugins/` (trusted + /// projects only) and unloads vanished ones. Each still needs the user's + /// consent before it runs. + pub fn sync_project(&self, root: &Path) { + if !(self.project_policy.read())(root) { + self.restrict_project(root); + return; + } + let _guard = self.lifecycle.lock(); + let dirs = package_dirs(&ide_core::project_dir::path(root, "plugins")); + let stale: Vec = self + .plugins + .read() + .iter() + .filter(|(_, p)| p.dev_root.as_deref() == Some(root) && !dirs.iter().any(|d| d == p.dir())) + .map(|(id, _)| id.clone()) + .collect(); + let mut changed = !stale.is_empty(); + for id in stale { + self.unload(&id); + } + for dir in dirs { + if !self.is_loaded_from(&dir) { + self.load_dir(&dir, PluginSource::Dev, Some(root.to_path_buf())); + changed = true; + } + } + if changed { + self.changed(); + } + } + + /// Re-reads `links.json` (written by `openidea-plugin link`): loads new + /// linked plugins and unloads unlinked ones. + pub fn sync_links(&self) { + let links = self.links().paths; + let _guard = self.lifecycle.lock(); + let stale: Vec = self + .plugins + .read() + .iter() + .filter(|(_, p)| p.source == PluginSource::Linked && !links.iter().any(|l| l == p.dir())) + .map(|(id, _)| id.clone()) + .collect(); + let mut changed = !stale.is_empty(); + for id in stale { + self.unload(&id); + } + for dir in links { + if !self.is_loaded_from(&dir) && dir.join(MANIFEST_FILE).is_file() { + self.load_dir(&dir, PluginSource::Linked, None); + changed = true; + } + } + if changed { + self.changed(); + } + } + + /// Links a development plugin folder (loaded until unlinked; granted by path). + pub fn link(&self, dir: &Path) -> IdeResult { + let dir = dunce::canonicalize(dir)?; + Manifest::load(&dir).map_err(IdeError::invalid)?; + let mut links = self.links(); + if !links.paths.contains(&dir) { + links.paths.push(dir.clone()); + self.save_links(&links)?; + } + self.sync_links(); + let id = self.plugins.read().values().find(|p| p.dir() == dir).map(|p| p.id().to_owned()); + self.info_of(&id.ok_or_else(|| IdeError::invalid("the linked plugin's id is already in use"))?) + } + + pub fn unlink(&self, id: &str) -> IdeResult<()> { + let plugin = self.get(id)?; + if plugin.source != PluginSource::Linked { + return Err(IdeError::invalid(format!("plugin {id:?} is not linked"))); + } + let mut links = self.links(); + links.paths.retain(|p| p != plugin.dir()); + self.save_links(&links)?; + self.sync_links(); + Ok(()) + } + + /// Installed and linked plugins plus the project plugins of `project`. + pub fn list(&self, project: Option<&Path>) -> PluginsSnapshot { + let visible: Vec> = self + .plugins + .read() + .values() + .filter(|p| p.dev_root.is_none() || p.dev_root.as_deref() == project) + .cloned() + .collect(); + let ids: BTreeSet<&str> = visible.iter().map(|p| p.id()).collect(); + let ui: Vec = + self.ui.snapshot().into_iter().filter(|c| ids.contains(c.plugin_id.as_str())).collect(); + let mut plugins: Vec = visible.iter().map(|p| self.info(p)).collect(); + plugins.sort_by_key(|p| p.name.to_lowercase()); + PluginsSnapshot { plugins, active_theme: self.active_theme(), ui } + } + + pub fn info_of(&self, id: &str) -> IdeResult { + let plugin = self.get(id)?; + Ok(self.info(&plugin)) + } + + /// UI contributions of one point (all live plugins). + pub fn ui_items(&self, point: &str) -> Vec { + self.ui.items(point, None) + } + + /// Validated assets of a plugin whose id starts with `prefix` (icon theme SVGs). + pub fn assets(&self, id: &str, prefix: &str) -> IdeResult> { + let plugin = self.get(id)?; + if !plugin.status().is_live() { + return Err(IdeError::unavailable(format!("plugin {id:?} is not enabled"))); + } + Ok(self.ui.assets_with_prefix(id, prefix).into_iter().map(|(k, v)| (k, v.to_string())).collect()) + } + + pub fn set_enabled(&self, id: &str, enabled: bool) -> IdeResult<()> { + let _guard = self.lifecycle.lock(); + let plugin = self.get(id)?; + { + let mut state = self.state.lock(); + if enabled { + state.disabled.remove(id) + } else { + state.disabled.insert(id.to_owned()) + }; + } + self.save_state(); + self.stop(&plugin); + if enabled { + self.start(&plugin); + } else { + plugin.meta.lock().status = PluginStatus::Disabled; + } + self.changed(); + Ok(()) + } + + /// Re-reads a plugin from disk (e.g. after rebuilding a dev plugin). + pub fn reload(&self, id: &str) -> IdeResult { + let _guard = self.lifecycle.lock(); + let plugin = self.get(id)?; + let (dir, source, root) = (plugin.dir().to_path_buf(), plugin.source, plugin.dev_root.clone()); + self.unload(id); + let new_id = self.load_dir(&dir, source, root); + self.changed(); + self.info_of(&new_id) + } + + /// Validates a package for the install page: nothing is copied or run. + pub fn preview_install(&self, src: &Path) -> IdeResult { + let (pkg, set) = self.validate_package(src)?; + if let Some(problem) = self.signature_problem(src) { + return Err(IdeError::invalid(format!("refusing {}: {problem}", pkg.id()))); + } + let publisher = self.verified_publisher(src); + let m = &pkg.manifest; + let mut capabilities: Vec = + m.capabilities.all().map(|c| CapabilityInfo::new(c, m.capabilities.is_optional(c), false)).collect(); + for extra in &set.capabilities { + if !m.declares(extra) { + capabilities.push(CapabilityInfo::new(extra, true, false)); + } + } + capabilities.sort_by(|a, b| b.risk.cmp(&a.risk).then(a.id.cmp(&b.id))); + Ok(InstallPreview { + id: m.id.clone(), + name: m.name.clone(), + version: m.version.clone(), + description: m.description.clone(), + authors: m.authors.clone(), + has_code: m.wasm.is_some(), + capabilities, + contributions: counts(m), + warnings: set.warnings.clone(), + replaces: self.plugins.read().get(&m.id).map(|p| p.manifest().version.clone()), + unsigned: publisher.is_none(), + publisher, + }) + } + + /// Installs the package in `src` (manifest + the files its declarations + /// reference) with the user's `consent`, replacing an installed version + /// with the same id atomically. + pub fn install_from_dir(&self, src: &Path, consent: &Consent) -> IdeResult { + let _guard = self.lifecycle.lock(); + let (pkg, set) = self.validate_package(src)?; + let id = pkg.id().to_owned(); + if let Some(existing) = self.plugins.read().get(&id) + && existing.source != PluginSource::Installed + { + return Err(IdeError::new( + ide_core::error::ErrorKind::AlreadyExists, + format!("a development plugin with id {id:?} is loaded from {}", existing.dir().display()), + )); + } + // A signature that doesn't hold is worse than none. + if let Some(problem) = self.signature_problem(src) { + return Err(IdeError::invalid(format!("refusing {id}: {problem}"))); + } + let version = pkg.manifest.version.clone(); + if let Some(r) = self.market.read().as_ref().and_then(|i| i.revocation(&id, &version)) { + return Err(IdeError::invalid(format!("{id} {version} was revoked: {}", r.reason))); + } + let mut files = set.files.clone(); + files.extend(pkg.manifest.wasm.clone()); + let hash = ledger::package_hash(src, &files)?; + let root = self.plugins_dir.join(&id); + let current = install::active_dir(&root); + let same_dir = dunce::canonicalize(src) + .ok() + .zip(current.as_ref().and_then(|c| dunce::canonicalize(c).ok())) + .is_some_and(|(a, b)| a == b); + let subject = Subject::Installed(id.clone()); + let old_grant = self.ledger.lock().get(&subject).cloned(); + self.unload(&id); + let previous = if same_dir { + std::fs::write(current.as_ref().expect("same dir").join(install::HASH_FILE), &hash)?; + None + } else { + let version_of = |d: &Path| Manifest::load(d).ok().map(|m| m.version); + let previous = install::install_version(src, &root, &version, &files, &hash, version_of)?; + market::copy_signature(src, &root.join(&version)); + previous + }; + // Consent covers what the install page showed. + let request = request_for(&subject, &pkg.manifest, &hash, &set.capabilities); + self.record_consent(&request, consent); + let dir = install::active_dir(&root).ok_or_else(|| IdeError::internal("the installed version is missing"))?; + self.load_dir(&dir, PluginSource::Installed, None); + if let Some(previous) = previous { + let failed = self + .get(&id) + .ok() + .filter(|p| p.status() == PluginStatus::Failed) + .map(|p| p.meta.lock().error.clone().unwrap_or_else(|| "it failed to load".into())); + if let Some(reason) = failed { + self.roll_back(&id, &previous, &version, old_grant); + self.changed(); + return Err(IdeError::invalid(format!( + "{} {version} could not start ({reason}); version {previous} was restored", + pkg.manifest.name + ))); + } + // Confirmed once the new version's code has started (or right away without code). + if pkg.manifest.wasm.is_some() { + self.updates.lock().insert(id.clone(), PendingUpdate { previous, grant: old_grant }); + } + } + install::prune(&root); + self.changed(); + self.info_of(&id) + } + + /// Makes `previous` the active version of `id` again and drops `failed` + /// (its directory, its consent). Called with the plugin unloaded or not. + fn roll_back(&self, id: &str, previous: &str, failed: &str, grant: Option) { + let root = self.plugins_dir.join(id); + self.unload(id); + if let Err(e) = install::activate_version(&root, previous) { + tracing::warn!("plugin {id}: rolling back to {previous}: {e}"); + return; + } + if failed != previous { + let _ = std::fs::remove_dir_all(root.join(failed)); + } + { + let mut ledger = self.ledger.lock(); + ledger.restore(&Subject::Installed(id.to_owned()), grant); + self.save_ledger(&ledger); + } + self.updates.lock().remove(id); + if let Some(dir) = install::active_dir(&root) { + self.load_dir(&dir, PluginSource::Installed, None); + } + } + + /// An update whose code failed to start: back to the previous version. + /// Returns the message for the user when it rolled back. + fn roll_back_failed_update( + &self, + plugin: &Arc, + reason: &str, + client: Option<&str>, + ) -> Option { + let id = plugin.id().to_owned(); + let pending = self.updates.lock().remove(&id)?; + let version = plugin.manifest().version.clone(); + let name = plugin.manifest().name.clone(); + // The caller may hold the lifecycle lock (activation during start-up): don't wait for it forever. + let _guard = self.lifecycle.try_lock_for(Duration::from_secs(5)); + self.roll_back(&id, &pending.previous, &version, pending.grant); + let message = format!("{name} {version} failed to start ({reason}); version {} was restored", pending.previous); + self.emit( + client, + PluginEvent::Notification { + plugin_id: id, + level: ide_plugin::NotificationLevel::Warning, + title: format!("{name} update rolled back"), + body: message.clone(), + }, + ); + self.changed(); + Some(message) + } + + /// Settings › Plugins › Roll Back: the version the last update replaced. + pub fn roll_back_update(&self, id: &str) -> IdeResult { + let _guard = self.lifecycle.lock(); + let plugin = self.get(id)?; + if plugin.source != PluginSource::Installed { + return Err(IdeError::invalid("only installed plugins have versions to roll back to")); + } + let root = self.plugins_dir.join(id); + let previous = install::previous_version(&root) + .ok_or_else(|| IdeError::not_found(format!("{id} has no earlier version to roll back to")))?; + let current = plugin.manifest().version.clone(); + // The earlier version's consent: what it declared, as granted now where it overlaps. + let grant = self.ledger.lock().get(&Subject::Installed(id.to_owned())).cloned(); + self.roll_back(id, &previous, ¤t, grant); + self.changed(); + self.info_of(id) + } + + /// Confirms a plugin waiting for consent (project plugins, new capabilities). + pub fn grant(&self, id: &str, consent: &Consent) -> IdeResult { + let _guard = self.lifecycle.lock(); + let plugin = self.get(id)?; + if plugin.invalid { + return Err(IdeError::invalid("the plugin's manifest is invalid")); + } + let hash = self.package_hash_of(&plugin); + let extra = plugin.meta.lock().declared_extra.clone(); + let request = request_for(&plugin.subject(), plugin.manifest(), &hash, &extra); + self.record_consent(&request, consent); + self.stop(&plugin); + if !self.state.lock().disabled.contains(id) { + self.start(&plugin); + } + self.changed(); + self.info_of(id) + } + + /// Grants or revokes one capability (Settings › Plugins › Permissions). + /// Revoking a required one stops the plugin until consent is given again. + pub fn set_capability(&self, id: &str, capability: &str, granted: bool) -> IdeResult { + let _guard = self.lifecycle.lock(); + let plugin = self.get(id)?; + let cap: Capability = capability.parse().map_err(IdeError::invalid)?; + if !plugin.manifest().declares(&cap) && !plugin.meta.lock().declared_extra.contains(&cap) { + return Err(IdeError::invalid(format!("plugin {id:?} does not declare {cap}"))); + } + { + let mut ledger = self.ledger.lock(); + let subject = plugin.subject(); + if ledger.get(&subject).is_none() { + return Err(IdeError::invalid(format!("plugin {id:?} has not been confirmed yet"))); + } + ledger.set(&subject, &cap, granted); + if granted + && let Capability::Process(program) = &cap + && let Some(bin) = self.resolve_binary(program) + { + ledger.set_binary(&subject, &cap, bin); + } + self.save_ledger(&ledger); + } + self.stop(&plugin); + if !self.state.lock().disabled.contains(id) { + self.start(&plugin); + } + self.changed(); + self.info_of(id) + } + + /// The program a `process:` grant allows, checked against the file + /// approved for it. Errors ask the user to confirm again. + pub fn program_for(&self, id: &str, program: &str) -> IdeResult { + let plugin = self.get(id)?; + let cap = Capability::Process(program.to_owned()); + self.ledger + .lock() + .check_binary(&plugin.subject(), &cap) + .map_err(|e| IdeError::new(ide_core::error::ErrorKind::PermissionDenied, e)) + } + + pub fn uninstall(&self, id: &str) -> IdeResult<()> { + let _guard = self.lifecycle.lock(); + let plugin = self.get(id)?; + if plugin.source != PluginSource::Installed { + return Err(IdeError::invalid( + "development plugins are removed by deleting them from .openidea/plugins or unlinking them", + )); + } + // Its secrets (kept outside its directory, in the OS keychain on the desktop) go with it. + let secrets: Vec = plugin + .manifest() + .contributes + .get(providers::SECRETS_POINT) + .and_then(toml::Value::as_array) + .into_iter() + .flatten() + .filter_map(|s| s.get("name")?.as_str().map(str::to_owned)) + .collect(); + self.unload(id); + { + let store = self.shared.secrets.read().clone(); + for name in &secrets { + if let Err(e) = store.set(id, name, None) { + tracing::warn!(plugin = %id, "cannot delete secret {name:?}: {e}"); + } + } + } + // Every version (`/`), or the flat directory of an older install. + let root = self.plugins_dir.join(id); + std::fs::remove_dir_all(if root.is_dir() { root } else { plugin.dir().to_path_buf() })?; + self.updates.lock().remove(id); + // Its storage goes with it. + let _ = std::fs::remove_dir_all(self.shared.data_dir.join(id)); + { + let mut ledger = self.ledger.lock(); + ledger.remove(&plugin.subject()); + self.save_ledger(&ledger); + } + { + let mut state = self.state.lock(); + state.disabled.remove(id); + if state.theme.as_ref().is_some_and(|t| t.plugin == id) { + state.theme = None; + } + } + self.save_state(); + self.changed(); + Ok(()) + } + + /// Runs a plugin command, activating the plugin first when needed + /// (`on-command`). Blocks for up to the configured time limit. + pub fn run_command( + &self, + id: &str, + command: &str, + arg: Option<&str>, + invocation: Invocation, + ) -> IdeResult> { + let (cmd, arg) = (command.to_owned(), arg.map(str::to_owned)); + self.code_call(id, invocation, "running the command", move |rt, inv| rt.run_command(&cmd, arg.as_deref(), inv)) + } + + /// Content of a declared view, or of a custom editor (`invocation.editor` + /// is its document). Activates the plugin (`on-view`). + pub fn render_view( + &self, + id: &str, + view: &str, + viewport: Option, + invocation: Invocation, + ) -> IdeResult { + self.declared_view(id, view)?; + let view = view.to_owned(); + self.code_call(id, invocation, "rendering the view", move |rt, inv| rt.render_view(&view, viewport, inv)) + } + + /// A user action in a view or custom editor. + pub fn view_event( + &self, + id: &str, + view: &str, + event: ide_plugin::ViewEvent, + invocation: Invocation, + ) -> IdeResult<()> { + self.declared_view(id, view)?; + let view = view.to_owned(); + self.code_call(id, invocation, "handling the view's event", move |rt, inv| { + rt.view_event(&view, event.clone(), inv) + }) + } + + fn declared_view(&self, id: &str, view: &str) -> IdeResult<()> { + let declared = [ui_points::VIEWS, ui_points::CUSTOM_EDITORS] + .iter() + .any(|point| self.ui.items(point, Some(id)).iter().any(|i| i.key == view)); + if declared { Ok(()) } else { Err(IdeError::not_found(format!("plugin {id:?} declares no view {view:?}"))) } + } + + /// One call into a plugin's code for the UI: checks it may run (asking + /// for missing consent), activates it, retries once when the instance was + /// reclaimed meanwhile, and reports crashes. + fn code_call( + &self, + id: &str, + invocation: Invocation, + what: &str, + f: impl Fn(&mut Runtime, Invocation) -> Result + Clone + Send + 'static, + ) -> IdeResult { + let plugin = self.get(id)?; + let client = invocation.client.clone(); + { + let meta = plugin.meta.lock(); + let reason = match meta.status { + PluginStatus::Disabled => Some(format!("plugin {id:?} is disabled")), + PluginStatus::Static => Some(format!("plugin {id:?} has no code")), + PluginStatus::NeedsConsent => Some(format!("plugin {id:?} is waiting for your permission")), + PluginStatus::Failed => { + Some(format!("plugin {id:?} is not running: {}", meta.error.as_deref().unwrap_or("failed"))) + } + PluginStatus::Active | PluginStatus::Inactive => None, + }; + if let Some(reason) = reason { + return Err(IdeError::unavailable(reason)); + } + } + let pending = plugin.meta.lock().pending.clone(); + if !pending.is_empty() { + // Migrated from 0.1: ask for what was not granted automatically, on first use. + self.emit( + client.as_deref(), + PluginEvent::ConsentRequested { + plugin_id: id.to_owned(), + capabilities: pending.iter().map(|c| CapabilityInfo::new(c, false, false)).collect(), + }, + ); + return Err(IdeError::new( + ide_core::error::ErrorKind::PermissionDenied, + format!("plugin {id:?} needs your permission first"), + )); + } + // Twice at most: the instance may be reclaimed between picking it and queueing the call. + for attempt in 0..2 { + let (actor, activated) = self.ensure_active(&plugin, client.as_deref())?; + if activated { + self.changed(); + } + let started = Instant::now(); + let (call, inv) = (f.clone(), invocation.clone()); + let result = actor.call(None, move |rt| call(rt, inv)); + if !matches!(result, Err(ActorError::Stopped | ActorError::SoftTimeout | ActorError::Cancelled)) { + let crashed = matches!(result, Err(ActorError::Call(CallError::Trap(_)))); + // Cancelling or a missing grant is not the plugin failing. + let ok = match &result { + Ok(_) => true, + Err(ActorError::Call(CallError::Guest(e))) => !e.is_failure(), + Err(_) => false, + }; + self.record_call(&plugin, started.elapsed(), ok, !crashed); + } + match result { + Ok(value) => return Ok(value), + Err(ActorError::Call(CallError::Guest(e))) => return Err(e.into()), + Err(ActorError::Call(CallError::Trap(e))) => { + self.reap(&plugin, &actor, client.as_deref()); + return Err(IdeError::internal(format!("plugin {id:?} {e}"))); + } + Err(ActorError::Stopped | ActorError::SoftTimeout | ActorError::Cancelled) => { + self.reap(&plugin, &actor, client.as_deref()); + if attempt == 1 { + break; + } + } + } + } + Err(IdeError::unavailable(format!("plugin {id:?} stopped before {what}; try again"))) + } + + /// Interrupts the plugin's running call, if any. Its instance is dropped + /// and started again on next use; this does not count as a crash. + pub fn cancel(&self, id: &str) { + if let Some(actor) = self.plugins.read().get(id).and_then(|p| p.runtime.lock().clone()) { + actor.cancel(); + } + } + + /// Runs a `syntax-provider` call of the plugin contributing `language`, + /// activating it on first use. `None` when no running plugin provides it + /// (or the call failed: the editor then shows plain text). + fn syntax_call( + &self, + language: &LanguageId, + f: impl FnOnce(&mut Runtime, Duration) -> Result + Send + 'static, + ) -> Option { + let owner = self.languages.owner_of(language)?; + let plugin = self.get(&owner).ok()?; + { + let meta = plugin.meta.lock(); + let usable = + matches!(meta.status, PluginStatus::Active | PluginStatus::Inactive) && meta.pending.is_empty(); + // Known not to provide syntax (activated before without it). + if !usable || (meta.stats.activations > 0 && !meta.has_syntax) { + return None; + } + } + plugin.manifest().wasm.as_ref()?; + let (actor, activated) = self.ensure_active(&plugin, None).ok()?; + if activated { + self.changed(); + } + if !plugin.meta.lock().has_syntax { + return None; + } + // Edit path: stop waiting at the soft deadline (the result is dropped + // but the instance kept); interrupt at the hard one. + let started = Instant::now(); + let hard = self.limits.edit_hard; + let result = actor.call(Some(self.limits.edit_soft), move |rt| f(rt, hard)); + self.finish_provider_call(&plugin, &actor, started, result) + } + + /// Plugins' `runDetectors`, for [`ide_run::set_external_detection`]. + pub fn run_detection(&self) -> Arc { + Arc::new(run_detectors::PluginRunDetection { store: self.run_detectors.clone(), pins: self.pins.clone() }) + } + + /// The syntax of plugin languages, for [`ide_language::set_external_syntax`]. + pub fn syntax_provider(self: &Arc) -> Arc { + Arc::new(PluginSyntax(Arc::downgrade(self))) + } + + /// The UI reports which file its focused editor shows (`editor-focused`). + pub fn set_active_file(&self, client: &str, path: Option) { + self.post_events(Some(client), vec![WorkbenchEvent::EditorFocused(path)]); + } + + /// Where plugin secrets are kept (default: files under the plugins + /// directory; the desktop app uses the OS keychain). + pub fn set_secret_store(&self, store: Arc) { + *self.shared.secrets.write() = store; + } + + /// Stores (or, with `None`, deletes) a secret the plugin declares under + /// `[[contributes.secrets]]`. + pub fn set_secret(&self, id: &str, name: &str, value: Option<&str>) -> IdeResult<()> { + let plugin = self.get(id)?; + if !self.ui.items(providers::SECRETS_POINT, Some(plugin.id())).iter().any(|s| s.key == name) { + return Err(IdeError::not_found(format!("plugin {id:?} declares no secret {name:?}"))); + } + let value = value.map(str::trim).filter(|v| !v.is_empty()); + self.shared.secrets.read().set(plugin.id(), name, value).map_err(IdeError::internal) + } + + /// The declared secrets of a plugin and whether each is set. + pub fn secrets(&self, id: &str) -> IdeResult> { + let plugin = self.get(id)?; + let store = self.shared.secrets.read().clone(); + Ok(self + .ui + .items(providers::SECRETS_POINT, Some(plugin.id())) + .into_iter() + .map(|s| { + let set = store.get(plugin.id(), &s.key).is_some(); + (s.key, set) + }) + .collect()) + } + + /// What plugins see of the open projects (documents, edits, trust). + pub fn set_workspace(&self, workspace: Option>) { + *self.shared.workspace.write() = workspace; + } + + /// Every plugin status bar item: (plugin, item id, item). + pub fn status_items(&self) -> Vec<(String, String, ide_plugin::StatusItem)> { + self.shared.status_items() + } + + /// The user cancelled a plugin task (`task_id` from `TaskStarted`). + pub fn cancel_task(&self, task_id: &str) -> bool { + task_id.parse().is_ok_and(|id| self.shared.cancel_task(id)) + } + + /// Kinds of workbench events some running or activatable plugin wants; + /// the UI reports only these. + pub fn event_kinds(&self) -> BTreeSet { + let subs = self.shared.subscriptions.lock().clone(); + let mut out = BTreeSet::new(); + for p in self.plugins.read().values() { + for kind in EventKind::ALL { + if self.wants(p, kind, subs.get(p.id())) { + out.insert(kind); + } + } + } + out + } + + /// Whether `plugin` gets `kind` events: subscribed at run time or with + /// `on-event:`, the capability granted, and able to run. + fn wants(&self, plugin: &LoadedPlugin, kind: EventKind, runtime: Option<&BTreeSet>) -> bool { + let declared = + plugin.manifest().activation.iter().any(|a| matches!(a, ActivationEvent::Event(k) if k == kind.name())); + if !declared && !runtime.is_some_and(|s| s.contains(&kind)) { + return false; + } + let meta = plugin.meta.lock(); + matches!(meta.status, PluginStatus::Active | PluginStatus::Inactive) + && kind.capability().is_none_or(|cap| meta.granted.iter().any(|g| g.covers(&cap))) + } + + /// Queues workbench events from window `client` for the plugins that want + /// them; [`flush_events`](Self::flush_events) delivers them in batches. + pub fn post_events(&self, client: Option<&str>, events: Vec) { + if events.is_empty() { + return; + } + let subs = self.shared.subscriptions.lock().clone(); + let plugins: Vec<_> = self.plugins.read().values().cloned().collect(); + let now = Instant::now(); + let mut queues = self.queues.lock(); + for p in plugins { + let wanted: Vec = + events.iter().filter(|e| self.wants(&p, e.kind(), subs.get(p.id()))).cloned().collect(); + if wanted.is_empty() { + continue; + } + let queue = queues + .entry((p.id().to_owned(), client.map(str::to_owned))) + .or_insert_with(|| EventQueue { since: now, events: Vec::new() }); + queue.events.extend(wanted); + let excess = queue.events.len().saturating_sub(MAX_QUEUED_EVENTS); + queue.events.drain(..excess); + } + } + + /// Delivers queued events: to running plugins right away, to idle ones + /// (which must be activated) after [`IDLE_BATCH`], so frequent events + /// don't keep waking them. Call it a few times a second. + pub fn flush_events(&self) { + self.flush_events_at(Instant::now()); + } + + #[doc(hidden)] + pub fn flush_events_at(&self, now: Instant) { + let due: Vec<(QueueKey, Vec)> = { + let mut queues = self.queues.lock(); + let plugins = self.plugins.read(); + let keys: Vec<_> = queues + .iter() + .filter(|((id, _), q)| { + let running = + plugins.get(id).is_some_and(|p| p.runtime.lock().as_ref().is_some_and(|a| a.is_alive())); + running + || now.saturating_duration_since(q.since) >= IDLE_BATCH + || q.events.len() >= MAX_QUEUED_EVENTS / 2 + || q.events.contains(&WorkbenchEvent::Scheduled) + }) + .map(|(k, _)| k.clone()) + .collect(); + keys.into_iter().filter_map(|k| queues.remove(&k).map(|q| (k, q.events))).collect() + }; + let mut changed = false; + for ((id, client), events) in due { + changed |= self.deliver(&id, client, events); + } + // Batches that crashed since. + let plugins: Vec<_> = self.plugins.read().values().cloned().collect(); + for p in plugins { + let dead = p.runtime.lock().clone().filter(|a| !a.is_alive()); + if let Some(actor) = dead { + self.reap(&p, &actor, None); + } + } + if changed { + self.changed(); + } + } + + /// Waits (at most `timeout`) until every posted event batch was handled. + /// Returns whether they all were. + #[doc(hidden)] + pub fn wait_events(&self, timeout: Duration) -> bool { + let deadline = Instant::now() + timeout; + loop { + let busy = self.plugins.read().values().any(|p| p.batches.lock().pending > 0); + if !busy { + self.flush_events_at(Instant::now()); + return true; + } + if Instant::now() >= deadline { + return false; + } + std::thread::sleep(Duration::from_millis(5)); + } + } + + /// Hands one batch to the plugin's `event-handler.handle` without waiting + /// for it. A newer batch of the same kinds cooperatively cancels the one + /// being handled (a save while the previous save is still being checked). + /// Returns whether the plugin was activated. + fn deliver(&self, id: &str, client: Option, events: Vec) -> bool { + let Ok(plugin) = self.get(id) else { return false }; + if !plugin.meta.lock().pending.is_empty() { + return false; + } + let Ok((actor, activated)) = self.ensure_active(&plugin, client.as_deref()) else { return false }; + let invocation = Invocation { + workspace_root: client.as_deref().and_then(|c| self.shared.project_of(c)), + client: client.clone(), + editor: None, + }; + let kinds: BTreeSet = events.iter().map(WorkbenchEvent::kind).collect(); + { + let mut batches = plugin.batches.lock(); + if batches.running.as_ref() == Some(&kinds) && !kinds.contains(&EventKind::Scheduled) { + actor.cancel_soft(); + } + batches.pending += 1; + } + let started = Instant::now(); + let (start, finish) = (plugin.batches.clone(), plugin.batches.clone()); + let done_plugin = plugin.clone(); + actor.post( + move |rt| { + start.lock().running = Some(kinds); + rt.handle_events(events, invocation) + }, + move |result| { + let crashed = matches!(result, Err(ActorError::Call(CallError::Trap(_)))); + if !matches!(result, Err(ActorError::Stopped)) { + done_plugin.record_call(started.elapsed(), result.is_ok(), !crashed); + } + match &result { + Err(ActorError::Call(CallError::Guest(e))) => { + tracing::debug!(plugin = %done_plugin.id(), "events: {e}") + } + Err(ActorError::Call(CallError::Trap(e))) => { + tracing::warn!(plugin = %done_plugin.id(), "events: {e}") + } + _ => {} + } + let mut batches = finish.lock(); + batches.pending = batches.pending.saturating_sub(1); + batches.running = None; + }, + ); + activated + } + + /// Selects a plugin theme (`None` restores the built-in theme). + pub fn set_theme(&self, selection: Option<(&str, &str)>) -> IdeResult> { + if let Some((plugin, theme)) = selection { + self.get(plugin)?; + if !self.ui.items(theme::POINT_ID, Some(plugin)).iter().any(|t| t.key == theme) { + return Err(IdeError::not_found(format!("plugin {plugin:?} has no theme {theme:?}"))); + } + } + self.state.lock().theme = + selection.map(|(plugin, theme)| ThemeRef { plugin: plugin.into(), theme: theme.into(), frame: None }); + self.save_state(); + let active = self.active_theme(); + *self.announced_theme.lock() = active.clone(); + self.emit(None, PluginEvent::ThemeChanged { theme: active.clone() }); + Ok(active) + } + + /// Records the selected theme's resolved window frame colour (`#rgb`, + /// `#rrggbb` or `#rrggbbaa`); ignored without a selected theme. + pub fn set_theme_frame(&self, frame: Option<&str>) -> IdeResult<()> { + if let Some(f) = frame + && !is_hex_color(f) + { + return Err(IdeError::invalid(format!("not a hex colour: {f:?}"))); + } + let changed = match self.state.lock().theme.as_mut() { + Some(t) if t.frame.as_deref() != frame => { + t.frame = frame.map(str::to_owned); + true + } + _ => false, + }; + if changed { + self.save_state(); + } + Ok(()) + } + + /// Frame colour for a new window: the recorded one of the selected theme, + /// unless its plugin is disabled. Available before plugins are loaded. + pub fn startup_frame(&self) -> Option { + let state = self.state.lock(); + let t = state.theme.as_ref()?; + if state.disabled.contains(&t.plugin) { + return None; + } + t.frame.clone() + } + + /// The selected plugin theme, when its plugin is enabled and live. + pub fn active_theme(&self) -> Option { + let sel = self.state.lock().theme.clone()?; + let item = self.ui.items(theme::POINT_ID, Some(&sel.plugin)).into_iter().find(|t| t.key == sel.theme)?; + let theme: ThemeDef = serde_json::from_value(item.decl).ok()?; + Some(ActiveTheme { plugin_id: sel.plugin, theme }) + } + + /// Languages contributed by live plugins. + pub fn languages(&self) -> Vec { + self.languages.all() + } + + /// Plugin languages for a remote project's server, with the programs each + /// plugin was granted ([`remote::RemotePluginLanguages::sync`]). + pub fn remote_languages(&self) -> Vec { + let plugins = self.plugins.read(); + let ledger = self.ledger.lock(); + self.languages + .with_owners() + .into_iter() + .map(|(plugin, language)| { + let grant = plugins.get(&plugin).and_then(|p| ledger.get(&p.subject()).cloned()); + let granted = ide_language::plugin_point::required_capabilities(&language) + .into_iter() + .filter(|cap| grant.as_ref().is_some_and(|g| g.confirmed && g.has(cap))) + .filter_map(|cap| match cap { + Capability::Process(program) => Some(program), + _ => None, + }) + .collect(); + remote::RemoteLanguage { plugin, language, granted } + }) + .collect() + } + + /// The overlay of plugin languages (for the language registry). + pub fn language_store(&self) -> &Arc { + &self.languages + } + + /// Plugin packages found in `dirs` (first occurrence of an id wins). Invalid + /// manifests are skipped; packages that fail validation carry a `problem`. + pub fn catalog(&self, dirs: &[PathBuf]) -> Vec { + let mut out: Vec = Vec::new(); + for dir in dirs.iter().flat_map(|d| package_dirs(d)) { + let Ok(m) = Manifest::load(&dir) else { continue }; + if out.iter().any(|c| c.id == m.id) { + continue; + } + let pkg = Package::new(m.clone(), dir.clone()); + let problem = match self.registry.prepare(&pkg) { + Err(e) => Some(e), + Ok(_) => m + .wasm + .as_ref() + .filter(|w| !dir.join(w).is_file()) + .map(|w| format!("{} is missing; build the plugin first", w.display())), + }; + out.push(CatalogPlugin { + has_code: m.wasm.is_some(), + capabilities: m + .capabilities + .all() + .map(|c| CapabilityInfo::new(c, m.capabilities.is_optional(c), false)) + .collect(), + contributions: counts(&m), + id: m.id, + name: m.name, + version: m.version, + description: m.description, + authors: m.authors, + homepage: m.homepage, + change_notes: m.change_notes, + path: dir.into(), + problem, + }); + } + out.sort_by_key(|a| a.name.to_lowercase()); + out + } + + /// Deactivates every plugin (also done on drop). + pub fn shutdown(&self) { + let actors: Vec<_> = self.plugins.read().values().filter_map(|p| p.runtime.lock().take()).collect(); + for a in &actors { + a.stop(false); + } + for a in actors { + a.stop(true); + } + } + + /// Periodic upkeep (every few seconds): reports crashes nobody waited + /// for, reclaims idle instances and fires due `on-schedule` activations + /// (which don't keep a plugin alive: it is reclaimed again when idle). + pub fn tick(&self) { + self.tick_at(Instant::now()); + } + + /// [`tick`](Self::tick) as if it were `now` (schedules only; tests). + #[doc(hidden)] + pub fn tick_at(&self, now: Instant) { + let plugins: Vec<_> = self.plugins.read().values().cloned().collect(); + let mut changed = false; + for p in plugins { + let actor = p.runtime.lock().clone(); + if let Some(a) = &actor { + if !a.is_alive() { + self.reap(&p, a, None); + continue; + } + if self.limits.idle_timeout.is_some_and(|idle| !a.is_busy() && a.idle_for() >= idle) { + changed |= self.reclaim(&p, a); + } + } + let every = p.manifest().activation.iter().filter_map(|e| match e { + ActivationEvent::Schedule(secs) => Some(Duration::from_secs(u64::from(*secs).max(1))), + _ => None, + }); + let Some(every) = every.min() else { continue }; + let due = { + let mut meta = p.meta.lock(); + let next = *meta.next_schedule.get_or_insert(now + every); + if next > now { + false + } else { + meta.next_schedule = Some(now + every); + meta.status == PluginStatus::Inactive && meta.pending.is_empty() + } + }; + let restricted = p.dev_root.as_deref().is_some_and(|root| !(self.project_policy.read())(root)); + if due && !restricted && self.startup_finished.load(Ordering::Acquire) { + // Activates it if needed and calls `handle([scheduled])`. + self.queues + .lock() + .entry((p.id().to_owned(), None)) + .or_insert_with(|| EventQueue { since: now, events: Vec::new() }) + .events + .push(WorkbenchEvent::Scheduled); + } + } + if changed { + self.changed(); + } + self.flush_events_at(now); + } + + /// Number of plugins with a live Wasm instance. + pub fn instances(&self) -> usize { + self.plugins.read().values().filter(|p| p.runtime.lock().as_ref().is_some_and(|a| a.is_alive())).count() + } + + // ---- internals ---- + + fn get(&self, id: &str) -> IdeResult> { + let plugin = + self.plugins.read().get(id).cloned().ok_or_else(|| IdeError::not_found(format!("no plugin {id:?}")))?; + if plugin.dev_root.as_deref().is_some_and(|root| !(self.project_policy.read())(root)) { + return Err(IdeError::unavailable("Project is in Restricted Mode")); + } + Ok(plugin) + } + + fn is_loaded_from(&self, dir: &Path) -> bool { + self.plugins.read().values().any(|p| p.dir() == dir) + } + + /// Parses and validates a package directory; nothing takes effect. + fn validate_package(&self, src: &Path) -> IdeResult<(Package, ide_extension::PreparedSet)> { + let manifest = Manifest::load(src).map_err(IdeError::invalid)?; + let pkg = Package::new(manifest, src.to_path_buf()); + let set = self.registry.prepare(&pkg).map_err(IdeError::invalid)?; + if let Some(wasm) = &pkg.manifest.wasm { + if !src.join(wasm).is_file() { + return Err(IdeError::invalid(format!( + "{} is missing (referenced by plugin.toml); build the plugin first", + wasm.display() + ))); + } + // Precompiled on the way: the installed copy has the same bytes. + let component = + self.engine.compile_cached(&src.join(wasm), &self.component_cache()).map_err(IdeError::invalid)?; + self.engine.check_component(&component).map_err(IdeError::invalid)?; + } + Ok((pkg, set)) + } + + /// Loads one package and starts it unless disabled. Returns the plugin id. + fn load_dir(&self, dir: &Path, source: PluginSource, dev_root: Option) -> String { + let (manifest, error) = match Manifest::load(dir) { + Ok(m) => (m, None), + Err(e) => (placeholder_manifest(dir), Some(e)), + }; + let invalid = error.is_some(); + let id = manifest.id.clone(); + let mut pkg = Package::new(manifest, dir.to_path_buf()); + if source == PluginSource::Installed + && let Ok(digest) = std::fs::read_to_string(dir.join(install::HASH_FILE)) + && !digest.trim().is_empty() + { + // Installed copies don't change: their validated UI declarations are indexed. + pkg = pkg.with_digest(digest.trim()); + } + let plugin = Arc::new(LoadedPlugin { + pkg, + invalid, + source, + dev_root, + meta: Mutex::new(Meta::new()), + batches: Arc::default(), + runtime: Mutex::new(None), + }); + { + let mut plugins = self.plugins.write(); + if let Some(existing) = plugins.get(&id) { + tracing::warn!( + "plugin {id:?} at {} ignored: already loaded from {}", + dir.display(), + existing.dir().display() + ); + return id; + } + plugins.insert(id.clone(), plugin.clone()); + } + if let Some(e) = error { + tracing::warn!("plugin {}: {e}", dir.display()); + let mut meta = plugin.meta.lock(); + meta.status = PluginStatus::Failed; + meta.error = Some(e); + } else if !self.state.lock().disabled.contains(&id) { + self.start(&plugin); + } + id + } + + fn unload(&self, id: &str) { + let Some(plugin) = self.plugins.write().remove(id) else { return }; + self.stop(&plugin); + } + + /// Validates, checks grants and commits the contributions; activates code + /// whose activation event already fired. + fn start(&self, plugin: &Arc) { + self.registry.dispose_plugin(plugin.id()); + if plugin.source == PluginSource::Installed + && let Some(reason) = self.revoked_reason(plugin.id(), &plugin.manifest().version, plugin.dir()) + { + return self.set_failed(plugin, format!("revoked: {reason}")); + } + if plugin.source == PluginSource::Installed { + let publisher = self.verified_publisher(plugin.dir()); + plugin.meta.lock().publisher = publisher; + } + let set = match self.registry.prepare(&plugin.pkg) { + Ok(set) => set, + Err(e) => return self.set_failed(plugin, e), + }; + let hash = self.package_hash_of(plugin); + let request = request_for(&plugin.subject(), plugin.manifest(), &hash, &set.capabilities); + let decision = { + let mut ledger = self.ledger.lock(); + let d = ledger.decide(&request); + self.save_ledger(&ledger); + d + }; + { + let mut meta = plugin.meta.lock(); + meta.warnings = set.warnings.clone(); + meta.declared_extra = set.capabilities.clone(); + meta.error = None; + } + let (granted, pending) = match decision { + Decision::Allowed { granted, pending } => (granted, pending), + Decision::NeedsConfirmation { new, .. } => { + let mut meta = plugin.meta.lock(); + meta.status = PluginStatus::NeedsConsent; + meta.pending = new; + meta.granted.clear(); + return; + } + }; + if let Err(e) = self.registry.commit(set) { + return self.set_failed(plugin, e); + } + { + let mut meta = plugin.meta.lock(); + meta.granted = granted; + meta.pending = pending; + meta.status = if plugin.manifest().wasm.is_some() { PluginStatus::Inactive } else { PluginStatus::Static }; + } + let eager = plugin.manifest().activation.contains(&ActivationEvent::StartupFinished) + && self.startup_finished.load(Ordering::Acquire); + if eager { + let _ = self.ensure_active(plugin, None); + } + } + + /// The plugin's running instance, instantiating and activating its code + /// first if needed. Returns whether it was activated now. + fn ensure_active(&self, plugin: &Arc, client: Option<&str>) -> IdeResult<(Arc, bool)> { + let mut runtime = plugin.runtime.lock(); + if let Some(actor) = runtime.as_ref() { + if actor.is_alive() { + return Ok((actor.clone(), false)); + } + // Crashed while nobody was waiting for it. + let actor = actor.clone(); + drop(runtime); + self.reap(plugin, &actor, client); + runtime = plugin.runtime.lock(); + if let Some(actor) = runtime.as_ref().filter(|a| a.is_alive()) { + return Ok((actor.clone(), false)); + } + } + if plugin.status() != PluginStatus::Inactive { + return Err(IdeError::unavailable(format!("plugin {:?} cannot be activated", plugin.id()))); + } + if let Some(wait) = plugin.meta.lock().retry_at.map(|at| at.saturating_duration_since(Instant::now())) + && !wait.is_zero() + { + return Err(IdeError::unavailable(format!( + "plugin {:?} crashed and restarts in {:.1}s", + plugin.id(), + wait.as_secs_f64() + ))); + } + let Some(wasm) = plugin.manifest().wasm.clone() else { + return Err(IdeError::unavailable(format!("plugin {:?} has no code", plugin.id()))); + }; + let started = Instant::now(); + let granted = plugin.meta.lock().granted.clone(); + let api: Arc = Arc::new(api::PluginApi { pkg: plugin.pkg.clone(), shared: self.shared.clone() }); + let setup = RuntimeSetup { + plugin_id: plugin.id().to_owned(), + version: plugin.manifest().version.clone(), + granted, + host: api, + limits: self.limits, + }; + let instance = self + .engine + .compile_cached(&plugin.dir().join(wasm), &self.component_cache()) + .and_then(|component| Runtime::instantiate(&self.engine, &component, setup)); + let mut rt = match instance { + Ok(rt) => rt, + Err(e) => { + drop(runtime); + if let Some(message) = self.roll_back_failed_update(plugin, &e, client) { + return Err(IdeError::unavailable(message)); + } + self.fail(plugin, &e, client); + return Err(IdeError::internal(format!("plugin {:?} {e}", plugin.id()))); + } + }; + let crash = match rt.activate() { + Ok(_) => None, + Err(CallError::Trap(e)) => Some(format!("activation {e}")), + Err(CallError::Guest(e)) => { + drop(runtime); + let e = format!("activation failed: {e}"); + if let Some(message) = self.roll_back_failed_update(plugin, &e, client) { + return Err(IdeError::unavailable(message)); + } + self.fail(plugin, &e, client); + return Err(IdeError::internal(format!("plugin {:?} {e}", plugin.id()))); + } + }; + if let Some(e) = crash { + drop(runtime); + if let Some(message) = self.roll_back_failed_update(plugin, &e, client) { + return Err(IdeError::unavailable(message)); + } + self.crashed(plugin, &e, client); + return Err(IdeError::internal(format!("plugin {:?} {e}", plugin.id()))); + } + // An update's first start: confirmed. + self.updates.lock().remove(plugin.id()); + let has_syntax = rt.has_syntax(); + let actor = match Actor::spawn(plugin.id(), rt) { + Ok(a) => Arc::new(a), + Err(e) => return Err(IdeError::internal(format!("plugin {:?}: {e}", plugin.id()))), + }; + *runtime = Some(actor.clone()); + let mut meta = plugin.meta.lock(); + meta.status = PluginStatus::Active; + meta.has_syntax = has_syntax; + meta.stats.activations += 1; + meta.stats.activation_ms = started.elapsed().as_secs_f64() * 1000.0; + Ok((actor, true)) + } + + fn record_call(&self, plugin: &LoadedPlugin, elapsed: Duration, ok: bool, healthy: bool) { + plugin.record_call(elapsed, ok, healthy); + } + + /// Clears `actor` from the plugin if it ended, reporting its crash once. + fn reap(&self, plugin: &LoadedPlugin, actor: &Arc, client: Option<&str>) { + if actor.is_alive() { + return; + } + { + let mut runtime = plugin.runtime.lock(); + if runtime.as_ref().is_some_and(|r| Arc::ptr_eq(r, actor)) { + *runtime = None; + } + } + let Some(error) = actor.take_crash() else { return }; + if error.starts_with(CANCELLED) { + // Cancelled on request: restart on next use, no backoff. + let mut meta = plugin.meta.lock(); + if meta.status == PluginStatus::Active { + meta.status = PluginStatus::Inactive; + } + drop(meta); + self.changed(); + return; + } + self.crashed(plugin, &error, client); + } + + /// A trap dropped the plugin's instance: restart it on next use after a + /// backoff, or stop it for the session after too many crashes in a row. + fn crashed(&self, plugin: &LoadedPlugin, error: &str, client: Option<&str>) { + let failures = { + let mut meta = plugin.meta.lock(); + meta.failures += 1; + meta.stats.crashes += 1; + meta.failures + }; + if failures >= self.limits.max_failures.max(1) { + let error = + if failures > 1 { format!("{error} (crashed {failures} times in a row)") } else { error.to_owned() }; + return self.fail(plugin, &error, client); + } + let delay = self.limits.backoff(failures); + tracing::warn!(plugin = %plugin.id(), "crashed ({failures}), restarting in {delay:?}: {error}"); + { + let mut meta = plugin.meta.lock(); + if meta.status == PluginStatus::Active { + meta.status = PluginStatus::Inactive; + } + meta.error = Some(error.to_owned()); + meta.retry_at = Some(Instant::now() + delay); + } + if failures == 1 { + self.emit( + client, + PluginEvent::Notification { + plugin_id: plugin.id().to_owned(), + level: NotificationLevel::Warning, + title: format!("Plugin \u{201c}{}\u{201d} crashed", plugin.manifest().name), + body: format!("{error}\nIt restarts the next time it is needed."), + }, + ); + } + self.changed(); + } + + /// Ends an idle instance; the plugin activates again on its next event. + fn reclaim(&self, plugin: &LoadedPlugin, actor: &Arc) -> bool { + { + let mut runtime = plugin.runtime.lock(); + if !runtime.as_ref().is_some_and(|r| Arc::ptr_eq(r, actor)) || actor.is_busy() { + return false; + } + *runtime = None; + } + actor.stop(false); + let mut meta = plugin.meta.lock(); + if meta.status == PluginStatus::Active { + meta.status = PluginStatus::Inactive; + } + meta.stats.reclaims += 1; + tracing::debug!(plugin = %plugin.id(), "reclaimed after {:?} idle", actor.idle_for()); + true + } + + fn stop(&self, plugin: &LoadedPlugin) { + if let Some(actor) = plugin.runtime.lock().take() { + actor.stop(true); + } + self.registry.dispose_plugin(plugin.id()); + self.shared.clear_plugin(plugin.id(), true); + self.queues.lock().retain(|(id, _), _| id != plugin.id()); + } + + fn set_failed(&self, plugin: &LoadedPlugin, error: String) { + tracing::warn!(plugin = %plugin.id(), "{error}"); + self.registry.dispose_plugin(plugin.id()); + let mut meta = plugin.meta.lock(); + meta.status = PluginStatus::Failed; + meta.error = Some(error); + } + + fn fail(&self, plugin: &LoadedPlugin, error: &str, client: Option<&str>) { + tracing::warn!(plugin = %plugin.id(), "disabled after failure: {error}"); + if let Some(actor) = plugin.runtime.lock().take() { + actor.stop(false); + } + self.shared.clear_plugin(plugin.id(), true); + self.set_failed(plugin, error.to_owned()); + self.emit( + client, + PluginEvent::Notification { + plugin_id: plugin.id().to_owned(), + level: NotificationLevel::Error, + title: format!("Plugin \u{201c}{}\u{201d} was disabled", plugin.manifest().name), + body: error.to_owned(), + }, + ); + self.changed(); + } + + /// Contributions or statuses changed: tell the UI and re-announce the theme if it changed. + fn changed(&self) { + // Held by this thread when called from a grant change, which refreshed them already. + if let Some(ledger) = self.ledger.try_lock() { + self.refresh_pins(&ledger); + } + self.emit(None, PluginEvent::CommandsChanged); + let languages = self.languages.revision(); + if self.announced_languages.swap(languages, Ordering::AcqRel) != languages { + self.emit(None, PluginEvent::LanguagesChanged); + } + let active = self.active_theme(); + let mut announced = self.announced_theme.lock(); + if *announced != active { + *announced = active.clone(); + drop(announced); + self.emit(None, PluginEvent::ThemeChanged { theme: active }); + } + } + + fn emit(&self, client: Option<&str>, event: PluginEvent) { + self.sink.emit(client, event); + } + + fn save_state(&self) { + let json = serde_json::to_string_pretty(&*self.state.lock()).unwrap_or_default(); + if let Err(e) = std::fs::write(self.plugins_dir.join(STATE_FILE), json) { + tracing::warn!("saving plugin state: {e}"); + } + } + + fn save_ledger(&self, ledger: &Ledger) { + if let Err(e) = ledger.save() { + tracing::warn!("saving plugin grants: {e}"); + } + self.refresh_pins(ledger); + // Grants of programs that exist only on a remote host change no local pin, + // but what a remote server may start (`LanguagesChanged` re-syncs it). + if !self.languages.with_owners().is_empty() { + self.languages.invalidate(); + } + } + + /// Recomputes the approved programs of every plugin; plugin languages + /// pick up a change on their next lookup. + fn refresh_pins(&self, ledger: &Ledger) { + let mut pins = HashMap::new(); + for plugin in self.plugins.read().values() { + let subject = plugin.subject(); + let declared = + plugin.manifest().capabilities.all().cloned().chain(plugin.meta.lock().declared_extra.clone()); + for cap in declared.filter(|c| matches!(c, Capability::Process(_))) { + if let Some(bin) = ledger.pinned_binary(&subject, &cap) { + pins.insert( + (plugin.id().to_owned(), cap.to_string()), + ProgramPin { path: bin.path, hash: bin.hash }, + ); + } + } + } + let mut current = self.pins.write(); + if *current != pins { + *current = pins; + drop(current); + self.languages.invalidate(); + } + } + + fn links(&self) -> Links { + std::fs::read_to_string(self.plugins_dir.join(LINKS_FILE)) + .ok() + .and_then(|s| serde_json::from_str(&s).ok()) + .unwrap_or_default() + } + + fn save_links(&self, links: &Links) -> IdeResult<()> { + let json = serde_json::to_string_pretty(links).map_err(|e| IdeError::internal(e.to_string()))?; + std::fs::write(self.plugins_dir.join(LINKS_FILE), json)?; + Ok(()) + } + + /// The installed package's recorded hash; development plugins are granted by path. + fn package_hash_of(&self, plugin: &LoadedPlugin) -> String { + if plugin.source != PluginSource::Installed { + return String::new(); + } + let file = plugin.dir().join(install::HASH_FILE); + if let Ok(h) = std::fs::read_to_string(&file) { + return h.trim().to_owned(); + } + // Installed before hashes were recorded: hash once and remember. + let files = self.registry.prepare(&plugin.pkg).map(|s| s.files).unwrap_or_default(); + let files: Vec = files.into_iter().chain(plugin.manifest().wasm.clone()).collect(); + let hash = ledger::package_hash(plugin.dir(), &files).unwrap_or_default(); + let _ = std::fs::write(&file, &hash); + hash + } + + /// One-time migration from 0.1, where declaring a permission granted it. + fn migrate_grants(&self, installed: &[PathBuf]) { + let mut ledger = self.ledger.lock(); + if !ledger.needs_migration() { + return; + } + let manifests: Vec = installed.iter().filter_map(|d| Manifest::load(d).ok()).collect(); + let requests: Vec> = + manifests.iter().map(|m| request_for(&Subject::Installed(m.id.clone()), m, "", &[])).collect(); + ledger.migrate(&requests); + self.save_ledger(&ledger); + } + + fn record_consent(&self, request: &Request<'_>, consent: &Consent) { + let accepted: Vec = request.optional.iter().filter(|c| consent.accepts(c)).cloned().collect(); + let binaries: BTreeMap = request + .required + .iter() + .chain(&accepted) + .filter_map(|c| match c { + Capability::Process(program) => self.resolve_binary(program).map(|b| (c.to_string(), b)), + _ => None, + }) + .collect(); + let mut ledger = self.ledger.lock(); + ledger.confirm(request, &accepted, binaries); + self.save_ledger(&ledger); + } + + fn resolve_binary(&self, program: &str) -> Option { + let path_var = (self.path_var.read())(); + let path = ledger::resolve_program(program, path_var.as_deref()) + .map_err(|e| tracing::info!("process:{program}: {e}")) + .ok()?; + let hash = ledger::file_hash(&path).ok()?; + Some(BinaryGrant { path, hash }) + } + + fn info(&self, p: &LoadedPlugin) -> PluginInfo { + let m = p.manifest(); + // The ledger before a plugin's `meta`, as everywhere (`refresh_pins` holds the + // ledger and locks each plugin's): the other order deadlocks. + let grant = self.ledger.lock().get(&p.subject()).cloned(); + let meta = p.meta.lock(); + let granted = |c: &Capability| grant.as_ref().is_some_and(|g| g.confirmed && g.has(c)); + let mut capabilities: Vec = + m.capabilities.all().map(|c| CapabilityInfo::new(c, m.capabilities.is_optional(c), granted(c))).collect(); + for extra in &meta.declared_extra { + if !m.declares(extra) { + capabilities.push(CapabilityInfo::new(extra, true, granted(extra))); + } + } + PluginInfo { + id: m.id.clone(), + name: m.name.clone(), + version: m.version.clone(), + description: m.description.clone(), + authors: m.authors.clone(), + homepage: m.homepage.clone(), + change_notes: m.change_notes.clone(), + source: p.source, + path: p.dir().to_path_buf().into(), + enabled: !self.state.lock().disabled.contains(&m.id), + status: meta.status, + error: meta.error.clone(), + has_code: m.wasm.is_some(), + capabilities, + contributions: self.registry.contributions(&m.id), + activation: m.activation.iter().map(ToString::to_string).collect(), + warnings: meta.warnings.clone(), + stats: PluginStats { p95_call_ms: meta.p95(), ..meta.stats }, + publisher: meta.publisher.clone(), + previous_version: (p.source == PluginSource::Installed) + .then(|| install::previous_version(&self.plugins_dir.join(&m.id))) + .flatten(), + } + } +} + +impl Drop for PluginHost { + fn drop(&mut self) { + self.shutdown(); + } +} + +fn request_for<'a>(subject: &Subject, m: &'a Manifest, hash: &'a str, declared: &[Capability]) -> Request<'a> { + let mut optional = m.capabilities.optional.clone(); + // What declarations need (a language server's `process:`) is optional: + // refusing it keeps the rest of the plugin working. + for cap in declared { + if !m.declares(cap) && !optional.contains(cap) { + optional.push(cap.clone()); + } + } + Request { + subject: subject.clone(), + plugin_id: &m.id, + version: &m.version, + package_hash: hash, + required: m.capabilities.required.clone(), + optional, + } +} + +fn counts(m: &Manifest) -> Vec { + m.declaration_counts().into_iter().map(|(point, count)| ContributionCount { point, count }).collect() +} + +fn activation_matches(declared: &ActivationEvent, fired: &ActivationEvent) -> bool { + match (declared, fired) { + (ActivationEvent::Language(a), ActivationEvent::Language(b)) => a == b || a == "*", + (ActivationEvent::View(a), ActivationEvent::View(b)) => a == b, + (ActivationEvent::File(glob), ActivationEvent::File(path)) => glob_match(glob, path), + _ => false, + } +} + +/// `**` matches across `/`, `*` and `?` within one segment. +fn glob_match(glob: &str, path: &str) -> bool { + fn go(p: &[u8], s: &[u8]) -> bool { + match p.first() { + None => s.is_empty(), + Some(b'*') if p.get(1) == Some(&b'*') => { + let rest = p[2..].strip_prefix(b"/").unwrap_or(&p[2..]); + if rest.is_empty() { + return true; + } + (0..=s.len()).any(|i| (i == 0 || s[i - 1] == b'/') && go(rest, &s[i..])) || go(rest, s) + } + Some(b'*') => (0..=s.len()).take_while(|&i| i == 0 || s[i - 1] != b'/').any(|i| go(&p[1..], &s[i..])), + Some(b'?') => s.first().is_some_and(|c| *c != b'/') && go(&p[1..], &s[1..]), + Some(c) => s.first() == Some(c) && go(&p[1..], &s[1..]), + } + } + go(glob.as_bytes(), path.as_bytes()) +} + +fn is_hex_color(s: &str) -> bool { + s.strip_prefix('#').is_some_and(|h| matches!(h.len(), 3 | 6 | 8) && h.bytes().all(|b| b.is_ascii_hexdigit())) +} + +/// Subdirectories of `dir` that contain a `plugin.toml`, sorted. +/// The active version of every installed plugin (`/`, or `` +/// for installs from before versioning). +fn package_dirs(dir: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut dirs: Vec = entries + .flatten() + .map(|e| e.path()) + .filter(|p| !p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with('.'))) + .filter_map(|p| install::active_dir(&p)) + .collect(); + dirs.sort(); + dirs +} + +/// Stand-in for a package whose manifest failed to parse, so it still shows up (as failed). +fn placeholder_manifest(dir: &Path) -> Manifest { + let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + Manifest { + id: format!("invalid-{}", name.to_lowercase().replace(|c: char| !c.is_ascii_alphanumeric(), "-")), + name, + version: "0.0.0".into(), + description: String::new(), + authors: Vec::new(), + homepage: None, + license: None, + change_notes: None, + engine: ide_extension::ENGINE_VERSION.into(), + legacy: false, + wasm: None, + activation: Vec::new(), + capabilities: Default::default(), + contributes: Default::default(), + } +} + +/// [`PluginHost::syntax_provider`]: plugin languages' `syntax-provider` exports. +struct PluginSyntax(std::sync::Weak); + +type SyntaxFn = fn(&mut Runtime, &str, &str, Duration) -> Result; + +/// A syntax call with its own copies of the arguments, to run on the plugin's thread. +fn owned( + lang: &LanguageId, + text: &str, + f: SyntaxFn, +) -> impl FnOnce(&mut Runtime, Duration) -> Result + Send + 'static { + let (lang, text) = (lang.as_str().to_owned(), text.to_owned()); + move |rt, timeout| f(rt, &lang, &text, timeout) +} + +impl ide_language::ExternalSyntax for PluginSyntax { + fn highlights(&self, lang: &LanguageId, text: &str) -> Option> { + let tokens = self.0.upgrade()?.syntax_call(lang, owned(lang, text, Runtime::syntax_highlights))?; + Some( + tokens + .into_iter() + .map(|t| ide_language::ExternalToken { start: t.start, end: t.end, kind: t.kind }) + .collect(), + ) + } + + fn outline(&self, lang: &LanguageId, text: &str) -> Option> { + let symbols = self.0.upgrade()?.syntax_call(lang, owned(lang, text, Runtime::syntax_outline))?; + Some( + symbols + .into_iter() + .map(|s| ide_language::ExternalSymbol { + name: s.name, + detail: s.detail, + kind: s.kind, + start: s.start, + end: s.end, + name_start: s.name_start, + name_end: s.name_end, + parent: s.parent, + }) + .collect(), + ) + } + + fn folding(&self, lang: &LanguageId, text: &str) -> Option> { + let folds = self.0.upgrade()?.syntax_call(lang, owned(lang, text, Runtime::syntax_folding))?; + Some( + folds + .into_iter() + .map(|f| ide_language::ExternalFold { start_line: f.start_line, end_line: f.end_line, kind: f.kind }) + .collect(), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn globs() { + assert!(glob_match("**/*Mapper.xml", "src/main/UserMapper.xml")); + assert!(glob_match("**/*Mapper.xml", "UserMapper.xml")); + assert!(!glob_match("*.xml", "a/b.xml")); + assert!(glob_match("pom.xml", "pom.xml")); + assert!(glob_match("src/**", "src/a/b")); + assert!(glob_match("a?c", "abc") && !glob_match("a?c", "a/c")); + } +} diff --git a/crates/ide-host/src/plugins/points.rs b/crates/ide-host/src/plugins/points.rs new file mode 100644 index 00000000..bdf23c66 --- /dev/null +++ b/crates/ide-host/src/plugins/points.rs @@ -0,0 +1,71 @@ +//! First-party extension points registered by the host, plus +//! [`register_builtin_points`], the one place that lists them. Feature crates +//! own their points (`ide_language::plugin_point`); adding a contribution type +//! means adding a point here or in its crate, and a `defineUiPoint` projection +//! on the client for `Ui` points — nothing else. + +use ide_extension::{ExtensionRegistry, Package, UiDecl, UiPoint, UiStore, decode, validate_item_id, validate_when}; +use ide_language::plugin_point::{LanguagesPoint, PluginLanguages}; +use serde::{Deserialize, Serialize}; +use std::sync::Arc; + +pub const COMMANDS: &str = "commands"; +const MAX_TITLE: usize = 256; + +/// `[[contributes.commands]]`: an action `plugin..` in Search +/// Everywhere and the keymap editor; shown before the plugin's code runs. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, specta::Type)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CommandDecl { + pub id: String, + pub title: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub category: Option, + /// Enablement, evaluated by the client against context keys (`editorLang == rust`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub when: Option, +} + +fn command(_pkg: &Package, decl: toml::Value) -> Result { + let c: CommandDecl = decode(COMMANDS, decl)?; + validate_item_id(&c.id, "command id")?; + if c.title.trim().is_empty() { + return Err(format!("command {:?} has an empty title", c.id)); + } + if c.title.len() > MAX_TITLE || c.category.as_ref().is_some_and(|x| x.len() > MAX_TITLE) { + return Err(format!("command {:?}: title or category longer than {MAX_TITLE} bytes", c.id)); + } + if let Some(when) = &c.when { + validate_when(when).map_err(|e| format!("command {:?}: {e}", c.id))?; + } + let c = CommandDecl { category: c.category.filter(|x| !x.trim().is_empty()), ..c }; + let json = serde_json::to_value(&c).map_err(|e| e.to_string())?; + Ok(UiDecl::new(c.id.clone(), c.title, json)) +} + +/// Registers every first-party extension point. +pub fn register_builtin_points( + registry: &ExtensionRegistry, + ui: &Arc, + languages: &Arc, + run_detectors: &Arc, + providers: &Arc, +) -> Result<(), String> { + registry.register(Arc::new(UiPoint::new(COMMANDS, ui.clone(), command)))?; + registry.register(Arc::new(super::theme::ThemesPoint::new(ui.clone())))?; + registry.register(Arc::new(LanguagesPoint::new(languages.clone())))?; + registry.register(Arc::new(UiPoint::new(super::icons::POINT_ID, ui.clone(), super::icons::icon_theme)))?; + registry.register(Arc::new(super::run_detectors::RunDetectorsPoint::new(run_detectors.clone())))?; + registry.register(Arc::new(super::providers::ProvidersPoint::new(providers.clone())))?; + registry.register(Arc::new(UiPoint::new(super::providers::SECRETS_POINT, ui.clone(), super::providers::secret)))?; + use super::ui_points as p; + registry.register(Arc::new(UiPoint::new(p::MENUS, ui.clone(), p::menu)))?; + registry.register(Arc::new(UiPoint::new(p::KEYMAPS, ui.clone(), p::keymap)))?; + registry.register(Arc::new(UiPoint::new(p::STATUS_BAR, ui.clone(), p::status_item)))?; + registry.register(Arc::new(UiPoint::new(p::SETTINGS, ui.clone(), p::settings)))?; + registry.register(Arc::new(UiPoint::new(p::VIEWS, ui.clone(), p::view)))?; + registry.register(Arc::new(UiPoint::new(p::CUSTOM_EDITORS, ui.clone(), p::custom_editor)))?; + registry.register(Arc::new(UiPoint::new(p::FILE_ICONS, ui.clone(), p::file_icon)))?; + registry.register(Arc::new(UiPoint::new(p::FILE_TEMPLATES, ui.clone(), p::file_template)))?; + Ok(()) +} diff --git a/crates/ide-host/src/plugins/providers.rs b/crates/ide-host/src/plugins/providers.rs new file mode 100644 index 00000000..d60b806a --- /dev/null +++ b/crates/ide-host/src/plugins/providers.rs @@ -0,0 +1,342 @@ +//! Editor providers of plugins: completion, inline +//! completion, code actions, go to definition and gutter line markers, for +//! the languages a plugin declares. The host calls only plugins whose +//! declaration matches, so the others stay unloaded. +//! +//! ```toml +//! [[contributes.providers]] +//! kinds = ["definition", "line-markers"] +//! languages = ["java", "xml"] # editor language ids; "*" for any +//! ``` +//! +//! And `[[contributes.secrets]]`: secrets the user can store for the plugin +//! (shown in Settings › Plugins), used only through `net` request headers. +//! +//! ```toml +//! [[contributes.secrets]] +//! name = "api-key" +//! label = "API key" +//! description = "Create one at https://example.com/keys" +//! ``` + +use ide_extension::{Disposable, ExtensionPoint, Package, Placement, Prepared, UiDecl, decode, validate_item_id}; +use parking_lot::RwLock; +use serde::{Deserialize, Serialize}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +pub const POINT_ID: &str = "providers"; +pub const SECRETS_POINT: &str = "secrets"; + +/// What a plugin can provide in the editor. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, specta::Type)] +#[serde(rename_all = "kebab-case")] +pub enum ProviderKind { + Completion, + InlineCompletion, + CodeActions, + Definition, + LineMarkers, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct Decl { + kinds: Vec, + languages: Vec, +} + +/// (sequence, plugin, kinds, languages) of one declaration. +type Declared = (u64, String, Vec, Vec); + +/// Provider declarations of enabled plugins. +#[derive(Default)] +pub struct Providers { + items: RwLock>, + seq: AtomicU64, +} + +impl Providers { + fn add(self: &Arc, plugin: String, decl: Decl) -> Disposable { + let seq = self.seq.fetch_add(1, Ordering::Relaxed); + self.items.write().push((seq, plugin, decl.kinds, decl.languages)); + let weak = Arc::downgrade(self); + Disposable::new(move || { + if let Some(this) = weak.upgrade() { + this.items.write().retain(|(s, ..)| *s != seq); + } + }) + } + + /// Plugins providing `kind` for `language`, in declaration order. + pub fn plugins_for(&self, kind: ProviderKind, language: &str) -> Vec { + let mut out: Vec = Vec::new(); + for (_, plugin, kinds, languages) in self.items.read().iter() { + if kinds.contains(&kind) && languages.iter().any(|l| l == "*" || l == language) && !out.contains(plugin) { + out.push(plugin.clone()); + } + } + out + } + + /// Whether any plugin provides `kind` (for any language). + pub fn any(&self, kind: ProviderKind) -> bool { + self.items.read().iter().any(|(_, _, kinds, _)| kinds.contains(&kind)) + } +} + +pub struct ProvidersPoint { + store: Arc, +} + +impl ProvidersPoint { + pub fn new(store: Arc) -> Self { + Self { store } + } +} + +impl ExtensionPoint for ProvidersPoint { + fn id(&self) -> &'static str { + POINT_ID + } + + fn placement(&self) -> Placement { + Placement::Workspace + } + + fn prepare(&self, pkg: &Package, decl: toml::Value) -> Result { + let d: Decl = decode(POINT_ID, decl)?; + if pkg.manifest.wasm.is_none() { + return Err("contributes.providers: providers need code (`wasm`)".into()); + } + if d.kinds.is_empty() || d.languages.is_empty() || d.languages.len() > 64 { + return Err("contributes.providers: give `kinds` and 1–64 `languages`".into()); + } + for l in &d.languages { + if l != "*" + && (l.is_empty() + || l.len() > 64 + || !l.chars().all(|c| c.is_ascii_alphanumeric() || "-_.+#".contains(c))) + { + return Err(format!("contributes.providers: invalid language id {l:?}")); + } + } + let label = format!( + "{} for {}", + d.kinds + .iter() + .map(|k| serde_json::to_value(k).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default()) + .collect::>() + .join(", "), + d.languages.join(", ") + ); + let (store, plugin) = (self.store.clone(), pkg.id().to_owned()); + Ok(Prepared::new(label, move || Ok(store.add(plugin, d)))) + } +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct SecretDecl { + name: String, + label: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + description: Option, +} + +/// `[[contributes.secrets]]` (a UI point: Settings › Plugins lists them). +pub(super) fn secret(_pkg: &Package, decl: toml::Value) -> Result { + let d: SecretDecl = decode(SECRETS_POINT, decl)?; + validate_item_id(&d.name, "secret name")?; + if d.label.trim().is_empty() || d.label.len() > 128 || d.description.as_ref().is_some_and(|x| x.len() > 1024) { + return Err(format!("secret {:?}: `label` 1–128 bytes, `description` up to 1 KiB", d.name)); + } + let json = serde_json::to_value(&d).map_err(|e| e.to_string())?; + Ok(UiDecl::new(d.name.clone(), d.label, json)) +} + +// ---- dispatch --------------------------------------------------------------- + +use super::{LoadedPlugin, PluginHost, PluginStatus}; +use ide_core::CancellationToken; +use ide_plugin::{ + ActorError, CallError, CodeAction, CompletionItem, InlineSuggestion, LineMarker, Location, Pending, + ProviderDocument, Runtime, +}; +use std::sync::Weak; +use std::time::{Duration, Instant}; + +/// How long a superseded inline completion may take to return after its +/// request was cancelled before it is interrupted. +const CANCEL_GRACE: Duration = Duration::from_millis(250); + +static EDITOR_PROVIDERS: RwLock>> = RwLock::new(None); + +/// Makes `host`'s plugin providers part of completion, code actions, go to +/// definition and inline completion (`None` removes them). +pub fn set_editor_providers(host: Option<&Arc>) { + *EDITOR_PROVIDERS.write() = host.map(Arc::downgrade); +} + +/// The plugin host whose providers take part, when any declares `kind`. +pub(crate) fn editor_providers(kind: ProviderKind) -> Option> { + let host = EDITOR_PROVIDERS.read().as_ref()?.upgrade()?; + host.providers.any(kind).then_some(host) +} + +impl PluginHost { + /// Usable plugins declaring `kind` for `language`. + fn provider_plugins(&self, kind: ProviderKind, language: &str) -> Vec> { + self.providers + .plugins_for(kind, language) + .into_iter() + .filter_map(|id| self.get(&id).ok()) + .filter(|p| { + let m = p.meta.lock(); + matches!(m.status, PluginStatus::Active | PluginStatus::Inactive) && m.pending.is_empty() + }) + .collect() + } + + /// Edit-path calls (soft / hard deadline) to every usable plugin that + /// declares `kind` for `language`, in plugin order, leaving out those that + /// failed or were late. Each plugin runs on its own thread, so the calls + /// run at the same time: the wait is the slowest plugin's, not the sum. + fn edit_calls( + &self, + kind: ProviderKind, + language: &str, + f: impl FnOnce(&mut Runtime, Duration) -> Result + Clone + Send + 'static, + ) -> Vec<(Arc, R)> { + let (soft, hard) = (self.limits.edit_soft, self.limits.edit_hard); + let queued: Vec<_> = self + .provider_plugins(kind, language) + .into_iter() + .filter_map(|plugin| { + let (actor, activated) = self.ensure_active(&plugin, None).ok()?; + if activated { + self.changed(); + } + let f = f.clone(); + let started = Instant::now(); + let call = actor.submit(Some(soft), move |rt| f(rt, hard)); + Some((plugin, actor, started, call)) + }) + .collect(); + queued + .into_iter() + .filter_map(|(plugin, actor, started, call)| { + let result = call.and_then(Pending::wait); + self.finish_provider_call(&plugin, &actor, started, result).map(|r| (plugin, r)) + }) + .collect() + } + + pub(super) fn finish_provider_call( + &self, + plugin: &Arc, + actor: &Arc, + started: Instant, + result: Result, + ) -> Option { + let elapsed = started.elapsed(); + match result { + Ok(r) => { + self.record_call(plugin, elapsed, true, true); + Some(r) + } + Err(ActorError::SoftTimeout) => { + plugin.meta.lock().stats.slow_calls += 1; + None + } + Err(ActorError::Cancelled) => None, + Err(ActorError::Call(CallError::Guest(e))) => { + self.record_call(plugin, elapsed, !e.is_failure(), true); + tracing::debug!(plugin = %plugin.id(), "provider: {e}"); + None + } + Err(ActorError::Call(CallError::Trap(_)) | ActorError::Stopped) => { + self.record_call(plugin, elapsed, false, false); + self.reap(plugin, actor, None); + None + } + } + } + + pub fn provide_completion( + &self, + doc: &ProviderDocument, + at: ide_core::Pos, + trigger: Option<&str>, + ) -> Vec<(String, CompletionItem)> { + let (d, t) = (Arc::new(doc.clone()), trigger.map(str::to_owned)); + self.edit_calls(ProviderKind::Completion, &doc.language, move |rt, timeout| { + rt.provide_completion(&d, at, t.as_deref(), timeout) + }) + .into_iter() + .flat_map(|(p, items)| items.into_iter().map(move |i| (p.id().to_owned(), i))) + .collect() + } + + pub fn provide_code_actions( + &self, + doc: &ProviderDocument, + selection: ide_core::Range, + ) -> Vec<(String, CodeAction)> { + let d = Arc::new(doc.clone()); + self.edit_calls(ProviderKind::CodeActions, &doc.language, move |rt, timeout| { + rt.provide_code_actions(&d, selection, timeout) + }) + .into_iter() + .flat_map(|(p, actions)| actions.into_iter().map(move |a| (p.id().to_owned(), a))) + .collect() + } + + pub fn provide_definition(&self, doc: &ProviderDocument, at: ide_core::Pos) -> Vec { + let d = Arc::new(doc.clone()); + self.edit_calls(ProviderKind::Definition, &doc.language, move |rt, timeout| { + rt.provide_definition(&d, at, timeout) + }) + .into_iter() + .flat_map(|(_, locations)| locations) + .collect() + } + + pub fn provide_line_markers(&self, doc: &ProviderDocument) -> Vec<(String, LineMarker)> { + let d = Arc::new(doc.clone()); + self.edit_calls(ProviderKind::LineMarkers, &doc.language, move |rt, timeout| { + rt.provide_line_markers(&d, timeout) + }) + .into_iter() + .flat_map(|(p, markers)| markers.into_iter().map(move |m| (p.id().to_owned(), m))) + .collect() + } + + /// Ghost text from the first plugin that has some. Not bound by the + /// edit-path soft deadline (it may need the network) but by `cancel`: + /// the editor cancels a request as soon as the user types on. + pub fn provide_inline_completion( + &self, + doc: &ProviderDocument, + at: ide_core::Pos, + cancel: &CancellationToken, + ) -> Option<(String, InlineSuggestion)> { + for p in self.provider_plugins(ProviderKind::InlineCompletion, &doc.language) { + if cancel.is_cancelled() { + return None; + } + let Ok((actor, activated)) = self.ensure_active(&p, None) else { continue }; + if activated { + self.changed(); + } + let (d, timeout) = (doc.clone(), self.limits.timeout); + let started = Instant::now(); + let result = + actor.call_cancellable(cancel, CANCEL_GRACE, move |rt| rt.provide_inline_completion(&d, at, timeout)); + if let Some(Some(s)) = self.finish_provider_call(&p, &actor, started, result) { + return Some((p.id().to_owned(), s)); + } + } + None + } +} diff --git a/crates/ide-host/src/plugins/remote.rs b/crates/ide-host/src/plugins/remote.rs new file mode 100644 index 00000000..e3666cf4 --- /dev/null +++ b/crates/ide-host/src/plugins/remote.rs @@ -0,0 +1,222 @@ +//! Plugin languages of a remote project: `Workspace` contributions take effect where the project is, so the +//! desktop pushes its plugins' language definitions to `openidea-server` +//! (`plugin_sync_languages`) together with the `process:` programs the user +//! granted. The server resolves each granted program on its own `PATH`, pins +//! the file (path + hash, kept in `plugin-pins.json`) the first time and +//! starts only that file afterwards; a program missing from a sync is revoked. +//! Revoking and granting again on the desktop re-pins a replaced program. + +use ide_extension::Capability; +use ide_extension::ledger::{self, BinaryGrant}; +use ide_language::plugin_point::{PluginLanguages, validate_definition}; +use ide_language::{LanguageConfig, ProgramPin}; +use parking_lot::Mutex; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::Arc; + +pub const PINS_FILE: &str = "plugin-pins.json"; +/// The server command the desktop calls. +pub const SYNC_COMMAND: &str = "plugin_sync_languages"; + +/// One plugin language as the desktop sends it. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RemoteLanguage { + pub plugin: String, + pub language: LanguageConfig, + /// Program names of the plugin's granted `process:` capabilities. + #[serde(default)] + pub granted: Vec, +} + +/// What the server made of a sync. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct SyncReport { + pub languages: usize, + /// `plugin: program` → the file it starts. + pub pinned: BTreeMap, + /// Granted programs not found on this machine's `PATH`. + pub unresolved: Vec, + /// Definitions that failed validation (not applied). + pub rejected: Vec, +} + +#[derive(Default, Serialize, Deserialize)] +struct PinsFile { + /// `plugin\nprocess:program` → the approved file. + #[serde(default)] + pins: BTreeMap, +} + +type PathVar = Arc Option + Send + Sync>; + +/// The server's side: an overlay for its language registry, filled by syncs. +pub struct RemotePluginLanguages { + store: Arc, + pins: Arc>>, + file: Option, + applied: Mutex>, + path_var: PathVar, +} + +fn key(plugin: &str, cap: &Capability) -> String { + format!("{plugin}\n{cap}") +} + +impl RemotePluginLanguages { + /// Pins persist in `data_dir` (none: in memory, for tests). + pub fn new(data_dir: Option<&std::path::Path>) -> Arc { + Self::with_path(data_dir, Arc::new(|| std::env::var_os("PATH"))) + } + + pub fn with_path(data_dir: Option<&std::path::Path>, path_var: PathVar) -> Arc { + let file = data_dir.map(|d| d.join(PINS_FILE)); + let saved: PinsFile = file + .as_ref() + .and_then(|f| std::fs::read_to_string(f).ok()) + .and_then(|s| serde_json::from_str(&s).ok()) + .unwrap_or_default(); + let pins = Arc::new(Mutex::new(saved.pins)); + let store = PluginLanguages::new(); + let policy_pins = pins.clone(); + store.set_process_policy(Arc::new(move |plugin, cap| { + policy_pins.lock().get(&key(plugin, cap)).map(|b| ProgramPin { path: b.path.clone(), hash: b.hash.clone() }) + })); + Arc::new(Self { store, pins, file, applied: Mutex::default(), path_var }) + } + + /// For [`ide_language::LanguageRegistry::attach_plugins`]. + pub fn store(&self) -> &Arc { + &self.store + } + + /// Replaces every plugin language with `languages`. + pub fn sync(&self, languages: Vec) -> SyncReport { + let mut report = SyncReport::default(); + let mut wanted: BTreeMap = BTreeMap::new(); + let mut accepted = Vec::new(); + for l in languages { + if let Err(e) = validate_definition(&l.language) { + report.rejected.push(format!("{} ({}): {e}", l.language.id, l.plugin)); + continue; + } + for program in &l.granted { + let cap = Capability::Process(program.clone()); + // Only programs the definition starts: a grant is not a licence for anything else. + if ide_language::plugin_point::required_capabilities(&l.language).contains(&cap) { + wanted.insert(key(&l.plugin, &cap), (program.clone(), cap)); + } + } + accepted.push(l); + } + { + let mut pins = self.pins.lock(); + pins.retain(|k, _| wanted.contains_key(k)); + for (k, (program, _)) in &wanted { + if pins.contains_key(k) { + continue; + } + let resolved = ledger::resolve_program(program, (self.path_var)().as_deref()).and_then(|path| { + ledger::file_hash(&path).map(|hash| BinaryGrant { path, hash }).map_err(|e| e.to_string()) + }); + match resolved { + Ok(bin) => { + pins.insert(k.clone(), bin); + } + Err(e) => { + tracing::info!("process:{program}: {e}"); + report.unresolved.push(program.clone()); + } + } + } + for (k, bin) in pins.iter() { + report.pinned.insert(k.replace("\nprocess:", ": "), bin.path.clone()); + } + self.save(&pins); + } + let mut applied = self.applied.lock(); + applied.clear(); // disposes the previous sync's languages + for l in accepted { + applied.push(self.store.add(l.plugin, l.language)); + } + report.languages = applied.len(); + self.store.invalidate(); + report + } + + fn save(&self, pins: &BTreeMap) { + let Some(file) = &self.file else { return }; + let json = serde_json::to_string_pretty(&PinsFile { pins: pins.clone() }).unwrap_or_default(); + let tmp = file.with_extension("json.tmp"); + if let Err(e) = std::fs::write(&tmp, json).and_then(|()| std::fs::rename(&tmp, file)) { + tracing::warn!("saving {}: {e}", file.display()); + } + } +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use ide_core::LanguageId; + use ide_language::LanguageRegistry; + use std::os::unix::fs::PermissionsExt; + + fn toy(granted: &[&str]) -> RemoteLanguage { + let language = ide_language::plugin_point::parse_definition( + "id = \"toy\"\nname = \"Toy\"\nextensions = [\"toy\"]\n\ + [[language-servers]]\nname = \"toylsp\"\ncommand = \"toylsp\"\n", + ) + .unwrap(); + RemoteLanguage { + plugin: "acme.toy".into(), + language, + granted: granted.iter().map(|s| (*s).to_owned()).collect(), + } + } + + #[test] + fn syncs_languages_and_pins_granted_programs_on_this_machine() { + let tmp = tempfile::tempdir().unwrap(); + let bin = tmp.path().join("bin"); + std::fs::create_dir(&bin).unwrap(); + std::fs::write(bin.join("toylsp"), "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(bin.join("toylsp"), std::fs::Permissions::from_mode(0o755)).unwrap(); + let path = bin.clone().into_os_string(); + let remote = RemotePluginLanguages::with_path(Some(tmp.path()), Arc::new(move || Some(path.clone()))); + let registry = LanguageRegistry::load(None).unwrap(); + registry.attach_plugins(remote.store().clone()); + let project = registry.fork(); + let id = LanguageId::new("toy"); + + // Not granted: the language, no server. + let report = remote.sync(vec![toy(&[])]); + assert_eq!(report.languages, 1); + assert_eq!(project.detect(std::path::Path::new("/r/a.toy"), None), id); + assert!(project.get(&id).unwrap().language_servers.is_empty()); + + // Granted: resolved here and pinned; persisted. + let report = remote.sync(vec![toy(&["toylsp", "rm"])]); + assert_eq!(report.pinned.len(), 1, "only programs the definition starts: {report:?}"); + let pin = project.get(&id).unwrap().language_servers[0].pinned.clone().unwrap(); + assert!(pin.verify().is_ok()); + assert!(tmp.path().join(PINS_FILE).is_file()); + + // Replaced: refused at start until revoked and granted again. + std::fs::write(bin.join("toylsp"), "#!/bin/sh\necho x\n").unwrap(); + remote.sync(vec![toy(&["toylsp"])]); + assert!(project.get(&id).unwrap().language_servers[0].pinned.as_ref().unwrap().verify().is_err()); + remote.sync(vec![toy(&[])]); + remote.sync(vec![toy(&["toylsp"])]); + assert!(project.get(&id).unwrap().language_servers[0].pinned.as_ref().unwrap().verify().is_ok()); + + // Missing programs are reported; invalid definitions rejected; empty sync removes all. + let mut bad = toy(&[]); + bad.language.id = LanguageId::new("a b"); + let report = remote.sync(vec![bad]); + assert_eq!(report.rejected.len(), 1); + assert_eq!(project.detect(std::path::Path::new("/r/a.toy"), None), LanguageId::plain_text()); + } +} diff --git a/crates/ide-host/src/plugins/remote_host.rs b/crates/ide-host/src/plugins/remote_host.rs new file mode 100644 index 00000000..71be9116 --- /dev/null +++ b/crates/ide-host/src/plugins/remote_host.rs @@ -0,0 +1,504 @@ +//! Code plugins of remote projects: +//! Wasm runs where the project is, so `openidea-server` hosts the desktop's +//! code plugins and they read, search, run processes and publish diagnostics +//! on the remote machine. +//! +//! The desktop stays the authority over what is installed and granted. It +//! pushes its live code plugins with [`SYNC_PACKAGES`]: first their digests +//! and grants, then the files of those the server doesn't have (one package +//! per request); a package missing from a sync is uninstalled. The server +//! installs them under `/remote-plugins` and records the desktop's +//! grants (a `process:` grant is pinned to the program on this machine's +//! `PATH`). +//! +//! The commands a window needs at run time (`plugin_run_command`, +//! `plugin_post_events`, `plugin_event_kinds`, `plugin_status_items`, +//! `plugin_cancel_task`, `plugin_set_active_file`, `plugin_line_markers`, +//! `plugin_view_render`, `plugin_view_event`) +//! carry the desktop commands' names and arguments, so a remote window's UI +//! routes them here unchanged. Plugin results come back as `plugin` +//! notifications ([`PluginEventMessage`]); secrets stay in the desktop's +//! keychain and are asked for with a `plugin_secret` request +//! ([`SecretRequest`]) when a request header needs one (rule 4). + +use super::{ + Consent, HostWorkspace, PluginEditor, PluginEvent, PluginHost, PluginSource, PluginStatusItem, SecretStore, +}; +use crate::rpc::Dispatcher; +use base64::Engine as _; +use ide_core::{IdeError, IdeResult}; +use ide_extension::{MANIFEST_FILE, ledger}; +use ide_jsonrpc::Peer; +use ide_plugin::{Invocation, Limits}; +use parking_lot::Mutex; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Component, Path, PathBuf}; +use std::sync::{Arc, OnceLock, Weak}; +use std::time::Duration; + +/// The server command the desktop calls with its packages. +pub const SYNC_PACKAGES: &str = "plugin_sync_packages"; +/// Server → client notification carrying a [`PluginEventMessage`]. +pub const EVENT_NOTIFICATION: &str = "plugin"; +/// Server → client request ([`SecretRequest`] → `Option`). +pub const SECRET_REQUEST: &str = "plugin_secret"; +/// Under the server's data directory. +pub const PLUGINS_DIR: &str = "remote-plugins"; +const INCOMING_DIR: &str = "remote-plugins.incoming"; +const SECRET_TIMEOUT: Duration = Duration::from_secs(10); +const EVENT_FLUSH: Duration = Duration::from_millis(250); +const TICKS_PER_SUPERVISION: u32 = 20; + +/// One live code plugin of the desktop. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RemotePackage { + pub id: String, + /// [`package_digest`] of the package. + pub digest: String, + /// Capabilities the user granted on the desktop. + pub granted: Vec, +} + +/// One file of a package (`path` relative to the package, `data` base64). +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct PackageFile { + pub path: String, + pub data: String, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PackageSyncReport { + /// Packages the server needs the files of (send them in another sync). + pub missing: Vec, + pub installed: Vec, + pub removed: Vec, + /// `id: reason`. + pub failed: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct PluginEventMessage { + /// The window that invoked the plugin (`None`: every window of the connection). + pub window: Option, + pub event: PluginEvent, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct SecretRequest { + pub plugin: String, + pub name: String, +} + +/// Identifies a package's content: the manifest, the files its declarations +/// reference and the component. +pub fn package_digest(dir: &Path, files: &[PathBuf]) -> IdeResult { + let mut all = files.to_vec(); + all.push(PathBuf::from(MANIFEST_FILE)); + Ok(ledger::package_hash(dir, &all)?) +} + +/// Whether a plugin event means something to a remote window (the desktop +/// owns the plugin list, themes and consent). +pub fn forwarded(event: &PluginEvent) -> bool { + matches!( + event, + PluginEvent::Notification { .. } + | PluginEvent::StatusItemChanged { .. } + | PluginEvent::TaskStarted { .. } + | PluginEvent::TaskProgress { .. } + | PluginEvent::TaskEnded { .. } + | PluginEvent::SubscriptionsChanged + | PluginEvent::ViewChanged { .. } + | PluginEvent::ViewMessage { .. } + | PluginEvent::OpenTerminal { .. } + ) +} + +// ---- desktop side ----------------------------------------------------------- + +impl PluginHost { + fn package_files(&self, plugin: &super::LoadedPlugin) -> IdeResult> { + let set = self.registry.prepare(&plugin.pkg).map_err(IdeError::invalid)?; + Ok(set.files.into_iter().chain(plugin.manifest().wasm.clone()).collect()) + } + + /// The live code plugins (installed or linked) for a remote project's server. + pub fn remote_packages(&self) -> Vec { + let plugins: Vec<_> = self.plugins.read().values().cloned().collect(); + plugins + .iter() + .filter(|p| p.dev_root.is_none() && !p.invalid && p.manifest().wasm.is_some()) + .filter(|p| matches!(p.status(), super::PluginStatus::Active | super::PluginStatus::Inactive)) + .filter_map(|p| { + let files = self.package_files(p).ok()?; + let digest = package_digest(p.dir(), &files).ok()?; + let granted = p.meta.lock().granted.iter().map(ToString::to_string).collect(); + Some(RemotePackage { id: p.id().to_owned(), digest, granted }) + }) + .collect() + } + + /// The files of a package for [`SYNC_PACKAGES`], the manifest first. + pub fn remote_package_files(&self, id: &str) -> IdeResult> { + let plugin = self.get(id)?; + let files = self.package_files(&plugin)?; + std::iter::once(PathBuf::from(MANIFEST_FILE)) + .chain(files) + .map(|rel| { + let bytes = std::fs::read(plugin.dir().join(&rel))?; + let path = rel.to_str().ok_or_else(|| IdeError::invalid("non UTF-8 file name"))?.replace('\\', "/"); + Ok(PackageFile { path, data: base64::engine::general_purpose::STANDARD.encode(bytes) }) + }) + .collect() + } + + /// A secret a plugin declares, for its remote instance (`plugin_secret`). + pub fn declared_secret(&self, id: &str, name: &str) -> Option { + let plugin = self.get(id).ok()?; + if !self.ui.items(super::providers::SECRETS_POINT, Some(plugin.id())).iter().any(|s| s.key == name) { + return None; + } + let store = self.shared.secrets.read().clone(); + store.get(plugin.id(), name) + } +} + +// ---- server side ------------------------------------------------------------ + +/// The plugin host of `openidea-server`. +pub struct RemotePlugins { + host: Arc, + incoming: PathBuf, + sync: Mutex<()>, +} + +/// Secrets from the desktop's keychain, asked for when used. +struct ClientSecrets { + peer: Arc>, + runtime: tokio::runtime::Handle, +} + +impl SecretStore for ClientSecrets { + fn get(&self, plugin: &str, name: &str) -> Option { + let peer = self.peer.get()?.clone(); + let request = SecretRequest { plugin: plugin.to_owned(), name: name.to_owned() }; + let ask = async move { + tokio::time::timeout(SECRET_TIMEOUT, peer.request::<_, Option>(SECRET_REQUEST, request, None)).await + }; + // Plugin threads block on the runtime; a runtime worker (a host + // command asking) must leave its thread to the other tasks first. + let answer = if tokio::runtime::Handle::try_current().is_ok() { + tokio::task::block_in_place(|| self.runtime.block_on(ask)) + } else { + self.runtime.block_on(ask) + }; + match answer { + Ok(Ok(value)) => value, + Ok(Err(e)) => { + tracing::warn!("plugin secret {plugin}/{name}: {e}"); + None + } + Err(_) => None, + } + } + + fn set(&self, _: &str, _: &str, _: Option<&str>) -> Result<(), String> { + Err("secrets are stored on the desktop".into()) + } +} + +impl RemotePlugins { + /// Creates the host over `/remote-plugins`, loads what earlier + /// sessions installed and starts event delivery and supervision. + pub fn start(data_dir: &Path, projects: &Arc, peer: Arc>) -> IdeResult> { + let sink_peer = peer.clone(); + let sink = move |client: Option<&str>, event: PluginEvent| { + if forwarded(&event) + && let Some(p) = sink_peer.get() + { + let _ = p.notify(EVENT_NOTIFICATION, PluginEventMessage { window: client.map(str::to_owned), event }); + } + }; + let host = Arc::new(PluginHost::new(data_dir.join(PLUGINS_DIR), Arc::new(sink), Limits::default())?); + host.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(projects))))); + host.set_secret_store(Arc::new(ClientSecrets { peer, runtime: projects.runtime.clone() })); + let trust = Arc::downgrade(projects); + host.set_project_policy(Arc::new(move |root| { + trust.upgrade().is_some_and(|h| h.trust.trusted(root).unwrap_or(false)) + })); + super::set_editor_providers(Some(&host)); + ide_language::set_external_syntax(Some(host.syntax_provider())); + ide_run::set_external_detection(Some(host.run_detection())); + host.load_all(); + host.startup_finished(); + spawn_supervision(Arc::downgrade(&host))?; + Ok(Arc::new(Self { host, incoming: data_dir.join(INCOMING_DIR), sync: Mutex::new(()) })) + } + + pub fn host(&self) -> &Arc { + &self.host + } + + /// Makes the installed packages match `packages`: uninstalls the others, + /// follows changed grants, installs those with `files` and reports the + /// rest as missing. + pub fn sync( + &self, + packages: Vec, + mut files: BTreeMap>, + ) -> PackageSyncReport { + let _guard = self.sync.lock(); + let mut report = PackageSyncReport::default(); + let wanted: BTreeSet<&str> = packages.iter().map(|p| p.id.as_str()).collect(); + let installed: Vec = self + .host + .plugins + .read() + .values() + .filter(|p| p.source == PluginSource::Installed) + .map(|p| p.id().to_owned()) + .collect(); + for id in installed.iter().filter(|id| !wanted.contains(id.as_str())) { + match self.host.uninstall(id) { + Ok(()) => report.removed.push(id.clone()), + Err(e) => report.failed.push(format!("{id}: {e}")), + } + } + for pkg in packages { + if !valid_id(&pkg.id) { + report.failed.push(format!("{}: invalid plugin id", pkg.id)); + continue; + } + let consent = Consent { optional: pkg.granted.clone() }; + if self.current_digest(&pkg.id).as_deref() == Some(pkg.digest.as_str()) { + if let Err(e) = self.follow_grants(&pkg, &consent) { + report.failed.push(format!("{}: {e}", pkg.id)); + } + continue; + } + match files.remove(&pkg.id) { + None => report.missing.push(pkg.id), + Some(list) => match self.install(&pkg, list, &consent) { + Ok(()) => report.installed.push(pkg.id), + Err(e) => report.failed.push(format!("{}: {}", pkg.id, e.message)), + }, + } + } + report + } + + fn current_digest(&self, id: &str) -> Option { + let plugin = self.host.plugins.read().get(id).cloned()?; + if plugin.source != PluginSource::Installed || plugin.invalid { + return None; + } + let files = self.host.package_files(&plugin).ok()?; + package_digest(plugin.dir(), &files).ok() + } + + fn follow_grants(&self, pkg: &RemotePackage, consent: &Consent) -> IdeResult<()> { + let info = self.host.info_of(&pkg.id)?; + let have: BTreeSet<&str> = info.capabilities.iter().filter(|c| c.granted).map(|c| c.id.as_str()).collect(); + let want: BTreeSet<&str> = pkg.granted.iter().map(String::as_str).collect(); + if have != want || info.status == super::PluginStatus::NeedsConsent { + self.host.grant(&pkg.id, consent)?; + } + Ok(()) + } + + fn install(&self, pkg: &RemotePackage, files: Vec, consent: &Consent) -> IdeResult<()> { + let dir = self.incoming.join(&pkg.id); + let _ = std::fs::remove_dir_all(&dir); + let result = (|| { + let mut rels = Vec::new(); + for f in files { + let rel = safe_relative(&f.path)?; + let bytes = base64::engine::general_purpose::STANDARD + .decode(f.data.as_bytes()) + .map_err(|e| IdeError::invalid(format!("{}: {e}", f.path)))?; + let to = dir.join(&rel); + if let Some(parent) = to.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(&to, bytes)?; + if rel != Path::new(MANIFEST_FILE) { + rels.push(rel); + } + } + if package_digest(&dir, &rels)? != pkg.digest { + return Err(IdeError::invalid("the package arrived incomplete or changed")); + } + let info = self.host.install_from_dir(&dir, consent)?; + if info.id != pkg.id { + let _ = self.host.uninstall(&info.id); + return Err(IdeError::invalid(format!("the package is plugin {:?}", info.id))); + } + Ok(()) + })(); + let _ = std::fs::remove_dir_all(&dir); + result + } + + /// The run-time commands of remote windows plus [`SYNC_PACKAGES`]. + pub fn register(self: &Arc, d: &mut Dispatcher) { + let this = self.clone(); + d.add(SYNC_PACKAGES, move |c| { + let this = this.clone(); + async move { + let packages: Vec = c.arg("packages")?; + let files: Option>> = c.arg("files")?; + blocking(move || Ok(this.sync(packages, files.unwrap_or_default()))).await + } + }); + let host = Arc::downgrade(&self.host); + let h = host.clone(); + d.add("plugin_run_command", move |c| { + let h = h.clone(); + async move { + let host = alive(&h)?; + let plugin_id: String = c.arg("pluginId")?; + let command_id: String = c.arg("commandId")?; + let arg: Option = c.arg("arg")?; + let editor: Option = c.arg("editor")?; + let invocation = Invocation { + client: Some(c.window.clone()), + workspace_root: c.host.project(&c.window).ok().map(|p| p.root.clone()), + editor: editor.map(PluginEditor::context), + }; + blocking(move || host.run_command(&plugin_id, &command_id, arg.as_deref(), invocation)).await + } + }); + let h = host.clone(); + d.add("plugin_post_events", move |c| { + let h = h.clone(); + async move { + alive(&h)?.post_events(Some(&c.window), c.arg("events")?); + Ok(()) + } + }); + let h = host.clone(); + d.add("plugin_event_kinds", move |_| { + let h = h.clone(); + async move { Ok(alive(&h)?.event_kinds().into_iter().collect::>()) } + }); + let h = host.clone(); + d.add("plugin_status_items", move |_| { + let h = h.clone(); + async move { + Ok(alive(&h)? + .status_items() + .into_iter() + .map(|(plugin_id, id, item)| PluginStatusItem { plugin_id, id, item }) + .collect::>()) + } + }); + let h = host.clone(); + d.add("plugin_cancel_task", move |c| { + let h = h.clone(); + async move { Ok(alive(&h)?.cancel_task(&c.arg::("taskId")?)) } + }); + let h = host.clone(); + d.add("plugin_set_active_file", move |c| { + let h = h.clone(); + async move { + alive(&h)?.set_active_file(&c.window, c.arg("path")?); + Ok(()) + } + }); + let h = host.clone(); + d.add("plugin_view_render", move |c| { + let h = h.clone(); + async move { + let plugins = alive(&h)?; + super::views::render( + &c.host, + plugins, + &c.window, + c.arg("pluginId")?, + c.arg("view")?, + c.arg("viewport")?, + c.arg("doc")?, + c.arg("editor")?, + ) + .await + } + }); + let h = host.clone(); + d.add("plugin_view_event", move |c| { + let h = h.clone(); + async move { + let plugins = alive(&h)?; + super::views::event( + &c.host, + plugins, + &c.window, + c.arg("pluginId")?, + c.arg("view")?, + c.arg("event")?, + c.arg("doc")?, + c.arg("editor")?, + ) + .await + } + }); + d.add("plugin_line_markers", |c| async move { + crate::ops::lsp::plugin_line_markers(&c.host, &c.window, c.arg("doc")?).await + }); + } +} + +fn alive(host: &Weak) -> IdeResult> { + host.upgrade().ok_or_else(|| IdeError::unavailable("the plugin host has shut down")) +} + +async fn blocking(f: impl FnOnce() -> IdeResult + Send + 'static) -> IdeResult { + tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))? +} + +fn spawn_supervision(host: Weak) -> IdeResult<()> { + std::thread::Builder::new().name("remote-plugins".into()).spawn(move || { + for n in 1u32.. { + std::thread::sleep(EVENT_FLUSH); + let Some(host) = host.upgrade() else { return }; + host.flush_events(); + if n % TICKS_PER_SUPERVISION == 0 { + host.tick(); + } + } + })?; + Ok(()) +} + +fn valid_id(id: &str) -> bool { + !id.is_empty() + && id.len() <= 128 + && !id.starts_with('.') + && id.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c)) +} + +/// `path` as a relative path inside a package (no `..`, no root). +fn safe_relative(path: &str) -> IdeResult { + let p = Path::new(path); + if path.is_empty() || !p.components().all(|c| matches!(c, Component::Normal(_))) { + return Err(IdeError::invalid(format!("invalid file path {path:?} in package"))); + } + Ok(p.to_path_buf()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn package_paths_stay_inside_the_package() { + assert!(safe_relative("dist/plugin.wasm").is_ok()); + for bad in ["", "../x", "/etc/passwd", "a/../../b", "./x"] { + assert!(safe_relative(bad).is_err(), "{bad}"); + } + assert!(valid_id("ai-completion")); + assert!(!valid_id("../x") && !valid_id(".data") && !valid_id("")); + } +} diff --git a/crates/ide-host/src/plugins/run_detectors.rs b/crates/ide-host/src/plugins/run_detectors.rs new file mode 100644 index 00000000..c48b001e --- /dev/null +++ b/crates/ide-host/src/plugins/run_detectors.rs @@ -0,0 +1,167 @@ +//! The `runDetectors` extension point: run configurations a plugin offers in +//! projects that contain a marker file. +//! +//! ```toml +//! [[contributes.runDetectors]] +//! id = "forge-test" +//! name = "forge test" +//! files = ["foundry.toml"] # any of these at the project root +//! command = "forge" +//! args = ["test"] +//! test = true # results go to the test tree +//! ``` +//! +//! The command is a `process:` capability like a language server's: the +//! configuration is offered only while it is granted, and starts the approved +//! file (checked right before it starts). + +use ide_extension::{ + Capability, Disposable, ExtensionPoint, Package, Placement, Prepared, check_relative, decode, validate_item_id, +}; +use ide_language::ProgramPin; +use ide_run::{EXTERNAL_PREFIX, ExternalDetection, RunConfig}; +use parking_lot::RwLock; +use serde::Deserialize; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +pub const POINT_ID: &str = "runDetectors"; +const MAX_FILES: usize = 16; +const MAX_ARGS: usize = 64; + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Detector { + pub id: String, + pub name: String, + pub files: Vec, + pub command: String, + #[serde(default)] + pub args: Vec, + #[serde(default)] + pub test: bool, +} + +/// Detectors of enabled plugins. +#[derive(Default)] +pub struct RunDetectors { + items: RwLock>, + seq: AtomicU64, +} + +impl RunDetectors { + fn add(self: &Arc, plugin: String, detector: Detector) -> Disposable { + let seq = self.seq.fetch_add(1, Ordering::Relaxed); + self.items.write().push((seq, plugin, detector)); + let weak = Arc::downgrade(self); + Disposable::new(move || { + if let Some(this) = weak.upgrade() { + this.items.write().retain(|(s, _, _)| *s != seq); + } + }) + } +} + +pub struct RunDetectorsPoint { + store: Arc, +} + +impl RunDetectorsPoint { + pub fn new(store: Arc) -> Self { + Self { store } + } +} + +impl ExtensionPoint for RunDetectorsPoint { + fn id(&self) -> &'static str { + POINT_ID + } + + fn placement(&self) -> Placement { + Placement::Workspace + } + + fn prepare(&self, pkg: &Package, decl: toml::Value) -> Result { + let d: Detector = decode(POINT_ID, decl)?; + validate_item_id(&d.id, "run detector id")?; + if d.name.trim().is_empty() || d.name.len() > 128 { + return Err(format!("run detector {:?}: `name` must be 1–128 bytes", d.id)); + } + if d.files.is_empty() || d.files.len() > MAX_FILES { + return Err(format!("run detector {:?}: give 1–{MAX_FILES} marker `files`", d.id)); + } + for f in &d.files { + check_relative(f, "files")?; + } + let program = d.command.trim(); + if program.is_empty() || program.contains(char::is_whitespace) { + return Err(format!("run detector {:?}: `command` is one program name (arguments go in `args`)", d.id)); + } + if d.args.len() > MAX_ARGS { + return Err(format!("run detector {:?}: at most {MAX_ARGS} arguments", d.id)); + } + let cap = Capability::Process(program.to_owned()); + let (store, plugin, label) = (self.store.clone(), pkg.id().to_owned(), d.name.clone()); + let key = d.id.clone(); + Ok(Prepared::new(label, move || Ok(store.add(plugin, d))).key(key).capability(cap)) + } +} + +type Pins = Arc>>; + +/// [`ExternalDetection`] over the detectors and the approved programs. +pub struct PluginRunDetection { + pub(crate) store: Arc, + pub(crate) pins: Pins, +} + +fn config_id(plugin: &str, detector: &str) -> String { + format!("{EXTERNAL_PREFIX}{plugin}:{detector}") +} + +impl PluginRunDetection { + fn pin(&self, plugin: &str, d: &Detector) -> Option { + let cap = Capability::Process(d.command.trim().to_owned()); + self.pins.read().get(&(plugin.to_owned(), cap.to_string())).cloned() + } +} + +impl ExternalDetection for PluginRunDetection { + fn detect(&self, root: &Path) -> Vec { + let items = self.store.items.read().clone(); + items + .into_iter() + .filter(|(_, plugin, d)| self.pin(plugin, d).is_some() && d.files.iter().any(|f| root.join(f).exists())) + .map(|(_, plugin, d)| RunConfig { + id: config_id(&plugin, &d.id), + name: d.name.clone(), + kind: "plugin".into(), + command: d.command.trim().to_owned(), + args: d.args.clone(), + cwd: None, + env: Default::default(), + detected: true, + is_test: d.test, + debug_adapter: None, + allow_parallel: false, + extras: Default::default(), + }) + .collect() + } + + fn launch(&self, config: &RunConfig) -> Result { + let items = self.store.items.read(); + let (plugin, d) = items + .iter() + .find(|(_, plugin, d)| config_id(plugin, &d.id) == config.id) + .map(|(_, p, d)| (p.clone(), d.clone())) + .ok_or_else(|| "the plugin that detected this configuration is no longer enabled".to_owned())?; + drop(items); + let pin = self.pin(&plugin, &d).ok_or_else(|| { + format!("allow process:{} for plugin {plugin} in Settings › Plugins to run this configuration", d.command) + })?; + pin.verify().map(Path::to_path_buf) + } +} diff --git a/crates/ide-plugin/src/theme.rs b/crates/ide-host/src/plugins/theme.rs similarity index 76% rename from crates/ide-plugin/src/theme.rs rename to crates/ide-host/src/plugins/theme.rs index 0d4e65e7..e4f38ff5 100644 --- a/crates/ide-plugin/src/theme.rs +++ b/crates/ide-host/src/plugins/theme.rs @@ -1,9 +1,21 @@ -//! Theme contributions: design-token overrides applied as CSS variables on `:root`. -//! Theme and editor-scheme files are JSON that may contain `//` and `/* */` comments. +//! The `themes` extension point: design-token overrides applied as CSS +//! variables on `:root`. Theme and editor-scheme files are JSON that may +//! contain `//` and `/* */` comments. +//! +//! ```toml +//! [[contributes.themes]] +//! path = "themes/harbor-night.json" +//! editor-scheme = "themes/harbor-night.scheme.json" # optional +//! ``` +use ide_extension::{ExtensionPoint, Package, Placement, Prepared, UiContribution, UiStore, decode}; use serde::{Deserialize, Serialize}; use specta::Type; use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::Arc; + +pub const POINT_ID: &str = "themes"; const MAX_TOKENS: usize = 512; const MAX_VALUE_LEN: usize = 256; @@ -48,7 +60,7 @@ impl ThemeDef { } pub fn validate(&self) -> Result<(), String> { - crate::manifest::validate_command_id(&self.id).map_err(|e| e.replace("command id", "theme id"))?; + ide_extension::validate_item_id(&self.id, "theme id")?; if self.name.trim().is_empty() { return Err("theme name must not be empty".into()); } @@ -71,6 +83,55 @@ impl ThemeDef { } } +pub struct ThemesPoint { + store: Arc, +} + +impl ThemesPoint { + pub fn new(store: Arc) -> Self { + Self { store } + } +} + +#[derive(Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +struct Decl { + path: PathBuf, + #[serde(default)] + editor_scheme: Option, +} + +impl ExtensionPoint for ThemesPoint { + fn id(&self) -> &'static str { + POINT_ID + } + + fn placement(&self) -> Placement { + Placement::Ui + } + + fn prepare(&self, pkg: &Package, decl: toml::Value) -> Result { + let decl: Decl = decode(POINT_ID, decl)?; + let path = &decl.path; + let mut theme = ThemeDef::parse(&pkg.read_text(path)?).map_err(|e| format!("{}: {e}", path.display()))?; + let mut files = vec![path.clone()]; + if let Some(scheme) = &decl.editor_scheme { + files.push(scheme.clone()); + theme.merge_editor_scheme(&pkg.read_text(scheme)?).map_err(|e| format!("{}: {e}", scheme.display()))?; + } + let item = UiContribution { + plugin_id: pkg.id().to_owned(), + point: POINT_ID.into(), + key: theme.id.clone(), + decl: serde_json::to_value(&theme).map_err(|e| e.to_string())?, + }; + let store = self.store.clone(); + let mut prepared = Prepared::new(theme.name.clone(), move || Ok(store.insert(item))).key(theme.id); + prepared.files = files; + Ok(prepared) + } +} + /// Blanks out `//` and `/* */` comments outside strings, keeping newlines so /// parse errors still point at the right line. fn strip_json_comments(src: &str) -> String { diff --git a/crates/ide-host/src/plugins/types.rs b/crates/ide-host/src/plugins/types.rs new file mode 100644 index 00000000..c9cac430 --- /dev/null +++ b/crates/ide-host/src/plugins/types.rs @@ -0,0 +1,236 @@ +//! UI-facing plugin types and the event stream. + +use super::theme::ThemeDef; +use ide_extension::{CapabilityInfo, ContributionInfo, UiContribution}; +pub use ide_plugin::{ActionPerformed, ActionSource, EventKind, NotificationLevel, StatusItem, WorkbenchEvent}; +use serde::{Deserialize, Serialize}; +use specta::Type; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum PluginSource { + /// Installed under `/plugins//`. + Installed, + /// Loaded from `/.openidea/plugins//` while that project is open. + Dev, + /// A development plugin linked from any folder (`openidea-plugin link`). + Linked, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum PluginStatus { + /// Code instantiated and activated. + Active, + /// Has code that has not been needed yet: contributions are live, no Wasm instance. + Inactive, + /// No code; contributions only. + Static, + Disabled, + /// Waiting for the user to confirm its permissions (project and new plugins). + NeedsConsent, + /// Failed to load, or failed repeatedly and was stopped for this session (see `error`). + Failed, +} + +impl PluginStatus { + /// Contributions are in effect. + pub fn is_live(self) -> bool { + matches!(self, Self::Active | Self::Inactive | Self::Static) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PluginInfo { + pub id: String, + pub name: String, + pub version: String, + pub description: String, + pub authors: Vec, + pub homepage: Option, + pub change_notes: Option, + pub source: PluginSource, + /// Package directory. + pub path: ide_core::IpcPath, + pub enabled: bool, + pub status: PluginStatus, + pub error: Option, + pub has_code: bool, + /// Declared capabilities with risk and grant state. + pub capabilities: Vec, + /// What it contributes while live (point + label). + pub contributions: Vec, + /// `activation` events of the manifest. + pub activation: Vec, + /// Non-fatal problems (unsupported contribution points). + pub warnings: Vec, + /// Statistics of this session. + pub stats: PluginStats, + /// The marketplace publisher whose signature the package carries (none: unsigned or untrusted). + pub publisher: Option, + /// The version an update replaced, to roll back to. + pub previous_version: Option, +} + +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PluginStats { + pub activations: u32, + /// Last activation (instantiate + `activate`), ms. + pub activation_ms: f64, + pub calls: u32, + pub errors: u32, + /// Slowest call, ms. + pub max_call_ms: f64, + /// 95th percentile of the recent calls, ms. + pub p95_call_ms: f64, + /// Edit-path calls whose result came too late and was dropped. + pub slow_calls: u32, + /// Traps (panics, budgets, permission violations); each drops the instance. + pub crashes: u32, + /// Instances reclaimed after being idle. + pub reclaims: u32, +} + +/// Number of declarations of one extension point. +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ContributionCount { + pub point: String, + pub count: u32, +} + +/// A plugin package available for installation from a local catalog +/// directory (the samples shipped with the IDE). Not installed by listing it. +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct CatalogPlugin { + pub id: String, + pub name: String, + pub version: String, + pub description: String, + pub authors: Vec, + pub homepage: Option, + pub change_notes: Option, + /// Package directory; install with `install_from_dir(path)`. + pub path: ide_core::IpcPath, + pub has_code: bool, + pub capabilities: Vec, + pub contributions: Vec, + /// Why the package cannot be installed as is (e.g. its WASM is not built). + pub problem: Option, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ActiveTheme { + pub plugin_id: String, + pub theme: ThemeDef, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PluginsSnapshot { + pub plugins: Vec, + pub active_theme: Option, + /// UI contributions of live plugins, projected by the client. + pub ui: Vec, +} + +/// Backend → UI notifications (Tauri event `ide://plugin`). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(tag = "type", rename_all = "camelCase")] +pub enum PluginEvent { + /// Plugins, their status or their contributions changed: re-fetch `plugin_list`. + CommandsChanged, + #[serde(rename_all = "camelCase")] + Notification { plugin_id: String, level: NotificationLevel, title: String, body: String }, + /// A plugin's status bar item was set (`item`) or removed. + #[serde(rename_all = "camelCase")] + StatusItemChanged { plugin_id: String, id: String, item: Option }, + /// A plugin began a task: show it with the background tasks. + #[serde(rename_all = "camelCase")] + TaskStarted { plugin_id: String, task_id: String, title: String, cancellable: bool }, + #[serde(rename_all = "camelCase")] + TaskProgress { plugin_id: String, task_id: String, done: u32, total: Option, message: Option }, + #[serde(rename_all = "camelCase")] + TaskEnded { plugin_id: String, task_id: String }, + /// The kinds of workbench events plugins want changed: re-fetch + /// `plugin_event_kinds` (the UI reports only those). + SubscriptionsChanged, + #[serde(rename_all = "camelCase")] + ThemeChanged { theme: Option }, + /// A plugin needs capabilities the user has not granted yet (first use + /// after migrating from 0.1): show its consent dialog. + #[serde(rename_all = "camelCase")] + ConsentRequested { plugin_id: String, capabilities: Vec }, + /// A view (or the custom editors) of a plugin must be rendered again. + #[serde(rename_all = "camelCase")] + ViewChanged { plugin_id: String, view: String }, + /// For the script of a view's `html` body. + #[serde(rename_all = "camelCase")] + ViewMessage { plugin_id: String, view: String, message: String }, + /// Open a terminal running `program` (already approved and verified). + #[serde(rename_all = "camelCase")] + OpenTerminal { + plugin_id: String, + title: String, + program: ide_core::IpcPath, + args: Vec, + cwd: ide_core::IpcPath, + }, + /// Plugin languages, or the servers they may start, changed: re-fetch + /// `languages` (the host re-detects open documents: [`crate::Host::plugin_languages_changed`]). + LanguagesChanged, +} + +/// Delivers events to the UI. `client` is the window that invoked the plugin +/// (`None` = broadcast, e.g. during activation). +pub trait PluginEventSink: Send + Sync { + fn emit(&self, client: Option<&str>, event: PluginEvent); +} + +impl, PluginEvent) + Send + Sync> PluginEventSink for F { + fn emit(&self, client: Option<&str>, event: PluginEvent) { + self(client, event) + } +} + +/// The focused editor when a plugin command is invoked. +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PluginEditor { + pub path: String, + pub language: String, + pub selections: Vec, +} + +impl PluginEditor { + pub fn context(self) -> ide_plugin::EditorContext { + ide_plugin::EditorContext { path: self.path.into(), language: self.language, selections: self.selections } + } +} + +/// A plugin's status bar item. +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PluginStatusItem { + pub plugin_id: String, + pub id: String, + pub item: StatusItem, +} + +/// A gutter marker from a plugin's `line-markers` provider. +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct LineMarkerInfo { + pub plugin_id: String, + /// 0-based. + pub line: u32, + /// `navigate` (default), `implemented`, `implementing`, `run`. + pub icon: Option, + pub tooltip: String, + /// Opened on click. + pub target: Option, +} diff --git a/crates/ide-host/src/plugins/ui_points.rs b/crates/ide-host/src/plugins/ui_points.rs new file mode 100644 index 00000000..3b5e3d14 --- /dev/null +++ b/crates/ide-host/src/plugins/ui_points.rs @@ -0,0 +1,544 @@ +//! Declarative UI contributions: menus, key +//! bindings, status bar items and settings (L0, shown before any code runs), +//! and the views and custom editors whose content plugin code renders (L2). +//! Everything is validated here; the client only projects the JSON. +//! +//! ```toml +//! [[contributes.menus]] +//! menu = "editor.context" # projectView.context, editorTab.context, tools +//! command = "check" +//! when = "editorLang == java" +//! +//! [[contributes.keymaps]] +//! command = "check" +//! key = "Ctrl+Alt+C" # `mac` for a different binding on macOS (`Meta+Alt+C`) +//! +//! [[contributes.statusBar]] +//! id = "branch" +//! text = "…" # code replaces it with `set-status-item("branch", …)` +//! command = "show" +//! +//! [contributes.settings] +//! schema = "settings.schema.json" # {"properties": {"key": {"type": "boolean", "default": true, …}}} +//! +//! [[contributes.views]] +//! id = "jobs" +//! title = "Jobs" +//! icon = "server" +//! location = "right" # left, right, bottom +//! +//! [[contributes.customEditors]] +//! id = "table" +//! title = "Table" +//! patterns = ["*.csv", "*.tsv"] +//! priority = "default" # or "option": only through Open With +//! layout = "tab" # or "split" / "preview": beside the text editor +//! web = "web/index.html" # a web page from the package instead of rendered content +//! +//! [[contributes.fileIcons]] +//! id = "drawing" +//! patterns = ["*.excalidraw"] +//! icon = "icons/drawing.svg" +//! iconDark = "icons/drawing_dark.svg" +//! +//! [[contributes.fileTemplates]] +//! id = "drawing" +//! name = "Excalidraw Drawing" +//! extension = "excalidraw" +//! path = "templates/drawing.excalidraw" +//! ``` + +use ide_extension::{Package, UiDecl, decode, validate_item_id, validate_when}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::BTreeSet; +use std::path::PathBuf; + +pub const MENUS: &str = "menus"; +pub const KEYMAPS: &str = "keymaps"; +pub const STATUS_BAR: &str = "statusBar"; +pub const SETTINGS: &str = "settings"; +pub const VIEWS: &str = "views"; +pub const CUSTOM_EDITORS: &str = "customEditors"; +pub const FILE_ICONS: &str = "fileIcons"; +pub const FILE_TEMPLATES: &str = "fileTemplates"; + +const MENU_IDS: [&str; 4] = ["editor.context", "projectView.context", "editorTab.context", "tools"]; +const MAX_TITLE: usize = 256; +const MAX_SETTINGS: usize = 200; +const MAX_PATTERNS: usize = 16; + +/// Command ids the package declares. +fn commands(pkg: &Package) -> BTreeSet { + pkg.manifest + .declarations(super::COMMANDS) + .iter() + .filter_map(|d| d.get("id").and_then(|v| v.as_str()).map(str::to_owned)) + .collect() +} + +fn declared_command(pkg: &Package, point: &str, command: &str) -> Result<(), String> { + if commands(pkg).contains(command) { + Ok(()) + } else { + Err(format!("contributes.{point}: command {command:?} is not declared under [[contributes.commands]]")) + } +} + +fn title(point: &str, t: &str) -> Result<(), String> { + if t.trim().is_empty() || t.len() > MAX_TITLE { + return Err(format!("contributes.{point}: titles are 1–{MAX_TITLE} bytes")); + } + Ok(()) +} + +fn json(v: &T) -> Result { + serde_json::to_value(v).map_err(|e| e.to_string()) +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct MenuDecl { + menu: String, + command: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + when: Option, +} + +pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result { + let d: MenuDecl = decode(MENUS, decl)?; + if !MENU_IDS.contains(&d.menu.as_str()) { + return Err(format!("contributes.menus: unknown menu {:?} (one of {})", d.menu, MENU_IDS.join(", "))); + } + declared_command(pkg, MENUS, &d.command)?; + if let Some(w) = &d.when { + validate_when(w).map_err(|e| format!("contributes.menus: {e}"))?; + } + Ok(UiDecl::new(format!("{}/{}", d.menu, d.command), d.command.clone(), json(&d)?)) +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct KeymapDecl { + command: String, + key: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + mac: Option, +} + +const MODIFIERS: [&str; 4] = ["Meta", "Ctrl", "Alt", "Shift"]; +const NAMED_KEYS: [&str; 22] = [ + "Enter", + "Escape", + "Tab", + "Space", + "Backspace", + "Delete", + "Insert", + "Home", + "End", + "PageUp", + "PageDown", + "Up", + "Down", + "Left", + "Right", + "Minus", + "Equal", + "Comma", + "Period", + "Slash", + "Semicolon", + "Quote", +]; + +/// `Ctrl+Alt+C`, `Meta+K Meta+C` (a chord): at least one modifier per +/// stroke but for function keys, so plugins can't take plain typing. +pub fn validate_binding(binding: &str) -> Result<(), String> { + let strokes: Vec<&str> = binding.split(' ').collect(); + if strokes.is_empty() || strokes.len() > 2 { + return Err(format!("{binding:?}: one stroke, or two for a chord")); + } + for stroke in strokes { + let parts: Vec<&str> = stroke.split('+').collect(); + let (key, mods) = parts.split_last().ok_or_else(|| format!("{binding:?}: empty stroke"))?; + let mut seen = BTreeSet::new(); + for m in mods { + if !MODIFIERS.contains(m) || !seen.insert(*m) { + return Err(format!("{binding:?}: unknown or repeated modifier {m:?}")); + } + } + let function = key.strip_prefix('F').and_then(|n| n.parse::().ok()).is_some_and(|n| (1..=24).contains(&n)); + let plain = key.len() == 1 && key.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit()); + if !(function || plain || NAMED_KEYS.contains(key)) { + return Err(format!("{binding:?}: unknown key {key:?}")); + } + if !function && seen.iter().all(|m| *m == "Shift") { + return Err(format!("{binding:?}: needs Ctrl, Alt or Meta (plain keys are for typing)")); + } + } + Ok(()) +} + +pub(super) fn keymap(pkg: &Package, decl: toml::Value) -> Result { + let d: KeymapDecl = decode(KEYMAPS, decl)?; + declared_command(pkg, KEYMAPS, &d.command)?; + validate_binding(&d.key).map_err(|e| format!("contributes.keymaps: {e}"))?; + if let Some(m) = &d.mac { + validate_binding(m).map_err(|e| format!("contributes.keymaps: {e}"))?; + } + Ok(UiDecl::new(d.command.clone(), d.key.clone(), json(&d)?)) +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct StatusDecl { + id: String, + text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + tooltip: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + command: Option, + #[serde(default = "right")] + align: String, + #[serde(default)] + priority: u32, +} + +fn right() -> String { + "right".into() +} + +pub(super) fn status_item(pkg: &Package, decl: toml::Value) -> Result { + let d: StatusDecl = decode(STATUS_BAR, decl)?; + validate_item_id(&d.id, "status bar item id")?; + if d.text.is_empty() || d.text.len() > 128 || d.tooltip.as_ref().is_some_and(|t| t.len() > 1024) { + return Err(format!("status bar item {:?}: `text` 1–128 bytes, `tooltip` up to 1 KiB", d.id)); + } + if d.align != "left" && d.align != "right" { + return Err(format!("status bar item {:?}: `align` is left or right", d.id)); + } + if d.priority > 1000 { + return Err(format!("status bar item {:?}: `priority` is 0–1000", d.id)); + } + if let Some(c) = &d.command { + declared_command(pkg, STATUS_BAR, c)?; + } + Ok(UiDecl::new(d.id.clone(), d.text.clone(), json(&d)?)) +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SettingsDecl { + #[serde(default)] + title: Option, + schema: PathBuf, +} + +#[derive(Debug, Deserialize)] +struct SchemaFile { + properties: serde_json::Map, +} + +/// One setting of a plugin. +#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SettingSchema { + pub key: String, + /// `boolean`, `string`, `number` or `integer`. + #[serde(rename = "type")] + pub kind: String, + pub title: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + pub default: Value, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub options: Option>, + #[serde(default)] + pub multiline: bool, +} + +impl SettingSchema { + /// Whether `v` is a valid value of this setting. + pub fn accepts(&self, v: &Value) -> bool { + match self.kind.as_str() { + "boolean" => v.is_boolean(), + "integer" => v.is_i64() || v.is_u64(), + "number" => v.is_number(), + _ => v + .as_str() + .is_some_and(|s| s.len() <= 64 << 10 && self.options.as_ref().is_none_or(|o| o.iter().any(|x| x == s))), + } + } +} + +fn setting(key: &str, raw: &Value) -> Result { + if key.is_empty() || key.len() > 64 || !key.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c)) { + return Err(format!("setting {key:?}: keys are 1–64 of [A-Za-z0-9._-]")); + } + let o = raw.as_object().ok_or_else(|| format!("setting {key:?}: expected an object"))?; + let kind = o.get("type").and_then(Value::as_str).unwrap_or(""); + let default = match kind { + "boolean" => o.get("default").cloned().unwrap_or(Value::Bool(false)), + "string" => o.get("default").cloned().unwrap_or(Value::String(String::new())), + "number" | "integer" => o.get("default").cloned().unwrap_or(Value::from(0)), + _ => return Err(format!("setting {key:?}: `type` is boolean, string, number or integer")), + }; + let options = match o.get("enum") { + None => None, + Some(Value::Array(a)) if kind == "string" && !a.is_empty() && a.len() <= 100 => Some( + a.iter() + .map(|v| v.as_str().map(str::to_owned).ok_or_else(|| format!("setting {key:?}: `enum` lists strings"))) + .collect::, _>>()?, + ), + Some(_) => return Err(format!("setting {key:?}: `enum` is 1–100 strings of a string setting")), + }; + let text = |name: &str, max: usize| -> Result, String> { + match o.get(name) { + None => Ok(None), + Some(Value::String(s)) if s.len() <= max => Ok(Some(s.clone())), + Some(_) => Err(format!("setting {key:?}: `{name}` is a string up to {max} bytes")), + } + }; + let s = SettingSchema { + key: key.to_owned(), + kind: kind.to_owned(), + title: text("title", MAX_TITLE)?.unwrap_or_else(|| key.to_owned()), + description: text("description", 4096)?, + default, + options, + multiline: o.get("multiline").and_then(Value::as_bool).unwrap_or(false), + }; + if !s.accepts(&s.default) { + return Err(format!("setting {key:?}: the default does not match its type")); + } + Ok(s) +} + +/// The validated settings of a `[contributes.settings]` schema file. +pub fn parse_settings_schema(text: &str) -> Result, String> { + let file: SchemaFile = serde_json::from_str(text).map_err(|e| e.to_string())?; + if file.properties.len() > MAX_SETTINGS { + return Err(format!("more than {MAX_SETTINGS} settings")); + } + file.properties.iter().map(|(k, v)| setting(k, v)).collect() +} + +pub(super) fn settings(pkg: &Package, decl: toml::Value) -> Result { + let d: SettingsDecl = decode(SETTINGS, decl)?; + let text = pkg.read_text(&d.schema)?; + let properties = parse_settings_schema(&text).map_err(|e| format!("{}: {e}", d.schema.display()))?; + let title = d.title.unwrap_or_else(|| pkg.manifest.name.clone()); + title_ok(&title)?; + let mut decl = + UiDecl::new("settings", title.clone(), serde_json::json!({ "title": title, "properties": properties })); + decl.files.push(d.schema); + Ok(decl) +} + +fn title_ok(t: &str) -> Result<(), String> { + title(SETTINGS, t) +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct ViewDecl { + id: String, + title: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + icon: Option, + #[serde(default = "right")] + location: String, + /// A web page of the package (`web/index.html`) instead of content the code renders. + #[serde(default, skip_serializing_if = "Option::is_none")] + web: Option, +} + +/// The files of a `web` entry, or a check that the code renders the view. +fn web_or_code(pkg: &Package, web: Option<&str>, what: &str) -> Result, String> { + match web { + Some(entry) => super::web::web_files(pkg, entry, what), + None if pkg.manifest.wasm.is_none() => { + Err(format!("{what}: give a web page (`web`) or the code that renders it (`wasm`)")) + } + None => Ok(Vec::new()), + } +} + +pub(super) fn view(pkg: &Package, decl: toml::Value) -> Result { + let d: ViewDecl = decode(VIEWS, decl)?; + validate_item_id(&d.id, "view id")?; + title(VIEWS, &d.title)?; + let files = web_or_code(pkg, d.web.as_deref(), &format!("view {:?}", d.id))?; + if !["left", "right", "bottom"].contains(&d.location.as_str()) { + return Err(format!("view {:?}: `location` is left, right or bottom", d.id)); + } + if d.icon.as_ref().is_some_and(|i| i.len() > 64) { + return Err(format!("view {:?}: icon names are up to 64 bytes", d.id)); + } + let mut out = UiDecl::new(d.id.clone(), d.title.clone(), json(&d)?); + out.files = files; + Ok(out) +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct CustomEditorDecl { + id: String, + title: String, + patterns: Vec, + #[serde(default = "default_priority")] + priority: String, + /// `tab`: the file opens in this editor's own tab. `split` / `preview`: + /// the file opens in the text editor with this editor beside it (Editor / + /// Editor and Preview / Preview); the value is the layout files start in. + #[serde(default = "default_layout")] + layout: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + web: Option, +} + +fn default_priority() -> String { + "default".into() +} + +fn default_layout() -> String { + "tab".into() +} + +/// File name globs (`*.csv`, `{a,b}.json`): no directories. +fn file_patterns(patterns: &[String], what: &str) -> Result<(), String> { + if patterns.is_empty() || patterns.len() > MAX_PATTERNS { + return Err(format!("{what}: 1–{MAX_PATTERNS} file name `patterns`")); + } + for p in patterns { + if p.is_empty() || p.len() > 128 || p.contains(['/', '\\']) || globset::Glob::new(p).is_err() { + return Err(format!("{what}: invalid file name pattern {p:?}")); + } + } + Ok(()) +} + +pub(super) fn custom_editor(pkg: &Package, decl: toml::Value) -> Result { + let d: CustomEditorDecl = decode(CUSTOM_EDITORS, decl)?; + validate_item_id(&d.id, "custom editor id")?; + title(CUSTOM_EDITORS, &d.title)?; + let what = format!("custom editor {:?}", d.id); + let files = web_or_code(pkg, d.web.as_deref(), &what)?; + file_patterns(&d.patterns, &what)?; + if d.priority != "default" && d.priority != "option" { + return Err(format!("{what}: `priority` is default or option")); + } + if !["tab", "split", "preview"].contains(&d.layout.as_str()) { + return Err(format!("{what}: `layout` is tab, split or preview")); + } + let mut out = UiDecl::new(d.id.clone(), d.title.clone(), json(&d)?); + out.files = files; + Ok(out) +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct FileIconDecl { + id: String, + patterns: Vec, + icon: PathBuf, + #[serde(default)] + icon_dark: Option, +} + +/// Asset id of a file icon's SVG (`dark`: its dark-theme variant). +pub fn file_icon_asset(id: &str, dark: bool) -> String { + format!("fileIcon/{id}/{}", if dark { "dark" } else { "light" }) +} + +/// `[[contributes.fileIcons]]`: an icon for the files matching `patterns`, +/// whatever icon theme is in use (the user's own file type icons still win). +pub(super) fn file_icon(pkg: &Package, decl: toml::Value) -> Result { + let d: FileIconDecl = decode(FILE_ICONS, decl)?; + validate_item_id(&d.id, "file icon id")?; + let what = format!("file icon {:?}", d.id); + file_patterns(&d.patterns, &what)?; + let mut files = Vec::new(); + let mut assets = Vec::new(); + for (path, dark) in [(Some(&d.icon), false), (d.icon_dark.as_ref(), true)] { + let Some(path) = path else { continue }; + let svg = super::icons::read_icon(pkg, path)?; + assets.push((file_icon_asset(&d.id, dark), svg)); + files.push(path.clone()); + } + let json = serde_json::json!({ "id": d.id, "patterns": d.patterns, "dark": d.icon_dark.is_some() }); + let mut out = UiDecl::new(d.id.clone(), d.patterns.join(", "), json); + out.files = files; + out.assets = assets; + Ok(out) +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct FileTemplateDecl { + id: String, + name: String, + /// Without the dot. + extension: String, + /// The new file's content (`$NAME$`, `$END$` and the other template variables work). + path: PathBuf, +} + +const MAX_TEMPLATE: usize = 256 << 10; + +/// `[[contributes.fileTemplates]]`: an entry of the New menu. +pub(super) fn file_template(pkg: &Package, decl: toml::Value) -> Result { + let d: FileTemplateDecl = decode(FILE_TEMPLATES, decl)?; + validate_item_id(&d.id, "file template id")?; + title(FILE_TEMPLATES, &d.name)?; + let what = format!("file template {:?}", d.id); + let ext = d.extension.trim_start_matches('.'); + if ext.is_empty() + || ext.len() > 32 + || !ext.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')) + { + return Err(format!("{what}: `extension` is a file extension like \"md\" ({:?})", d.extension)); + } + let body = pkg.read_text(&d.path)?; + if body.len() > MAX_TEMPLATE { + return Err(format!("{what}: {} is larger than {} KiB", d.path.display(), MAX_TEMPLATE >> 10)); + } + let json = serde_json::json!({ "id": d.id, "name": d.name, "extension": ext, "body": body }); + let mut out = UiDecl::new(d.id.clone(), d.name.clone(), json); + out.files = vec![d.path.clone()]; + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bindings_need_a_modifier() { + for ok in ["Ctrl+Alt+C", "Meta+Shift+K", "F5", "Shift+F6", "Meta+K Meta+C", "Alt+Enter"] { + assert!(validate_binding(ok).is_ok(), "{ok}"); + } + for bad in ["C", "Shift+C", "Hyper+C", "Ctrl+Ctrl+C", "Ctrl+é", "Ctrl+A B C", ""] { + assert!(validate_binding(bad).is_err(), "{bad}"); + } + } + + #[test] + fn settings_schemas_are_typed() { + let s = parse_settings_schema( + r#"{"properties": { + "context": {"type": "string", "title": "Context", "default": ""}, + "watch": {"type": "boolean", "default": true}, + "mode": {"type": "string", "enum": ["a", "b"], "default": "b"}, + "limit": {"type": "integer", "default": 100} + }}"#, + ) + .unwrap(); + assert_eq!(s.len(), 4); + assert!(s.iter().find(|x| x.key == "mode").unwrap().accepts(&Value::from("a"))); + assert!(!s.iter().find(|x| x.key == "mode").unwrap().accepts(&Value::from("c"))); + assert!(parse_settings_schema(r#"{"properties": {"x": {"type": "string", "default": 3}}}"#).is_err()); + assert!(parse_settings_schema(r#"{"properties": {"x": {"type": "object"}}}"#).is_err()); + } +} diff --git a/crates/ide-host/src/plugins/views.rs b/crates/ide-host/src/plugins/views.rs new file mode 100644 index 00000000..a62484ea --- /dev/null +++ b/crates/ide-host/src/plugins/views.rs @@ -0,0 +1,92 @@ +//! Declarative views and custom editors as the +//! window commands `plugin_view_render` / `plugin_view_event` serve them — +//! the desktop for local projects, `openidea-server` for remote ones. + +use super::{PluginEditor, PluginHost}; +use ide_core::{DocId, IdeError, IdeResult}; +use ide_plugin::{EditorContext, Invocation, View, ViewEvent, Viewport}; +use std::sync::Arc; + +/// The window's project, plus the editor the call is about: the document a +/// custom editor shows, else (a tool window) the window's active editor, as +/// a command gets it, so a view's buttons can act on what the user is editing. +pub fn view_invocation( + host: &crate::Host, + window: &str, + doc: Option, + editor: Option, +) -> IdeResult { + let project = host.project(window).ok(); + let editor = match doc { + None => editor.map(PluginEditor::context), + Some(doc) => { + let project = project.as_ref().ok_or_else(|| IdeError::not_found("no project is open in this window"))?; + let info = project.documents.snapshot(doc)?; + Some(EditorContext { path: info.path.0, language: info.language.0, selections: Vec::new() }) + } + }; + Ok(Invocation { client: Some(window.to_owned()), workspace_root: project.as_ref().map(|p| p.root.clone()), editor }) +} + +async fn blocking(f: impl FnOnce() -> IdeResult + Send + 'static) -> IdeResult { + tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))? +} + +#[allow(clippy::too_many_arguments)] +pub async fn render( + host: &crate::Host, + plugins: Arc, + window: &str, + plugin_id: String, + view: String, + viewport: Option, + doc: Option, + editor: Option, +) -> IdeResult { + let invocation = view_invocation(host, window, doc, editor)?; + blocking(move || plugins.render_view(&plugin_id, &view, viewport, invocation)).await +} + +#[allow(clippy::too_many_arguments)] +pub async fn event( + host: &crate::Host, + plugins: Arc, + window: &str, + plugin_id: String, + view: String, + event: ViewEvent, + doc: Option, + editor: Option, +) -> IdeResult<()> { + let invocation = view_invocation(host, window, doc, editor)?; + blocking(move || plugins.view_event(&plugin_id, &view, event, invocation)).await +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Host, HostConfig}; + + #[tokio::test] + async fn a_tool_window_call_carries_the_active_editor() { + let tmp = tempfile::tempdir().unwrap(); + let host = Host::new(HostConfig { + config_dir: tmp.path().join("config"), + data_dir: tmp.path().join("data"), + local_data_dir: tmp.path().join("data"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(|_| Arc::new(ide_core::NullSink)), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + }); + let range = ide_core::Range::new(ide_core::Pos::new(1, 0), ide_core::Pos::new(1, 4)); + let active = PluginEditor { path: "/p/a.rs".into(), language: "rust".into(), selections: vec![range] }; + let inv = view_invocation(&host, "main", None, Some(active)).unwrap(); + let editor = inv.editor.expect("the active editor"); + assert_eq!((editor.path.to_string_lossy().as_ref(), editor.selections.as_slice()), ("/p/a.rs", &[range][..])); + assert_eq!(inv.client.as_deref(), Some("main")); + assert!(view_invocation(&host, "main", None, None).unwrap().editor.is_none()); + } +} diff --git a/crates/ide-host/src/plugins/web.rs b/crates/ide-host/src/plugins/web.rs new file mode 100644 index 00000000..11a109f8 --- /dev/null +++ b/crates/ide-host/src/plugins/web.rs @@ -0,0 +1,245 @@ +//! Web views: a view or custom editor whose UI is a web page shipped in the +//! package (`web = "web/index.html"`) instead of content the plugin's code +//! renders. +//! +//! The entry's directory is the page's root. Every file under it is part of +//! the declaration: it is checked when the package is prepared (count, size, +//! no links leaving the package), copied on install and covered by the +//! package digest and signature. The client loads the page in a sandboxed +//! frame (an opaque origin with no network and no IDE API) and fetches its +//! files through [`PluginHost::web_file`] (the desktop's `openidea-plugin` +//! URL scheme); the page talks to the IDE only through the frame bridge. + +use super::PluginHost; +use ide_core::{IdeError, IdeResult}; +use ide_extension::{Package, check_relative}; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::path::{Component, Path, PathBuf}; + +/// Most files under one web root. +const MAX_FILES: usize = 4096; +/// Most bytes under one web root. +const MAX_BYTES: u64 = 256 << 20; +/// Deepest directory nesting under a web root. +const MAX_DEPTH: usize = 16; + +/// Checks a declaration's `web` entry: an `.html` file inside a directory of +/// the package (the directory is what the page can load, so it can't be the +/// package root), and everything under that directory. Returns those files, +/// package-relative. +pub(super) fn web_files(pkg: &Package, entry: &str, what: &str) -> Result, String> { + let path = Path::new(entry); + check_relative(path, "web")?; + if entry.contains('\\') || !entry.to_ascii_lowercase().ends_with(".html") { + return Err(format!("{what}: `web` names an .html file, `/`-separated ({entry:?})")); + } + let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).ok_or_else(|| { + format!("{what}: put the page in a directory of its own (`web/index.html`): the directory is what it can load") + })?; + let real_entry = pkg.resolve(path)?; + if !real_entry.is_file() { + return Err(format!("{what}: {entry} is not a file")); + } + let root = pkg.resolve(dir)?; + let mut files = Vec::new(); + let mut total = 0u64; + let mut stack = vec![(root.clone(), dir.to_path_buf(), 0usize)]; + while let Some((real, rel, depth)) = stack.pop() { + let mut entries: Vec<_> = + std::fs::read_dir(&real).map_err(|e| format!("{}: {e}", rel.display()))?.filter_map(Result::ok).collect(); + entries.sort_by_key(|e| e.file_name()); + for e in entries { + let name = e.file_name(); + let rel = rel.join(&name); + // Links could point anywhere: only what is really in the package counts. + let ty = e.file_type().map_err(|err| format!("{}: {err}", rel.display()))?; + if ty.is_symlink() { + return Err(format!("{what}: {} is a link; web files must be real files", rel.display())); + } + if ty.is_dir() { + if depth + 1 > MAX_DEPTH { + return Err(format!("{what}: {} is nested deeper than {MAX_DEPTH} directories", rel.display())); + } + stack.push((e.path(), rel, depth + 1)); + continue; + } + if name.to_string_lossy() == ".DS_Store" { + continue; + } + let len = e.metadata().map_err(|err| format!("{}: {err}", rel.display()))?.len(); + if len > ide_extension::MAX_PACKAGE_FILE { + return Err(format!( + "{what}: {} is larger than {} MiB", + rel.display(), + ide_extension::MAX_PACKAGE_FILE >> 20 + )); + } + total += len; + files.push(rel); + if files.len() > MAX_FILES || total > MAX_BYTES { + return Err(format!( + "{what}: {} holds more than {MAX_FILES} files or {} MiB", + dir.display(), + MAX_BYTES >> 20 + )); + } + } + } + files.sort(); + Ok(files) +} + +/// The page of a web view, for the client to load in its frame. +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct WebPage { + /// `//` under the `openidea-plugin` scheme. The + /// revision changes with the installed package, so a cached file is never + /// stale; relative URLs in the page resolve to the package's files. + pub path: String, +} + +/// A file of a web view. +pub struct WebFile { + pub bytes: Vec, + pub mime: &'static str, +} + +impl PluginHost { + /// The web roots `plugin` declares (entry directories, package-relative, `/`-terminated). + fn web_dirs(&self, plugin: &str) -> Vec { + [super::ui_points::VIEWS, super::ui_points::CUSTOM_EDITORS] + .iter() + .flat_map(|point| self.ui.items(point, Some(plugin))) + .filter_map(|item| item.decl.get("web").and_then(|w| w.as_str()).map(str::to_owned)) + .filter_map(|entry| entry.rsplit_once('/').map(|(dir, _)| format!("{dir}/"))) + .collect() + } + + /// Changes whenever the installed package does (cache key of its web files). + fn web_revision(&self, plugin: &super::LoadedPlugin) -> String { + let digest = plugin.pkg.digest.as_deref().unwrap_or_default(); + let short: String = digest.chars().filter(char::is_ascii_alphanumeric).take(16).collect(); + if short.is_empty() { format!("v{}", plugin.pkg.manifest.version) } else { short } + } + + /// The page of `plugin`'s view or custom editor `view`. + pub fn web_page(&self, plugin_id: &str, view: &str) -> IdeResult { + let plugin = self.get(plugin_id)?; + if !plugin.status().is_live() { + return Err(IdeError::unavailable(format!("plugin {plugin_id:?} is not enabled"))); + } + let entry = [super::ui_points::VIEWS, super::ui_points::CUSTOM_EDITORS] + .iter() + .flat_map(|point| self.ui.items(point, Some(plugin_id))) + .find(|item| item.key == view) + .and_then(|item| item.decl.get("web").and_then(|w| w.as_str()).map(str::to_owned)) + .ok_or_else(|| IdeError::not_found(format!("plugin {plugin_id:?} has no web view {view:?}")))?; + Ok(WebPage { path: format!("{plugin_id}/{}/{entry}", self.web_revision(&plugin)) }) + } + + /// A file of one of `plugin`'s web views: `path` is `/` + /// as [`WebPage::path`] makes them. Only files under a declared web root + /// of a live plugin are served; the revision must be the installed one. + pub fn web_file(&self, plugin_id: &str, path: &str) -> IdeResult { + let plugin = self.get(plugin_id)?; + if !plugin.status().is_live() { + return Err(IdeError::unavailable(format!("plugin {plugin_id:?} is not enabled"))); + } + let (revision, rel) = path.split_once('/').ok_or_else(|| IdeError::not_found(path.to_owned()))?; + if revision != self.web_revision(&plugin) { + return Err(IdeError::not_found(format!("{path}: not the installed version"))); + } + let rel_path = Path::new(rel); + if !rel_path.components().all(|c| matches!(c, Component::Normal(_))) { + return Err(IdeError::invalid(format!("{rel}: not a plain relative path"))); + } + if !self.web_dirs(plugin_id).iter().any(|dir| rel.starts_with(dir.as_str())) { + return Err(IdeError::not_found(format!("{rel}: not part of a web view"))); + } + let bytes = plugin.pkg.read_bytes(rel_path).map_err(IdeError::not_found)?; + Ok(WebFile { bytes, mime: mime(rel) }) + } +} + +/// Content type by extension; unknown files are opaque bytes (never sniffed as script). +pub fn mime(path: &str) -> &'static str { + let ext = path.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); + match ext.as_str() { + "html" | "htm" => "text/html; charset=utf-8", + "js" | "mjs" | "cjs" => "text/javascript; charset=utf-8", + "css" => "text/css; charset=utf-8", + "json" | "map" => "application/json", + "wasm" => "application/wasm", + "svg" => "image/svg+xml", + "png" => "image/png", + "jpg" | "jpeg" => "image/jpeg", + "gif" => "image/gif", + "webp" => "image/webp", + "avif" => "image/avif", + "ico" => "image/x-icon", + "woff2" => "font/woff2", + "woff" => "font/woff", + "ttf" => "font/ttf", + "otf" => "font/otf", + "txt" | "md" => "text/plain; charset=utf-8", + "mp3" => "audio/mpeg", + "mp4" => "video/mp4", + "webm" => "video/webm", + _ => "application/octet-stream", + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ide_extension::Manifest; + + fn pkg(dir: &Path) -> Package { + let src = "id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\n"; + Package::new(Manifest::parse(src).unwrap(), dir.to_path_buf()) + } + + #[test] + fn a_web_root_is_its_directory_and_nothing_else() { + let tmp = tempfile::tempdir().unwrap(); + let d = tmp.path(); + std::fs::create_dir_all(d.join("web/assets/fonts")).unwrap(); + std::fs::write(d.join("web/index.html"), "

hi

").unwrap(); + std::fs::write(d.join("web/assets/app.js"), "1").unwrap(); + std::fs::write(d.join("web/assets/fonts/a.woff2"), "f").unwrap(); + std::fs::write(d.join("web/.DS_Store"), "x").unwrap(); + std::fs::write(d.join("secret.txt"), "no").unwrap(); + let files = web_files(&pkg(d), "web/index.html", "v").unwrap(); + let files: Vec = files.iter().map(|f| f.to_string_lossy().replace('\\', "/")).collect(); + assert_eq!(files, ["web/assets/app.js", "web/assets/fonts/a.woff2", "web/index.html"]); + + std::fs::write(d.join("index.html"), "x").unwrap(); + let err = |entry: &str| web_files(&pkg(d), entry, "v").err().unwrap_or_default(); + assert!(err("index.html").contains("directory of its own"), "{}", err("index.html")); + assert!(err("web/app.js").contains(".html")); + assert!(err("../web/index.html").contains("relative")); + assert!(err("web/missing.html").contains("no such file")); + } + + #[cfg(unix)] + #[test] + fn links_out_of_a_web_root_are_refused() { + let tmp = tempfile::tempdir().unwrap(); + let d = tmp.path(); + std::fs::create_dir_all(d.join("web")).unwrap(); + std::fs::write(d.join("web/index.html"), "x").unwrap(); + std::os::unix::fs::symlink("/etc/hosts", d.join("web/hosts")).unwrap(); + assert!(web_files(&pkg(d), "web/index.html", "v").unwrap_err().contains("is a link")); + } + + #[test] + fn content_types_never_make_unknown_files_scripts() { + assert_eq!(mime("a/b.JS"), "text/javascript; charset=utf-8"); + assert_eq!(mime("x.woff2"), "font/woff2"); + assert_eq!(mime("x.wasm"), "application/wasm"); + assert_eq!(mime("x.bin"), "application/octet-stream"); + assert_eq!(mime("noext"), "application/octet-stream"); + } +} diff --git a/crates/ide-host/src/rpc.rs b/crates/ide-host/src/rpc.rs index 2ab5bd7f..38795f7d 100644 --- a/crates/ide-host/src/rpc.rs +++ b/crates/ide-host/src/rpc.rs @@ -9,7 +9,10 @@ //! * server → client notification `event` `{ window, event }` (an `IdeEvent` //! for that window, or every window when `window` is null); //! * server → client notification `channel` `{ id, data }`: one value of a -//! streaming argument. +//! streaming argument; +//! * server → client notification `plugin` `{ window, event }` and request +//! `plugin_secret` `{ plugin, name }` → `string | null`: code plugins of the +//! remote project (`plugins::remote_host`). use crate::Host; use crate::ops::{self, Emit}; diff --git a/crates/ide-host/src/trust.rs b/crates/ide-host/src/trust.rs index d0e0731d..ea9b9604 100644 --- a/crates/ide-host/src/trust.rs +++ b/crates/ide-host/src/trust.rs @@ -273,6 +273,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool { | "plugin_set_theme" | "plugin_set_theme_frame" | "plugin_catalog" + | "plugin_assets" | "notebook_open" | "notebook_get" | "notebook_edit" diff --git a/crates/ide-host/tests/distribution.rs b/crates/ide-host/tests/distribution.rs new file mode 100644 index 00000000..540073a5 --- /dev/null +++ b/crates/ide-host/tests/distribution.rs @@ -0,0 +1,262 @@ +//! Versioned installs with automatic rollback, signed packages from +//! a static marketplace index, and revocation. + +use ide_extension::package::{self, Index, IndexEntry, KeyEntry, Publisher, PublisherKey, Revocation}; +use ide_host::plugins::*; +use ide_plugin::{Invocation, Limits}; +use parking_lot::Mutex; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +type Events = Arc>>; + +fn repo() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") +} + +fn copy_dir(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for entry in std::fs::read_dir(from).unwrap().flatten() { + let (src, dst) = (entry.path(), to.join(entry.file_name())); + if entry.file_name() == "target" { + continue; + } + if src.is_dir() { copy_dir(&src, &dst) } else { std::fs::copy(&src, &dst).map(|_| ()).unwrap() } + } +} + +/// A copy of `from` (under `dir/name`) whose manifest is rewritten by `f`. +fn variant(from: &Path, dir: &Path, name: &str, f: impl Fn(&str) -> String) -> PathBuf { + let pkg = dir.join(name); + copy_dir(from, &pkg); + let manifest = pkg.join("plugin.toml"); + std::fs::write(&manifest, f(&std::fs::read_to_string(&manifest).unwrap())).unwrap(); + pkg +} + +struct Fixture { + host: PluginHost, + plugins_dir: PathBuf, + events: Events, + _tmp: tempfile::TempDir, + work: PathBuf, +} + +fn fixture() -> Fixture { + let tmp = tempfile::tempdir().unwrap(); + let plugins_dir = tmp.path().join("plugins"); + let events: Events = Arc::default(); + let sink = { + let events = events.clone(); + move |_: Option<&str>, e: PluginEvent| events.lock().push(e) + }; + let host = PluginHost::new(plugins_dir.clone(), Arc::new(sink), Limits::default()).unwrap(); + host.load_all(); + let work = tmp.path().join("work"); + std::fs::create_dir_all(&work).unwrap(); + Fixture { host, plugins_dir, events, work, _tmp: tmp } +} + +fn inv() -> Invocation { + Invocation { client: Some("main".into()), workspace_root: None, editor: None } +} + +fn misbehave() -> PathBuf { + repo().join("crates/ide-plugin/tests/fixtures/misbehave") +} + +/// P8 acceptance: an update that fails to start rolls back to the version it replaced. +#[test] +fn a_failing_update_rolls_back_automatically() { + let f = fixture(); + let v1 = variant(&misbehave(), &f.work, "v1", |t| t.replace("version = \"0.0.2\"", "version = \"1.0.0\"")); + f.host.install_from_dir(&v1, &Consent::all()).unwrap(); + assert_eq!(f.host.run_command("misbehave", "echo", Some("hi"), inv()).unwrap().as_deref(), Some("hi")); + + let broken = + variant(&misbehave(), &f.work, "v2", |t| t.replace("version = \"0.0.2\"", "version = \"2.0.0-broken\"")); + let info = f.host.install_from_dir(&broken, &Consent::all()).unwrap(); + assert_eq!((info.version.as_str(), info.previous_version.as_deref()), ("2.0.0-broken", Some("1.0.0"))); + let root = f.plugins_dir.join("misbehave"); + assert!(root.join("2.0.0-broken").is_dir() && root.join("1.0.0").is_dir(), "versions side by side"); + + // Its first start fails: back to 1.0.0, without the user doing anything. + f.events.lock().clear(); + let err = f.host.run_command("misbehave", "echo", Some("x"), inv()).unwrap_err(); + assert!(err.message.contains("version 1.0.0 was restored"), "{}", err.message); + let info = f.host.info_of("misbehave").unwrap(); + assert_eq!((info.version.as_str(), info.status), ("1.0.0", PluginStatus::Inactive)); + assert!(!root.join("2.0.0-broken").exists(), "the failed version is removed"); + assert!( + f.events + .lock() + .iter() + .any(|e| matches!(e, PluginEvent::Notification { title, .. } if title.contains("rolled back"))) + ); + assert_eq!(f.host.run_command("misbehave", "echo", Some("ok"), inv()).unwrap().as_deref(), Some("ok")); + + // A working update is confirmed by its first start; the user can still roll it back. + let v3 = variant(&misbehave(), &f.work, "v3", |t| t.replace("version = \"0.0.2\"", "version = \"3.0.0\"")); + f.host.install_from_dir(&v3, &Consent::all()).unwrap(); + f.host.run_command("misbehave", "echo", None, inv()).unwrap(); + assert_eq!(f.host.info_of("misbehave").unwrap().version, "3.0.0"); + let info = f.host.roll_back_update("misbehave").unwrap(); + assert_eq!((info.version.as_str(), info.previous_version.as_deref()), ("1.0.0", None)); + assert!(f.host.roll_back_update("misbehave").is_err(), "nothing older to go back to"); + + // A restart loads the active version. + let again = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); + again.load_all(); + assert_eq!(again.info_of("misbehave").unwrap().version, "1.0.0"); + f.host.uninstall("misbehave").unwrap(); + assert!(!root.exists(), "every version goes"); +} + +#[test] +fn installs_from_before_versioning_keep_working_and_move_on_update() { + let f = fixture(); + // The flat layout of earlier releases. + copy_dir(&misbehave(), &f.plugins_dir.join("misbehave")); + let again = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); + again.load_all(); + assert_eq!(again.info_of("misbehave").unwrap().version, "0.0.2"); + let v1 = variant(&misbehave(), &f.work, "v1", |t| t.replace("version = \"0.0.2\"", "version = \"1.0.0\"")); + let info = again.install_from_dir(&v1, &Consent::all()).unwrap(); + assert_eq!((info.version.as_str(), info.previous_version.as_deref()), ("1.0.0", Some("0.0.2"))); + assert!(f.plugins_dir.join("misbehave/0.0.2/plugin.toml").is_file()); + assert!(f.plugins_dir.join("misbehave/1.0.0/plugin.toml").is_file()); +} + +// ---- marketplace ------------------------------------------------------------------ + +/// `hello` as `acme.hello` at `version`, packed and signed with `key`. +fn signed_hello(dir: &Path, version: &str, key: &PublisherKey, host: &PluginHost) -> (PathBuf, IndexEntry) { + let src = variant(&repo().join("crates/ide-plugin/tests/fixtures/hello"), dir, &format!("src-{version}"), |t| { + t.replace("id = \"hello\"", "id = \"acme.hello\"") + .replace("version = \"0.3.0\"", &format!("version = \"{version}\"")) + }); + let files = host.package_files_of(&src).unwrap(); + let digest = package::package_digest(&src, &files).unwrap(); + let sig = key.sign("acme", "acme.hello", version, &digest); + let out = dir.join(format!("acme.hello-{version}.oiplugin")); + package::pack(&src, &files, &out, Some(&sig)).unwrap(); + let entry = IndexEntry { + id: "acme.hello".into(), + name: "Hello".into(), + version: version.into(), + description: String::new(), + authors: vec![], + publisher: "acme".into(), + download: out.file_name().unwrap().to_string_lossy().into_owned(), + digest, + capabilities: vec![], + }; + (out, entry) +} + +fn write_index( + dir: &Path, + key: &PublisherKey, + plugins: Vec, + revoked: Vec, + key_revoked: bool, +) -> String { + let index = Index { + format: package::INDEX_FORMAT, + publishers: vec![Publisher { + id: "acme".into(), + name: "ACME".into(), + keys: vec![KeyEntry { key: key.public_base64(), revoked: key_revoked }], + }], + plugins, + revoked, + }; + let path = dir.join("index.json"); + std::fs::write(&path, serde_json::to_string(&index).unwrap()).unwrap(); + path.to_string_lossy().into_owned() +} + +#[test] +fn signed_marketplace_plugins_install_and_revocations_disable_them() { + let f = fixture(); + let market = f.work.join("market"); + std::fs::create_dir_all(&market).unwrap(); + let key = PublisherKey::from_seed([3; 32]); + let (_, entry) = signed_hello(&market, "1.0.0", &key, &f.host); + let url = write_index(&market, &key, vec![entry.clone()], vec![], false); + + assert!(f.host.refresh_market().is_err(), "no marketplace configured yet"); + f.host.set_market_url(Some(url.clone())); + let listed = f.host.refresh_market().unwrap(); + assert_eq!((listed[0].entry.id.as_str(), listed[0].installed.as_deref()), ("acme.hello", None)); + + let dir = f.host.download_market_plugin("acme.hello").unwrap(); + let preview = f.host.preview_install(&dir).unwrap(); + assert_eq!((preview.unsigned, preview.publisher.as_deref()), (false, Some("acme"))); + let info = f.host.install_from_dir(&dir, &Consent::all()).unwrap(); + assert_eq!(info.publisher.as_deref(), Some("acme")); + assert_eq!(f.host.market_plugins()[0].installed.as_deref(), Some("1.0.0")); + + // A changed file breaks the signature: refused. + let tampered = f.host.download_market_plugin("acme.hello").unwrap(); + let manifest = std::fs::read_to_string(tampered.join("plugin.toml")).unwrap(); + std::fs::write(tampered.join("plugin.toml"), manifest.replace("Sample plugin", "Totally safe plugin")).unwrap(); + let err = f.host.preview_install(&tampered).unwrap_err(); + assert!(err.message.contains("changed after signing"), "{}", err.message); + + // Someone else's key, or another publisher's prefix: not trusted. + let stranger = PublisherKey::from_seed([4; 32]); + let (foreign, _) = signed_hello(&f.work, "1.0.1", &stranger, &f.host); + let unpacked = f.host.unpack_package(&foreign).unwrap(); + assert!(f.host.preview_install(&unpacked).unwrap_err().message.contains("not one of")); + + // The index revokes the installed version: disabled, the user told. + f.events.lock().clear(); + let revoked = + vec![Revocation { id: "acme.hello".into(), versions: vec!["1.0.0".into()], reason: "steals tokens".into() }]; + write_index(&market, &key, vec![entry.clone()], revoked, false); + f.host.refresh_market().unwrap(); + let info = f.host.info_of("acme.hello").unwrap(); + assert_eq!((info.status, info.error.as_deref()), (PluginStatus::Failed, Some("revoked: steals tokens"))); + assert!( + f.events + .lock() + .iter() + .any(|e| matches!(e, PluginEvent::Notification { body, .. } if body.contains("steals tokens"))) + ); + assert!(f.host.market_plugins().is_empty(), "revoked versions are not offered"); + assert!(f.host.install_from_dir(&dir, &Consent::all()).is_err(), "nor installable"); + f.host.set_enabled("acme.hello", true).unwrap(); + assert_eq!(f.host.info_of("acme.hello").unwrap().status, PluginStatus::Failed, "enabling doesn't bring it back"); + + // Revocations hold across restarts (the index is kept). + let again = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); + again.load_all(); + assert_eq!(again.info_of("acme.hello").unwrap().status, PluginStatus::Failed); + + // A revoked signing key disables what it signed. + write_index(&market, &key, vec![entry.clone()], vec![], true); + f.host.refresh_market().unwrap(); + let info = f.host.info_of("acme.hello").unwrap(); + assert!(info.error.as_deref().unwrap_or("").contains("signing key was revoked"), "{:?}", info.error); + + // Lifted: it runs again. + write_index(&market, &key, vec![entry], vec![], false); + f.host.refresh_market().unwrap(); + let info = f.host.info_of("acme.hello").unwrap(); + assert_eq!((info.status, info.error), (PluginStatus::Inactive, None)); +} + +#[test] +fn package_files_install_from_disk_unsigned() { + let f = fixture(); + let src = variant(&misbehave(), &f.work, "pkg", |t| t.to_owned()); + let files = f.host.package_files_of(&src).unwrap(); + let out = f.work.join("misbehave-0.0.2.oiplugin"); + package::pack(&src, &files, &out, None).unwrap(); + let dir = f.host.unpack_package(&out).unwrap(); + let preview = f.host.preview_install(&dir).unwrap(); + assert_eq!((preview.unsigned, preview.publisher), (true, None)); + let info = f.host.install_from_dir(&dir, &Consent::all()).unwrap(); + assert_eq!((info.status, info.publisher), (PluginStatus::Inactive, None)); +} diff --git a/crates/ide-host/tests/plugins.rs b/crates/ide-host/tests/plugins.rs new file mode 100644 index 00000000..35139a57 --- /dev/null +++ b/crates/ide-host/tests/plugins.rs @@ -0,0 +1,2330 @@ +//! End-to-end tests of the plugin host against real components. +//! +//! The components are checked in (`dist/plugin.wasm` of the official plugins +//! and of the fixtures in `crates/ide-plugin/tests/fixtures/`: `hello`, `jobs`, +//! `misbehave`) so tests need no wasm toolchain. Rebuild them with +//! `plugins/build.sh ` after changing their source or `wit/`. + +use ide_core::error::ErrorKind; +use ide_host::plugins::*; +use ide_plugin::{EditorContext, HostError, Invocation, Limits}; +use parking_lot::Mutex; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +type Events = Arc, PluginEvent)>>>; + +/// What plugins see of the test project: real `Documents`, as in the IDE. +struct TestWorkspace { + root: PathBuf, + documents: Arc, + trusted: bool, + /// (producer, path) → published diagnostics. + diagnostics: Mutex>>, + /// plugin → its settings as the user set them. + settings: Mutex>>, +} + +impl TestWorkspace { + fn new(root: &Path) -> Arc { + let documents = ide_workspace::Documents::new( + Arc::new(ide_core::NullSink), + Box::new(|_: &Path, _: Option<&str>| ide_core::LanguageId::new("text")), + ); + Arc::new(Self { + root: root.to_path_buf(), + documents: Arc::new(documents), + trusted: true, + diagnostics: Mutex::default(), + settings: Mutex::default(), + }) + } + + /// Opens `rel` in an "editor": the invocation's focused editor. + fn open(&self, rel: &str, selections: &[(u32, u32, u32, u32)]) -> EditorContext { + let path = self.root.join(rel); + self.documents.open(&path).unwrap(); + let selections = selections + .iter() + .map(|&(a, b, c, d)| ide_core::Range::new(ide_core::Pos::new(a, b), ide_core::Pos::new(c, d))) + .collect(); + EditorContext { path, language: "text".into(), selections } + } + + fn text(&self, rel: &str) -> String { + self.documents.text_of(&self.root.join(rel)).unwrap() + } + + /// The user types at the start of the document. + fn type_text(&self, rel: &str, text: &str) { + let doc = self.documents.by_path(&self.root.join(rel)).unwrap(); + let edit = ide_core::TextEdit { range: ide_core::Range::default(), new_text: text.into() }; + self.documents.apply_edits(doc, &[edit]).unwrap(); + } +} + +impl PluginWorkspace for TestWorkspace { + fn projects(&self) -> Vec { + vec![self.root.clone()] + } + fn buffer_text(&self, path: &Path) -> Option { + self.documents.text_of(path) + } + fn document(&self, path: &Path) -> Option<(u64, String)> { + let snap = self.documents.snapshot(self.documents.by_path(path)?).ok()?; + Some((u64::from(snap.version), snap.text)) + } + fn apply_edits(&self, path: &Path, version: u64, edits: &[ide_core::TextEdit]) -> Result { + let doc = self.documents.by_path(path).ok_or_else(|| HostError::NotFound("not open".into()))?; + match self.documents.apply_edits_at(doc, version as u32, edits) { + Ok(Some(v)) => Ok(u64::from(v)), + Ok(None) => Err(HostError::Stale), + Err(e) => Err(HostError::Failed(e.message)), + } + } + fn trusted(&self, _root: &Path) -> bool { + self.trusted + } + fn project_of(&self, _window: &str) -> Option { + Some(self.root.clone()) + } + fn publish_diagnostics( + &self, + source: &str, + path: &Path, + items: Vec, + ) -> Result<(), HostError> { + if !path.starts_with(&self.root) { + return Err(HostError::Invalid("not in the project".into())); + } + self.diagnostics.lock().insert((source.to_owned(), path.to_path_buf()), items); + Ok(()) + } + fn plugin_settings(&self, plugin: &str, _root: Option<&Path>) -> serde_json::Map { + self.settings.lock().get(plugin).cloned().unwrap_or_default() + } +} + +fn repo() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../..").canonicalize().unwrap() +} + +/// A test fixture plugin (`crates/ide-plugin/tests/fixtures/`). +fn sample(name: &str) -> PathBuf { + repo().join("crates/ide-plugin/tests/fixtures").join(name) +} + +fn theme_template() -> PathBuf { + repo().join("plugins/official/harbor-night") +} + +fn misbehave_pkg() -> PathBuf { + repo().join("crates/ide-plugin/tests/fixtures/misbehave") +} + +/// A theme package with a light and a dark theme, plus licence files, in `dir`. +fn write_theme_pair(dir: &Path) { + std::fs::create_dir_all(dir.join("t")).unwrap(); + std::fs::write( + dir.join("plugin.toml"), + "id = \"theme-pair\"\nname = \"Pair\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\n\ + [[contributes.themes]]\npath = \"t/day.json\"\n[[contributes.themes]]\npath = \"t/night.json\"\n", + ) + .unwrap(); + std::fs::write( + dir.join("t/day.json"), + r##"{"id":"day","name":"Day","kind":"light","tokens":{"--bg-frame":"#eeeeee"}}"##, + ) + .unwrap(); + std::fs::write( + dir.join("t/night.json"), + r##"{"id":"night","name":"Night","kind":"dark","tokens":{"--bg-frame":"#111111"}}"##, + ) + .unwrap(); + std::fs::write(dir.join("LICENSE"), "MIT License\n").unwrap(); + std::fs::write(dir.join("NOTICE"), "Palette notice\n").unwrap(); +} + +fn copy_dir(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for entry in std::fs::read_dir(from).unwrap().flatten() { + let (src, dst) = (entry.path(), to.join(entry.file_name())); + if entry.file_name() == "target" { + continue; + } + if src.is_dir() { copy_dir(&src, &dst) } else { std::fs::copy(&src, &dst).map(|_| ()).unwrap() } + } +} + +/// A copy of `hello` whose manifest is rewritten by `f`. +fn hello_variant(dir: &Path, f: impl Fn(&str) -> String) -> PathBuf { + let pkg = dir.join("hello"); + copy_dir(&sample("hello"), &pkg); + let manifest = pkg.join("plugin.toml"); + let text = std::fs::read_to_string(&manifest).unwrap(); + std::fs::write(&manifest, f(&text)).unwrap(); + pkg +} + +/// `hello` requiring `required`, activated by `insert-date` only. +fn hello_02(text: &str, required: &str) -> String { + text.replace("activation = [\"on-command:*\", \"on-view:greetings\"]", "activation = [\"on-command:insert-date\"]") + .replace("required = [\"editor.read\", \"editor.write\"]", &format!("required = [{required}]")) +} + +/// `hello` with a 0.1 manifest (`openidea-api`, `permissions`, no activation). +fn hello_01(text: &str) -> String { + // A Windows checkout may have CRLF line ends. + text.replace("\r\n", "\n") + .replace("engines.openidea = \"^1.0\"", "openidea-api = \"0.1\"") + .replace("activation = [\"on-command:*\", \"on-view:greetings\"]\n", "") + .replace( + "[capabilities]\nrequired = [\"editor.read\", \"editor.write\"]", + "permissions = [\"project-read\", \"editor-read\", \"editor-write\"]", + ) +} + +struct Fixture { + host: PluginHost, + workspace: Arc, + events: Events, + _tmp: tempfile::TempDir, + plugins_dir: PathBuf, + project: PathBuf, +} + +fn fixture(limits: Limits) -> Fixture { + let tmp = tempfile::tempdir().unwrap(); + let plugins_dir = tmp.path().join("plugins"); + let project = tmp.path().join("project"); + std::fs::create_dir_all(project.join("src")).unwrap(); + std::fs::write(project.join("src/notes.txt"), "one two three\nfour five\n").unwrap(); + std::fs::write(tmp.path().join("secret.txt"), "top secret").unwrap(); + let project = project.canonicalize().unwrap(); + let events: Events = Arc::default(); + let sink = { + let events = events.clone(); + move |client: Option<&str>, e: PluginEvent| events.lock().push((client.map(str::to_owned), e)) + }; + let host = PluginHost::new(plugins_dir.clone(), Arc::new(sink), limits).unwrap(); + let workspace = TestWorkspace::new(&project); + host.set_workspace(Some(workspace.clone())); + host.load_all(); + host.startup_finished(); + Fixture { host, workspace, events, _tmp: tmp, plugins_dir, project } +} + +impl Fixture { + fn inv(&self) -> Invocation { + Invocation { client: Some("main".into()), workspace_root: Some(self.project.clone()), editor: None } + } + + fn install(&self, dir: &Path) -> PluginInfo { + self.host.install_from_dir(dir, &Consent::all()).unwrap() + } + + /// The installed copy of a plugin (its active version's directory). + fn installed(&self, id: &str) -> PathBuf { + self.host.info_of(id).unwrap().path.0 + } + + fn run(&self, plugin: &str, cmd: &str, arg: Option<&str>) -> Result, String> { + self.host.run_command(plugin, cmd, arg, self.inv()).map_err(|e| e.message) + } + + /// Runs a command with `editor` focused. + fn run_in(&self, editor: &EditorContext, plugin: &str, cmd: &str) -> Result, String> { + let inv = Invocation { editor: Some(editor.clone()), ..self.inv() }; + self.host.run_command(plugin, cmd, None, inv).map_err(|e| e.message) + } + + fn status(&self, id: &str) -> PluginStatus { + self.host.info_of(id).unwrap().status + } + + fn take_events(&self) -> Vec<(Option, PluginEvent)> { + std::mem::take(&mut *self.events.lock()) + } + + /// Titles of the `commands` UI contributions of `plugin`. + fn command_titles(&self, plugin: &str) -> Vec { + self.host + .ui_items(COMMANDS) + .into_iter() + .filter(|c| c.plugin_id == plugin) + .map(|c| c.decl["title"].as_str().unwrap().to_owned()) + .collect() + } + + fn theme_kinds(&self, plugin: &str) -> Vec<(String, ThemeKind)> { + self.host + .ui_items("themes") + .into_iter() + .filter(|c| c.plugin_id == plugin) + .map(|c| { + let t: ThemeDef = serde_json::from_value(c.decl).unwrap(); + (t.id, t.kind) + }) + .collect() + } +} + +#[test] +fn hello_plugin_commands() { + let f = fixture(Limits::default()); + let info = f.install(&sample("hello")); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + assert!(f.installed("hello").join("plugin.toml").is_file()); + assert!(f.installed("hello").join("dist/plugin.wasm").is_file()); + assert_eq!(f.command_titles("hello"), ["Hello: Insert Date", "Hello: Word Count of Active File"]); + + // Insert Date: one versioned edit replacing every selection (one undo step). + let editor = f.workspace.open("src/notes.txt", &[(0, 0, 0, 0), (1, 0, 1, 4)]); + let date = f.run_in(&editor, "hello", "insert-date").unwrap().unwrap(); + assert!(date.len() == 10 && date.as_bytes()[4] == b'-' && date.starts_with("20"), "{date}"); + assert_eq!(f.workspace.text("src/notes.txt"), format!("{date}one two three\n{date} five\n")); + assert_eq!(f.status("hello"), PluginStatus::Active, "activated by its command"); + + // Word Count reads the document, unsaved changes included. + let summary = f.run_in(&editor, "hello", "word-count").unwrap().unwrap(); + assert!(summary.starts_with("5 words, 2 lines"), "{summary}"); + assert!(f.take_events().iter().any(|(client, e)| client.as_deref() == Some("main") + && matches!(e, + PluginEvent::Notification { title, level: NotificationLevel::Info, .. } if title == "Word count: notes.txt"))); + + // Without an editor it fails cleanly; guest errors don't disable the plugin. + assert!(f.run("hello", "word-count", None).unwrap_err().contains("no file is open")); + let inv = Invocation { editor: Some(editor.clone()), ..f.inv() }; + let err = f.host.run_command("hello", "nope", None, inv).unwrap_err(); + assert_eq!(err.kind, ErrorKind::NotFound, "{err:?}"); + assert_eq!(f.status("hello"), PluginStatus::Active); + let stats = f.host.info_of("hello").unwrap().stats; + assert_eq!(stats.activations, 1); + // "no file is open" is the plugin failing; an unknown command is not. + assert!(stats.calls >= 4 && stats.errors == 1, "{stats:?}"); +} + +/// Edits name the document version they were computed for. +#[test] +fn edits_are_refused_when_the_document_changed() { + use ide_plugin::{HostApi, Runtime, RuntimeSetup}; + let f = fixture(Limits::default()); + f.install(&sample("hello")); + let editor = f.workspace.open("src/notes.txt", &[(0, 0, 0, 3)]); + let doc = f.workspace.document(&editor.path).unwrap(); + f.workspace.type_text("src/notes.txt", "typed "); + let edit = ide_core::TextEdit { + range: ide_core::Range::new(ide_core::Pos::new(0, 0), ide_core::Pos::new(0, 3)), + new_text: "ONE".into(), + }; + assert_eq!(f.workspace.apply_edits(&editor.path, doc.0, std::slice::from_ref(&edit)), Err(HostError::Stale)); + assert_eq!(f.workspace.text("src/notes.txt"), "typed one two three\nfour five\n"); + let now = f.workspace.document(&editor.path).unwrap().0; + assert_eq!(f.workspace.apply_edits(&editor.path, now, &[edit]), Ok(now + 1)); + assert_eq!(f.workspace.text("src/notes.txt"), "ONEed one two three\nfour five\n"); + let _ = ( + std::any::type_name::(), + std::any::type_name::(), + std::any::type_name::<&dyn HostApi>(), + ); +} + +#[test] +fn read_file_is_confined_to_the_project() { + let f = fixture(Limits::default()); + f.install(&misbehave_pkg()); + assert_eq!(f.run("misbehave", "read", Some("src/notes.txt")).unwrap().unwrap(), "one two three\nfour five\n"); + let abs = f.project.join("src/notes.txt"); + assert!(f.run("misbehave", "read", Some(abs.to_str().unwrap())).is_ok()); + let err = f.run("misbehave", "read", Some("../secret.txt")).unwrap_err(); + assert!(err.contains("outside the project root"), "{err}"); + let err = f.run("misbehave", "read", Some("src/../../secret.txt")).unwrap_err(); + assert!(err.contains("outside the project root"), "{err}"); + assert!(f.run("misbehave", "read", Some("/etc/hosts")).is_err()); + // Without a project there is nothing to read. + let inv = Invocation { client: None, workspace_root: None, editor: None }; + let err = f.host.run_command("misbehave", "read", Some("src/notes.txt"), inv).unwrap_err().message; + assert!(err.contains("no project is open"), "{err}"); + assert_eq!(f.run("misbehave", "root", None).unwrap().unwrap(), f.project.to_string_lossy()); + assert_eq!(f.status("misbehave"), PluginStatus::Active); +} + +/// A missing capability is an error the plugin can handle, not a trap. +#[test] +fn ungranted_capabilities_are_denied_not_trapped() { + let f = fixture(Limits::default()); + f.install(&misbehave_pkg()); + let editor = f.workspace.open("src/notes.txt", &[]); + let inv = Invocation { editor: Some(editor.clone()), ..f.inv() }; + let err = f.host.run_command("misbehave", "insert", None, inv).unwrap_err(); + assert_eq!(err.kind, ErrorKind::PermissionDenied, "{err:?}"); + assert!(err.message.contains("editor.write"), "{err:?}"); + let info = f.host.info_of("misbehave").unwrap(); + assert_eq!((info.status, info.stats.crashes), (PluginStatus::Active, 0), "the instance lives on"); + assert_eq!(info.stats.errors, 0, "a missing grant is not the plugin failing"); + let err = f.host.run_command("misbehave", "cancel", None, f.inv()).unwrap_err(); + assert_eq!(err.kind, ErrorKind::Cancelled, "{err:?}"); + assert_eq!(f.host.info_of("misbehave").unwrap().stats.errors, 0, "nor is the user cancelling"); + assert_eq!(f.workspace.text("src/notes.txt"), "one two three\nfour five\n"); +} + +/// A trap drops the instance, which restarts on next use after a +/// backoff that doubles; only consecutive crashes stop the plugin. +#[test] +fn crashes_restart_with_backoff_until_the_circuit_opens() { + let backoff = Duration::from_millis(150); + let f = fixture(Limits { restart_backoff: backoff, max_failures: 3, ..Limits::default() }); + f.install(&sample("hello")); + f.install(&misbehave_pkg()); + f.take_events(); + + let err = f.run("misbehave", "panic", None).unwrap_err(); + assert!(err.contains("crashed"), "{err}"); + assert!(err.contains("boom"), "stderr panic message is surfaced: {err}"); + let info = f.host.info_of("misbehave").unwrap(); + assert_eq!(info.status, PluginStatus::Inactive); + assert!(info.error.as_deref().is_some_and(|e| e.contains("boom"))); + assert!(!info.contributions.is_empty(), "contributions stay while it can restart"); + let events = f.take_events(); + assert!(events.iter().any(|(client, e)| client.as_deref() == Some("main") + && matches!(e, PluginEvent::Notification { level: NotificationLevel::Warning, title, .. } if title.contains("crashed")))); + + // Backing off, then a fresh instance; a call that returns resets the count. + assert!(f.run("misbehave", "echo", Some("x")).unwrap_err().contains("restarts in")); + std::thread::sleep(backoff + Duration::from_millis(50)); + assert_eq!(f.run("misbehave", "echo", Some("back")).unwrap().as_deref(), Some("back")); + let info = f.host.info_of("misbehave").unwrap(); + assert_eq!((info.status, info.stats.activations, info.error), (PluginStatus::Active, 2, None)); + + // Three in a row: stopped for the session, with growing waits between. + f.take_events(); + let mut waits = Vec::new(); + for _ in 0..3 { + let started = Instant::now(); + let err = loop { + match f.run("misbehave", "panic", None) { + Err(e) if e.contains("restarts in") => std::thread::sleep(Duration::from_millis(20)), + other => break other.unwrap_err(), + } + }; + assert!(err.contains("crashed"), "{err}"); + waits.push(started.elapsed()); + } + assert!(waits[2] >= backoff * 2 && waits[2] > waits[1], "{waits:?}"); + let info = f.host.info_of("misbehave").unwrap(); + assert_eq!(info.status, PluginStatus::Failed); + assert!(info.error.as_deref().is_some_and(|e| e.contains("3 times in a row")), "{:?}", info.error); + assert!(info.enabled, "failure is per session, not persisted"); + assert!(info.contributions.is_empty(), "a failed plugin's contributions are withdrawn"); + let events = f.take_events(); + assert!(events.iter().any(|(_, e)| matches!(e, + PluginEvent::Notification { level: NotificationLevel::Error, title, .. } if title.contains("was disabled")))); + assert_eq!( + events + .iter() + .filter(|(_, e)| matches!(e, PluginEvent::Notification { level: NotificationLevel::Warning, .. })) + .count(), + 1, + "one crash notice per streak" + ); + assert!(f.run("misbehave", "echo", Some("x")).unwrap_err().contains("not running")); + // Other plugins are unaffected. + let editor = f.workspace.open("src/notes.txt", &[(0, 0, 0, 0)]); + assert!(f.run_in(&editor, "hello", "insert-date").is_ok()); + + // Toggling restarts it with a fresh instance. + f.host.set_enabled("misbehave", true).unwrap(); + assert_eq!(f.run("misbehave", "echo", Some("again")).unwrap().as_deref(), Some("again")); + assert_eq!(f.status("misbehave"), PluginStatus::Active); +} + +#[test] +fn fuel_exhaustion_traps() { + let f = + fixture(Limits { fuel: 50_000_000, timeout: Duration::from_secs(30), max_failures: 1, ..Limits::default() }); + f.install(&misbehave_pkg()); + let err = f.run("misbehave", "spin", None).unwrap_err(); + assert!(err.contains("CPU budget"), "{err}"); + assert_eq!(f.status("misbehave"), PluginStatus::Failed, "max_failures 1: the first crash stops it"); +} + +#[test] +fn wall_clock_timeout_traps() { + let f = fixture(Limits { fuel: u64::MAX, timeout: Duration::from_millis(200), ..Limits::default() }); + f.install(&misbehave_pkg()); + let started = std::time::Instant::now(); + let err = f.run("misbehave", "spin", None).unwrap_err(); + assert!(err.contains("timed out after 200ms"), "{err}"); + assert!(started.elapsed() < Duration::from_secs(5)); + assert_eq!(f.host.info_of("misbehave").unwrap().stats.crashes, 1); +} + +#[test] +fn memory_limit_traps() { + let f = fixture(Limits { memory_bytes: 32 << 20, ..Limits::default() }); + f.install(&misbehave_pkg()); + let err = f.run("misbehave", "alloc", None).unwrap_err(); + assert!(err.contains("memory"), "{err}"); + assert_eq!(f.host.info_of("misbehave").unwrap().stats.crashes, 1); +} + +/// A running call can be interrupted from another thread; the +/// instance is rebuilt on next use without counting as a crash. +#[test] +fn running_calls_can_be_cancelled() { + let f = Arc::new(fixture(Limits { fuel: u64::MAX, timeout: Duration::from_secs(30), ..Limits::default() })); + f.install(&misbehave_pkg()); + let spinning = { + let f = f.clone(); + std::thread::spawn(move || f.run("misbehave", "spin", None)) + }; + std::thread::sleep(Duration::from_millis(100)); + let started = Instant::now(); + f.host.cancel("misbehave"); + let err = spinning.join().unwrap().unwrap_err(); + assert!(err.contains("was cancelled"), "{err}"); + assert!(started.elapsed() < Duration::from_secs(1)); + assert_eq!(f.run("misbehave", "echo", Some("x")).unwrap().as_deref(), Some("x"), "no backoff"); + let stats = f.host.info_of("misbehave").unwrap().stats; + assert_eq!((stats.crashes, stats.activations), (0, 2)); +} + +/// `misbehave` contributing a language, so its `syntax-provider` serves it. +fn misbehave_with_language(dir: &Path) -> PathBuf { + let pkg = dir.join("misbehave"); + copy_dir(&misbehave_pkg(), &pkg); + std::fs::write( + pkg.join("plugin.toml"), + "id = \"misbehave\"\nname = \"Misbehave\"\nversion = \"0.0.1\"\nengines.openidea = \"^1.0\"\n\ + wasm = \"dist/plugin.wasm\"\nactivation = [\"on-language:mis\"]\n\ + [[contributes.languages]]\npath = \"mis.toml\"\n", + ) + .unwrap(); + std::fs::write(pkg.join("mis.toml"), "id = \"mis\"\nname = \"Mis\"\nextensions = [\"mis\"]\n").unwrap(); + pkg +} + +/// Edit-path calls stop waiting at the soft deadline (the result is +/// dropped, the instance kept) and are interrupted at the hard one. +#[test] +fn edit_path_calls_have_soft_and_hard_deadlines() { + use ide_core::LanguageId; + let tmp = tempfile::tempdir().unwrap(); + let limits = Limits { + edit_soft: Duration::from_millis(50), + edit_hard: Duration::from_millis(400), + fuel: u64::MAX, + restart_backoff: Duration::ZERO, + ..Limits::default() + }; + let host = + Arc::new(PluginHost::new(tmp.path().join("plugins"), Arc::new(|_: Option<&str>, _| {}), limits).unwrap()); + host.load_all(); + host.startup_finished(); + host.install_from_dir(&misbehave_with_language(tmp.path()), &Consent::all()).unwrap(); + let provider = host.syntax_provider(); + let mis = LanguageId::new("mis"); + + let tokens = provider.highlights(&mis, "fast").unwrap(); + assert_eq!((tokens[0].start, tokens[0].end, tokens[0].kind.as_str()), (0, 4, "keyword")); + + // Slower than the soft deadline: dropped (however late this thread gets + // to look), but the instance lives on. + assert!(provider.highlights(&mis, "sleep:150").is_none()); + std::thread::sleep(Duration::from_millis(150)); + assert!(provider.highlights(&mis, "fast").is_some()); + let info = host.info_of("misbehave").unwrap(); + assert_eq!((info.stats.slow_calls, info.stats.crashes, info.stats.activations), (1, 0, 1)); + + // Past the hard deadline: interrupted; the next call gets a new instance. + assert!(provider.highlights(&mis, "spin").is_none()); + std::thread::sleep(Duration::from_millis(450)); + host.tick(); + let info = host.info_of("misbehave").unwrap(); + assert_eq!(info.stats.crashes, 1, "{:?}", info.error); + assert!(info.error.as_deref().is_some_and(|e| e.contains("timed out after 400ms")), "{:?}", info.error); + assert!(provider.highlights(&mis, "fast").is_some()); + assert_eq!(host.info_of("misbehave").unwrap().stats.activations, 2); +} + +/// Editor providers of several plugins are asked at the same time: the wait +/// is the slowest plugin's, not the sum, so each has the whole budget. +#[test] +fn providers_of_several_plugins_run_concurrently() { + let tmp = tempfile::tempdir().unwrap(); + let limits = Limits { + edit_soft: Duration::from_millis(300), + edit_hard: Duration::from_secs(2), + fuel: u64::MAX, + ..Limits::default() + }; + let host = + Arc::new(PluginHost::new(tmp.path().join("plugins"), Arc::new(|_: Option<&str>, _| {}), limits).unwrap()); + host.load_all(); + host.startup_finished(); + for id in ["slow-a", "slow-b"] { + let pkg = tmp.path().join(id); + copy_dir(&misbehave_pkg(), &pkg); + std::fs::write( + pkg.join("plugin.toml"), + format!( + "id = \"{id}\"\nname = \"{id}\"\nversion = \"0.0.1\"\nengines.openidea = \"^1.0\"\n\ + wasm = \"dist/plugin.wasm\"\nactivation = [\"on-language:text\"]\n\ + [[contributes.providers]]\nkinds = [\"completion\"]\nlanguages = [\"text\"]\n" + ), + ) + .unwrap(); + host.install_from_dir(&pkg, &Consent::all()).unwrap(); + } + let doc = |text: &str| ide_plugin::ProviderDocument { + path: "/p/a.txt".into(), + language: "text".into(), + version: 1, + text: text.into(), + }; + let at = ide_core::Pos::new(0, 0); + // Activation is not what is measured. + assert_eq!(host.provide_completion(&doc("fast"), at, None).len(), 2); + + let started = Instant::now(); + let items = host.provide_completion(&doc("sleep:200"), at, None); + let elapsed = started.elapsed(); + let mut from: Vec<&str> = items.iter().map(|(p, _)| p.as_str()).collect(); + from.sort(); + assert_eq!(from, ["slow-a", "slow-b"], "both within the budget"); + assert!(elapsed < Duration::from_millis(350), "one after the other would take 400ms: {elapsed:?}"); + assert_eq!(host.info_of("slow-b").unwrap().stats.slow_calls, 0); +} + +/// Idle instances are reclaimed; the plugin activates again on its +/// next use, and `on-schedule` activations don't keep it alive. +#[test] +fn idle_instances_are_reclaimed_and_schedules_reactivate() { + let tmp = tempfile::tempdir().unwrap(); + let f = fixture(Limits { idle_timeout: Some(Duration::from_millis(100)), ..Limits::default() }); + f.install(&misbehave_pkg()); + assert_eq!(f.run("misbehave", "echo", Some("x")).unwrap().as_deref(), Some("x")); + assert_eq!(f.host.instances(), 1); + f.host.tick(); + assert_eq!(f.host.instances(), 1, "not idle yet"); + std::thread::sleep(Duration::from_millis(150)); + f.host.tick(); + assert_eq!(f.host.instances(), 0); + let info = f.host.info_of("misbehave").unwrap(); + assert_eq!((info.status, info.stats.reclaims), (PluginStatus::Inactive, 1)); + assert_eq!(f.command_titles("misbehave").len(), 8, "contributions stay"); + assert_eq!(f.run("misbehave", "echo", Some("y")).unwrap().as_deref(), Some("y")); + assert_eq!(f.host.info_of("misbehave").unwrap().stats.activations, 2); + + let pkg = hello_variant(tmp.path(), |t| { + hello_02(t, "\"editor.read\"") + .replace("activation = [\"on-command:insert-date\"]", "activation = [\"on-schedule:60\"]") + }); + f.install(&pkg); + assert_eq!(f.status("hello"), PluginStatus::Inactive); + let now = Instant::now(); + f.host.tick_at(now); + f.host.tick_at(now + Duration::from_secs(59)); + assert_eq!(f.status("hello"), PluginStatus::Inactive, "not due yet"); + f.host.tick_at(now + Duration::from_secs(61)); + assert!(f.host.wait_events(Duration::from_secs(10))); + assert_eq!(f.status("hello"), PluginStatus::Active, "due"); + std::thread::sleep(Duration::from_millis(150)); + f.host.tick(); + assert_eq!(f.status("hello"), PluginStatus::Inactive, "reclaimed again"); +} + +#[test] +fn contribution_only_plugins() { + let f = fixture(Limits::default()); + let theme = f.install(&theme_template()); + assert_eq!(theme.status, PluginStatus::Static); + assert!(!theme.has_code); + assert_eq!(f.theme_kinds("openidea.harbor-night")[0].0, "harbor-night"); + let lang = f.install(&sample("language-toy")); + assert_eq!(lang.status, PluginStatus::Static); + assert_eq!(f.host.languages()[0].id.as_str(), "toy"); + assert_eq!(f.host.languages()[0].block_comment, Some(("(*".into(), "*)".into()))); + assert!(f.run("language-toy", "x", None).unwrap_err().contains("no code")); + + f.take_events(); + let active = f.host.set_theme(Some(("openidea.harbor-night", "harbor-night"))).unwrap().unwrap(); + assert_eq!(active.theme.tokens["--bg-app"], "#14171c"); + assert_eq!(active.theme.tokens["--syn-string"], "#9ccc7a"); + assert!(f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::ThemeChanged { theme: Some(_) }))); + assert_eq!(f.host.list(None).active_theme, Some(active)); + + // Disabling the plugin withdraws its theme and language. + f.host.set_enabled("openidea.harbor-night", false).unwrap(); + assert!(f.host.active_theme().is_none()); + assert!(f.take_events().iter().any(|(_, e)| *e == PluginEvent::ThemeChanged { theme: None })); + f.host.set_enabled("language-toy", false).unwrap(); + assert!(f.host.languages().is_empty()); + assert_eq!(f.status("language-toy"), PluginStatus::Disabled); +} + +#[test] +fn theme_template_installs_with_its_editor_scheme() { + let f = fixture(Limits::default()); + let info = f.install(&theme_template()); + assert_eq!(info.status, PluginStatus::Static); + assert_eq!(f.theme_kinds("openidea.harbor-night"), [("harbor-night".to_owned(), ThemeKind::Dark)]); + // The scheme file is copied with the package and merged over the UI tokens. + assert!(f.installed("openidea.harbor-night").join("themes/harbor-night.scheme.json").is_file()); + let active = f.host.set_theme(Some(("openidea.harbor-night", "harbor-night"))).unwrap().unwrap(); + let tokens = &active.theme.tokens; + assert!( + tokens.contains_key("--bg-app") && tokens.contains_key("--syn-keyword") && tokens.contains_key("--ansi-red") + ); + assert!(tokens.len() > 150); +} + +#[test] +fn theme_packages_install_with_their_licence() { + let f = fixture(Limits::default()); + let dir = tempfile::tempdir().unwrap(); + write_theme_pair(dir.path()); + let info = f.install(dir.path()); + assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error); + let installed = f.installed("theme-pair"); + assert!(std::fs::read_to_string(installed.join("LICENSE")).unwrap().contains("MIT License")); + assert!(installed.join("NOTICE").is_file()); + for (theme, kind) in [("day", ThemeKind::Light), ("night", ThemeKind::Dark)] { + let active = f.host.set_theme(Some(("theme-pair", theme))).unwrap().unwrap(); + assert_eq!(active.theme.kind, kind); + } +} + +#[test] +fn theme_frame_follows_the_selection() { + let f = fixture(Limits::default()); + let dir = tempfile::tempdir().unwrap(); + write_theme_pair(dir.path()); + f.install(dir.path()); + // Nothing to attach it to without a selected theme. + f.host.set_theme_frame(Some("#111111")).unwrap(); + assert_eq!(f.host.startup_frame(), None); + f.host.set_theme(Some(("theme-pair", "night"))).unwrap(); + assert!(f.host.set_theme_frame(Some("hsl(220, 13%, 15%)")).is_err()); + f.host.set_theme_frame(Some("#111111")).unwrap(); + assert_eq!(f.host.startup_frame().as_deref(), Some("#111111")); + f.host.set_enabled("theme-pair", false).unwrap(); + assert_eq!(f.host.startup_frame(), None); + f.host.set_enabled("theme-pair", true).unwrap(); + assert_eq!(f.host.startup_frame().as_deref(), Some("#111111")); + // A new selection drops the old theme's colour until the UI reports the new one. + f.host.set_theme(Some(("theme-pair", "day"))).unwrap(); + assert_eq!(f.host.startup_frame(), None); + f.host.set_theme_frame(Some("#eeeeee")).unwrap(); + f.host.set_theme(None).unwrap(); + assert_eq!(f.host.startup_frame(), None); +} + +#[test] +fn theme_with_broken_editor_scheme_is_rejected() { + let f = fixture(Limits::default()); + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("t")).unwrap(); + std::fs::write( + dir.path().join("plugin.toml"), + "id = \"bad-scheme\"\nname = \"B\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\n\ + [[contributes.themes]]\npath = \"t/a.json\"\neditor-scheme = \"t/a.scheme.json\"\n", + ) + .unwrap(); + std::fs::write(dir.path().join("t/a.json"), r##"{"id":"a","name":"A","kind":"light","tokens":{}}"##).unwrap(); + std::fs::write(dir.path().join("t/a.scheme.json"), "{\n \"tokens\": { \"--caret\": \"url(x)\" }\n}").unwrap(); + // Validation happens before anything is copied. + let err = f.host.install_from_dir(dir.path(), &Consent::all()).unwrap_err().message; + assert!(err.contains("a.scheme.json"), "{err}"); + assert!(!f.plugins_dir.join("bad-scheme").exists()); + // Already on disk (copied by hand): listed as failed. + copy_dir(dir.path(), &f.plugins_dir.join("bad-scheme")); + f.host.load_all(); + let info = f.host.info_of("bad-scheme").unwrap(); + assert_eq!(info.status, PluginStatus::Failed); + assert!(info.error.unwrap_or_default().contains("a.scheme.json")); +} + +#[test] +fn state_persists_across_restarts() { + let f = fixture(Limits::default()); + f.install(&sample("hello")); + f.install(&theme_template()); + f.host.set_enabled("hello", false).unwrap(); + f.host.set_theme(Some(("openidea.harbor-night", "harbor-night"))).unwrap(); + f.host.set_theme_frame(Some("#1f252e")).unwrap(); + + let again = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); + // Known before the plugins are loaded: new windows open in the theme's frame colour. + assert_eq!(again.startup_frame().as_deref(), Some("#1f252e")); + assert!(!again.wait_initial_load(Duration::from_millis(1))); + again.load_all(); + assert!(again.wait_initial_load(Duration::ZERO)); + let list = again.list(None); + let hello = list.plugins.iter().find(|p| p.id == "hello").unwrap(); + assert!(!hello.enabled); + assert_eq!(hello.status, PluginStatus::Disabled); + assert_eq!(list.active_theme.unwrap().theme.id, "harbor-night"); + assert!( + again + .run_command("hello", "insert-date", None, Invocation::default()) + .unwrap_err() + .message + .contains("disabled") + ); +} + +#[test] +fn startup_loads_without_instantiating_wasm() { + let f = fixture(Limits::default()); + f.install(&sample("hello")); + let again = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); + again.load_all(); + let hello = again.info_of("hello").unwrap(); + assert_eq!(hello.status, PluginStatus::Inactive, "no instance before start-up finished"); + assert_eq!(hello.stats.activations, 0); + assert_eq!(again.ui_items(COMMANDS).len(), 2, "commands are shown without running code"); + again.startup_finished(); + assert_eq!(again.instances(), 0, "hello waits for its commands"); + + // `on-startup-finished` plugins are activated then, not before. + let tmp = tempfile::tempdir().unwrap(); + let eager = hello_variant(tmp.path(), |t| t.replace("on-command:*", "on-startup-finished")); + f.install(&eager); + let again = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); + again.load_all(); + assert_eq!(again.instances(), 0); + again.startup_finished(); + assert_eq!(again.info_of("hello").unwrap().status, PluginStatus::Active); +} + +#[test] +fn lazy_activation_on_command() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let pkg = hello_variant(tmp.path(), |t| hello_02(t, "\"project.read\", \"editor.read\", \"editor.write\"")); + let info = f.install(&pkg); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + assert_eq!(info.activation, ["on-command:insert-date"]); + assert_eq!(f.command_titles("hello").len(), 2); + let editor = f.workspace.open("src/notes.txt", &[(0, 0, 0, 0)]); + assert!(f.run_in(&editor, "hello", "insert-date").unwrap().is_some()); + assert_eq!(f.status("hello"), PluginStatus::Active); +} + +#[test] +fn project_plugins_need_consent_even_in_trusted_projects() { + let f = fixture(Limits::default()); + f.host.set_project_policy(Arc::new(|_| true)); + let dev = f.project.join(DEV_PLUGINS_DIR).join("toy"); + copy_dir(&sample("language-toy"), &dev); + f.host.sync_project(&f.project); + let mine = f.host.list(Some(&f.project)); + assert_eq!(mine.plugins.len(), 1); + assert_eq!(mine.plugins[0].source, PluginSource::Dev); + assert_eq!(mine.plugins[0].status, PluginStatus::NeedsConsent); + assert!(f.host.languages().is_empty(), "nothing takes effect before consent"); + assert!(f.host.list(None).plugins.is_empty(), "project plugins only show for their project"); + + f.host.grant("language-toy", &Consent::default()).unwrap(); + assert_eq!(f.status("language-toy"), PluginStatus::Static); + assert_eq!(f.host.languages().len(), 1); + assert!(f.host.uninstall("language-toy").is_err()); + assert!(f.host.install_from_dir(&sample("language-toy"), &Consent::all()).is_err(), "id clash with a dev plugin"); + + // Edit + reload picks up changes; the grant is by path, so no new prompt. + let manifest = dev.join("plugin.toml"); + let src = std::fs::read_to_string(&manifest).unwrap().replace("Toy Language", "Toy Language (dev)"); + std::fs::write(&manifest, src).unwrap(); + let info = f.host.reload("language-toy").unwrap(); + assert_eq!(info.name, "Toy Language (dev)"); + assert_eq!(info.status, PluginStatus::Static); + + std::fs::remove_dir_all(&dev).unwrap(); + f.host.sync_project(&f.project); + assert!(f.host.list(Some(&f.project)).plugins.is_empty()); +} + +#[test] +fn untrusted_or_unconfirmed_project_plugins_never_run() { + let f = fixture(Limits::default()); + // Its commands are registered by `activate` only. + let dev = f.project.join(DEV_PLUGINS_DIR).join("misbehave"); + copy_dir(&misbehave_pkg(), &dev); + let trusted = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let policy = trusted.clone(); + f.host.set_project_policy(Arc::new(move |_| policy.load(std::sync::atomic::Ordering::Acquire))); + f.host.sync_project(&f.project); + assert!(f.host.list(Some(&f.project)).plugins.is_empty()); + assert!(f.host.info_of("misbehave").is_err()); + + // Trusted but not confirmed: listed, nothing runs, activation registers nothing. + trusted.store(true, std::sync::atomic::Ordering::Release); + f.host.sync_project(&f.project); + let info = f.host.info_of("misbehave").unwrap(); + assert_eq!(info.status, PluginStatus::NeedsConsent); + assert!(f.command_titles("misbehave").is_empty(), "unconfirmed plugin registered its activation witness"); + assert!(f.run("misbehave", "echo", None).unwrap_err().contains("permission")); + + // Positive control: after consent, activation itself registers the commands. + let info = f.host.grant("misbehave", &Consent::default()).unwrap(); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + assert_eq!(f.run("misbehave", "echo", Some("x")).unwrap().as_deref(), Some("x")); + assert!(f.command_titles("misbehave").iter().any(|t| t == "echo")); + + trusted.store(false, std::sync::atomic::Ordering::Release); + assert!(f.host.reload("misbehave").is_err()); + assert!(f.host.set_enabled("misbehave", true).is_err()); + assert!(f.run("misbehave", "echo", None).is_err()); + f.host.sync_project(&f.project); + assert!(f.host.list(Some(&f.project)).plugins.is_empty()); +} + +#[test] +fn new_capabilities_require_consent_again() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let v1 = hello_variant(&tmp.path().join("v1"), |t| hello_02(t, "\"project.read\"")); + let info = f.install(&v1); + assert_eq!(info.status, PluginStatus::Inactive); + assert!(info.capabilities.iter().all(|c| c.granted)); + + // Same capabilities, new version: accepted silently. + let v2 = hello_variant(&tmp.path().join("v2"), |t| { + hello_02(t, "\"project.read\"").replace("version = \"0.3.0\"", "version = \"0.3.1\"") + }); + f.host.load_all(); + std::fs::remove_dir_all(f.plugins_dir.join("hello")).unwrap(); + copy_dir(&v2, &f.plugins_dir.join("hello")); + let again = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); + again.load_all(); + assert_eq!(again.info_of("hello").unwrap().status, PluginStatus::Inactive); + drop(again); + + // A new required capability: waits for consent, nothing contributed. + let v3 = hello_variant(&tmp.path().join("v3"), |t| { + hello_02(t, "\"project.read\", \"editor.write\"").replace("version = \"0.3.0\"", "version = \"0.4.0\"") + }); + std::fs::remove_dir_all(f.plugins_dir.join("hello")).unwrap(); + copy_dir(&v3, &f.plugins_dir.join("hello")); + let again = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); + again.load_all(); + let info = again.info_of("hello").unwrap(); + assert_eq!(info.status, PluginStatus::NeedsConsent); + let write = info.capabilities.iter().find(|c| c.id == "editor.write").unwrap(); + assert!(!write.granted); + assert!(again.ui_items(COMMANDS).is_empty()); + again.grant("hello", &Consent::default()).unwrap(); + assert_eq!(again.info_of("hello").unwrap().status, PluginStatus::Inactive); + + // Revoking a required capability stops it again. + let info = again.set_capability("hello", "editor.write", false).unwrap(); + assert_eq!(info.status, PluginStatus::NeedsConsent); +} + +#[test] +fn migrated_plugins_get_low_risk_capabilities_and_ask_on_first_use() { + let tmp = tempfile::tempdir().unwrap(); + let plugins_dir = tmp.path().join("plugins"); + // Installed by a version without the grant ledger (a 0.1 manifest). + copy_dir(&sample("hello"), &plugins_dir.join("hello")); + let manifest = plugins_dir.join("hello/plugin.toml"); + std::fs::write(&manifest, hello_01(&std::fs::read_to_string(&manifest).unwrap())).unwrap(); + let events: Events = Arc::default(); + let sink = { + let events = events.clone(); + move |client: Option<&str>, e: PluginEvent| events.lock().push((client.map(str::to_owned), e)) + }; + let host = PluginHost::new(plugins_dir.clone(), Arc::new(sink), Limits::default()).unwrap(); + host.load_all(); + let info = host.info_of("hello").unwrap(); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + let granted: Vec<_> = info.capabilities.iter().filter(|c| c.granted).map(|c| c.id.as_str()).collect(); + assert_eq!(granted, ["project.read", "editor.read"]); + let inv = Invocation { client: Some("w".into()), ..Invocation::default() }; + let err = host.run_command("hello", "insert-date", None, inv.clone()).unwrap_err(); + assert_eq!(err.kind, ide_core::error::ErrorKind::PermissionDenied); + assert!(events.lock().iter().any(|(c, e)| c.as_deref() == Some("w") + && matches!(e, PluginEvent::ConsentRequested { capabilities, .. } if capabilities[0].id == "editor.write"))); + host.grant("hello", &Consent::default()).unwrap(); + // Runs now (and fails only for want of an editor). + let err = host.run_command("hello", "insert-date", None, inv).unwrap_err(); + assert!(err.message.contains("no file is open"), "{err:?}"); +} + +#[cfg(unix)] +#[test] +fn replaced_binaries_are_refused() { + use std::os::unix::fs::PermissionsExt; + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let bin = tmp.path().join("bin"); + std::fs::create_dir(&bin).unwrap(); + std::fs::write(bin.join("toylsp"), "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(bin.join("toylsp"), std::fs::Permissions::from_mode(0o755)).unwrap(); + let path = bin.clone(); + f.host.set_program_path(Arc::new(move || Some(path.clone().into_os_string()))); + + let pkg = tmp.path().join("pkg"); + copy_dir(&sample("language-toy"), &pkg); + let lang = pkg.join("languages/toy.toml"); + let text = std::fs::read_to_string(&lang).unwrap(); + std::fs::write(&lang, format!("{text}\n[[language-servers]]\nname = \"toylsp\"\ncommand = \"toylsp\"\n")).unwrap(); + + let preview = f.host.preview_install(&pkg).unwrap(); + let lsp = preview.capabilities.iter().find(|c| c.id == "process:toylsp").unwrap(); + assert_eq!(lsp.risk, ide_extension::Risk::High); + assert!(lsp.optional, "declaration-derived capabilities can be refused"); + + // Refused: the language still works. + f.host.install_from_dir(&pkg, &Consent::default()).unwrap(); + assert_eq!(f.host.languages().len(), 1); + assert!(f.host.program_for("language-toy", "toylsp").is_err()); + + // Accepted: pinned to the resolved file. + f.host.set_capability("language-toy", "process:toylsp", true).unwrap(); + let resolved = f.host.program_for("language-toy", "toylsp").unwrap(); + assert!(resolved.ends_with("toylsp")); + std::fs::write(bin.join("toylsp"), "#!/bin/sh\necho replaced\n").unwrap(); + let err = f.host.program_for("language-toy", "toylsp").unwrap_err(); + assert_eq!(err.kind, ide_core::error::ErrorKind::PermissionDenied); + assert!(err.message.contains("confirm"), "{}", err.message); +} + +/// A declaration-only language plugin reaches detection and LSP of +/// every project; its server starts only while `process:` is granted, from +/// the approved file. +#[cfg(unix)] +#[test] +fn plugin_languages_join_the_registry_and_start_only_granted_servers() { + use ide_core::LanguageId; + use ide_language::LanguageRegistry; + use std::os::unix::fs::PermissionsExt; + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let bin = tmp.path().join("bin"); + std::fs::create_dir(&bin).unwrap(); + std::fs::write(bin.join("toylsp"), "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(bin.join("toylsp"), std::fs::Permissions::from_mode(0o755)).unwrap(); + let path = bin.clone(); + f.host.set_program_path(Arc::new(move || Some(path.clone().into_os_string()))); + + let registry = LanguageRegistry::load(None).unwrap(); + registry.attach_plugins(f.host.language_store().clone()); + let project = registry.fork(); + let toy = LanguageId::new("toy"); + assert_eq!(project.detect(Path::new("/p/a.toy"), None), LanguageId::plain_text()); + + let pkg = tmp.path().join("pkg"); + copy_dir(&sample("language-toy"), &pkg); + let lang = pkg.join("languages/toy.toml"); + let text = std::fs::read_to_string(&lang).unwrap(); + std::fs::write(&lang, format!("{text}\n[[language-servers]]\nname = \"toylsp\"\ncommand = \"toylsp\"\n")).unwrap(); + + // Refused: detected and listed, no server. + f.host.install_from_dir(&pkg, &Consent::default()).unwrap(); + assert_eq!(project.detect(Path::new("/p/a.toy"), None), toy); + assert!(registry.all().iter().any(|l| l.id == toy), "the UI language list includes it"); + assert!(project.get(&toy).unwrap().language_servers.is_empty()); + + // Granted: the server is pinned to the approved file. + f.host.set_capability("language-toy", "process:toylsp", true).unwrap(); + let server = project.get(&toy).unwrap().language_servers[0].clone(); + let pin = server.pinned.expect("pinned"); + assert_eq!(pin.verify().unwrap(), dunce::canonicalize(bin.join("toylsp")).unwrap()); + // Replaced afterwards: refused when it would start. + std::fs::write(bin.join("toylsp"), "#!/bin/sh\necho replaced\n").unwrap(); + assert!(pin.verify().unwrap_err().contains("changed since it was approved")); + + // Revoked, then disabled. + f.host.set_capability("language-toy", "process:toylsp", false).unwrap(); + assert!(project.get(&toy).unwrap().language_servers.is_empty()); + f.host.set_enabled("language-toy", false).unwrap(); + assert_eq!(project.detect(Path::new("/p/a.toy"), None), LanguageId::plain_text()); +} + +/// A plugin provides the syntax of a language the IDE has no grammar +/// for (the official Solidity plugin, built with the SDK), activated on first use. +#[test] +fn plugin_syntax_for_languages_without_a_grammar() { + use ide_core::{DocId, LanguageId, SymbolKind}; + use ide_language::{Syntax, SyntaxCache, SyntaxHighlightKind}; + let tmp = tempfile::tempdir().unwrap(); + let host = Arc::new( + PluginHost::new(tmp.path().join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(), + ); + host.load_all(); + host.startup_finished(); + let info = host.install_from_dir(&repo().join("plugins/official/solidity"), &Consent::default()).unwrap(); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + assert!(info.capabilities.iter().all(|c| c.optional && !c.granted), "language servers were refused"); + + let provider = host.syntax_provider(); + let sol = LanguageId::new("solidity"); + let text = "// c\ncontract A {\n uint256 public x;\n function f() public {}\n}\n"; + assert!(provider.highlights(&LanguageId::new("rust"), text).is_none(), "only its own languages"); + let tokens = provider.highlights(&sol, text).unwrap(); + let kind_at = + |s: &str| tokens.iter().find(|t| &text[t.start as usize..t.end as usize] == s).map(|t| t.kind.as_str()); + assert_eq!(kind_at("contract"), Some("keyword")); + assert_eq!(kind_at("uint256"), Some("type")); + assert_eq!(kind_at("// c"), Some("comment")); + assert_eq!(host.info_of("openidea.solidity").unwrap().status, PluginStatus::Active, "activated on first use"); + + // As the editor gets it: through a project's syntax cache. + ide_language::set_external_syntax(Some(provider.clone())); + let cache = SyntaxCache::new(Arc::new(Syntax::new())); + let outline = cache.outline(DocId(1), &sol, 1, text); + assert_eq!(outline.len(), 1); + assert_eq!((outline[0].name.as_str(), outline[0].kind), ("A", SymbolKind::Class)); + let members: Vec<_> = outline[0].children.iter().map(|c| (c.name.as_str(), c.kind)).collect(); + assert_eq!(members, [("x", SymbolKind::Field), ("f", SymbolKind::Method)]); + assert_eq!(outline[0].selection_range.start.line, 1); + let folds = cache.folding(DocId(1), &sol, 1, text); + assert!(folds.iter().any(|f| f.start_line == 1 && f.end_line == 4)); + let highlights = cache.highlights(DocId(1), &sol, 1, text); + let keyword = SyntaxHighlightKind::ALL.iter().position(|k| *k == SyntaxHighlightKind::Keyword).unwrap() as u32; + assert!(highlights.data.chunks(3).any(|t| t == [5, 13, keyword]), "UTF-16 offsets of `contract`"); + ide_language::set_external_syntax(None); +} + +/// Plugins add run configurations to `ide-run`'s detection; the +/// command runs only while granted, from the approved file. +#[cfg(unix)] +#[test] +fn run_detectors_offer_granted_commands_in_marked_projects() { + use std::os::unix::fs::PermissionsExt; + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let bin = tmp.path().join("bin"); + std::fs::create_dir(&bin).unwrap(); + std::fs::write(bin.join("forge"), "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(bin.join("forge"), std::fs::Permissions::from_mode(0o755)).unwrap(); + let path = bin.clone(); + f.host.set_program_path(Arc::new(move || Some(path.clone().into_os_string()))); + + let pkg = tmp.path().join("pkg"); + std::fs::create_dir(&pkg).unwrap(); + std::fs::write( + pkg.join("plugin.toml"), + "id = \"acme.forge\"\nname = \"Forge\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\n\ + [[contributes.runDetectors]]\nid = \"test\"\nname = \"forge test\"\nfiles = [\"foundry.toml\"]\n\ + command = \"forge\"\nargs = [\"test\"]\ntest = true\n", + ) + .unwrap(); + let preview = f.host.preview_install(&pkg).unwrap(); + assert!(preview.capabilities.iter().any(|c| c.id == "process:forge" && c.optional)); + f.host.install_from_dir(&pkg, &Consent::default()).unwrap(); + + let detection = f.host.run_detection(); + let project = tmp.path().join("chain"); + std::fs::create_dir(&project).unwrap(); + assert!(detection.detect(&project).is_empty(), "no marker"); + std::fs::write(project.join("foundry.toml"), "").unwrap(); + assert!(detection.detect(&project).is_empty(), "not granted"); + + f.host.set_capability("acme.forge", "process:forge", true).unwrap(); + let configs = detection.detect(&project); + assert_eq!(configs.len(), 1); + let config = &configs[0]; + assert_eq!( + (config.id.as_str(), config.name.as_str(), config.is_test), + ("plugin:acme.forge:test", "forge test", true) + ); + assert_eq!(detection.launch(config).unwrap(), dunce::canonicalize(bin.join("forge")).unwrap()); + + std::fs::write(bin.join("forge"), "#!/bin/sh\necho swapped\n").unwrap(); + assert!(detection.launch(config).unwrap_err().contains("changed since it was approved")); + f.host.set_enabled("acme.forge", false).unwrap(); + assert!(detection.detect(&project).is_empty()); + assert!(detection.launch(config).unwrap_err().contains("no longer enabled")); +} + +/// Compiled components are cached across runs (keyed by module and +/// engine), so a cold activation only deserializes. +#[test] +fn precompiled_components_make_cold_activation_cheap() { + let f = fixture(Limits::default()); + f.install(&sample("hello")); + let cache = f.plugins_dir.join(".cache/components"); + let cached = || std::fs::read_dir(&cache).map(|d| d.count()).unwrap_or(0); + assert_eq!(cached(), 1, "install validation compiled it once, into the cache"); + + // Another run of the IDE: activation deserializes. + let again = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); + again.load_all(); + let started = Instant::now(); + let _ = again.run_command("hello", "word-count", None, Invocation::default()); + let cold = started.elapsed(); + let stats = again.info_of("hello").unwrap().stats; + assert_eq!(stats.activations, 1); + eprintln!("cold activation with a precompiled component: {:.1} ms (wall {cold:?})", stats.activation_ms); + assert!(stats.activation_ms < 250.0, "{} ms", stats.activation_ms); + + // A stale entry (other engine or uninstalled plugin) is pruned by the warm-up. + std::fs::write(cache.join("0000-stale.cwasm"), b"junk").unwrap(); + again.warm_component_cache(); + assert_eq!(cached(), 1); + // A corrupt entry is discarded and recompiled. The host that loaded it goes + // first: its component maps the file (which Windows won't let anyone replace). + drop(again); + for e in std::fs::read_dir(&cache).unwrap().flatten() { + std::fs::write(e.path(), b"junk").unwrap(); + } + let third = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); + third.load_all(); + assert!( + third.run_command("hello", "word-count", None, Invocation::default()).is_err(), + "no active file, but it runs" + ); + assert_eq!(third.info_of("hello").unwrap().status, PluginStatus::Active); +} + +#[test] +fn install_validation_atomic_replace_and_uninstall() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + + // Missing component file. + let pkg = tmp.path().join("broken"); + std::fs::create_dir_all(&pkg).unwrap(); + std::fs::write( + pkg.join("plugin.toml"), + "id = \"b\"\nname = \"B\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\nwasm = \"x.wasm\"", + ) + .unwrap(); + let install = |p: &Path| f.host.install_from_dir(p, &Consent::all()); + assert!(install(&pkg).unwrap_err().message.contains("missing")); + // Not a component. + std::fs::write(pkg.join("x.wasm"), b"\0asm garbage").unwrap(); + assert!(install(&pkg).unwrap_err().message.contains("not a valid plugin component")); + // Bad manifest. + std::fs::write(pkg.join("plugin.toml"), "id = \"B!\"").unwrap(); + assert!(install(&pkg).is_err()); + assert!(f.host.list(None).plugins.is_empty(), "failed installs leave nothing behind"); + + // A broken package already in the plugins dir shows up as failed. + std::fs::create_dir_all(f.plugins_dir.join("junk")).unwrap(); + std::fs::write(f.plugins_dir.join("junk/plugin.toml"), "garbage = ").unwrap(); + f.host.load_all(); + let junk = &f.host.list(None).plugins[0]; + assert_eq!(junk.status, PluginStatus::Failed); + assert!(junk.error.is_some()); + + // Reinstall replaces; a failing reinstall keeps the installed version. + f.install(&sample("hello")); + f.install(&sample("hello")); + assert_eq!(f.status("hello"), PluginStatus::Inactive); + let bad = hello_variant(tmp.path(), |t| t.replace("version = \"0.3.0\"", "version = \"0.9.0\"")); + std::fs::write(bad.join("dist/plugin.wasm"), b"not wasm").unwrap(); + assert!(install(&bad).is_err()); + assert_eq!(f.host.info_of("hello").unwrap().version, "0.3.0"); + assert!(f.installed("hello").join("dist/plugin.wasm").is_file()); + assert!(f.installed("hello").join(".package-hash").is_file()); + let leftovers: Vec<_> = std::fs::read_dir(&f.plugins_dir) + .unwrap() + .flatten() + .filter(|e| e.file_name().to_string_lossy().starts_with(".staging")) + .collect(); + assert!(leftovers.is_empty()); + + f.host.uninstall("hello").unwrap(); + assert!(!f.plugins_dir.join("hello").exists()); + assert!(f.host.info_of("hello").is_err()); +} + +#[test] +fn unknown_contribution_points_are_skipped_with_a_warning() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let pkg = tmp.path().join("future"); + copy_dir(&sample("language-toy"), &pkg); + let manifest = pkg.join("plugin.toml"); + let text = std::fs::read_to_string(&manifest).unwrap(); + std::fs::write(&manifest, format!("{text}\n[[contributes.holograms]]\nshape = \"cube\"\n")).unwrap(); + let info = f.install(&pkg); + assert_eq!(info.status, PluginStatus::Static); + assert!(info.warnings.iter().any(|w| w.contains("holograms"))); + assert_eq!(f.host.languages().len(), 1); +} + +#[test] +fn icon_themes_are_a_contribution_type_like_any_other() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let pkg = tmp.path().join("icons"); + std::fs::create_dir_all(pkg.join("svg")).unwrap(); + std::fs::write(pkg.join("svg/rust.svg"), r#""#).unwrap(); + std::fs::write(pkg.join("svg/file.svg"), r#""#).unwrap(); + std::fs::write( + pkg.join("theme.json"), + r#"{"iconDefinitions":{"rust":"svg/rust.svg","file":"svg/file.svg"},"file":"file","fileExtensions":{"rs":"rust"}}"#, + ) + .unwrap(); + std::fs::write( + pkg.join("plugin.toml"), + "id = \"acme.icons\"\nname = \"Icons\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\n\ + [[contributes.iconThemes]]\nid = \"acme\"\nlabel = \"Acme Icons\"\npath = \"theme.json\"\n", + ) + .unwrap(); + let info = f.install(&pkg); + assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error); + assert!(f.installed("acme.icons").join("svg/rust.svg").is_file(), "referenced files are installed"); + let items = f.host.ui_items("iconThemes"); + assert_eq!(items.len(), 1); + assert_eq!(items[0].decl["label"], "Acme Icons"); + let svgs = f.host.assets("acme.icons", &icon_theme_svg_prefix("acme")).unwrap(); + assert_eq!(svgs.len(), 2); + let map = f.host.assets("acme.icons", &icon_theme_map_asset("acme")).unwrap(); + assert!(map[0].1.contains("\"rs\":\"rust\"")); + f.host.set_enabled("acme.icons", false).unwrap(); + assert!(f.host.ui_items("iconThemes").is_empty()); + assert!(f.host.assets("acme.icons", "").is_err()); +} + +#[test] +fn official_material_icons_install() { + let f = fixture(Limits::default()); + let info = f.install(&repo().join("plugins/official/material-icons")); + assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error); + let theme: serde_json::Value = serde_json::from_str( + &std::fs::read_to_string(repo().join("plugins/official/material-icons/icons/theme.json")).unwrap(), + ) + .unwrap(); + let defined = theme["iconDefinitions"].as_object().unwrap().len(); + let svgs = f.host.assets("openidea.material-icons", &icon_theme_svg_prefix("material")).unwrap(); + assert_eq!(svgs.len(), defined, "every icon survives the sanitiser"); + let map = &f.host.assets("openidea.material-icons", &icon_theme_map_asset("material")).unwrap()[0].1; + assert!(map.contains("\"src\":\"folder-src\""), "folder names are part of the mapping"); + assert!( + !f.installed("openidea.material-icons").join("generate.py").exists(), + "only referenced files are installed" + ); +} + +/// An icon theme with thousands of SVGs (sanitising, package size, start-up). +#[test] +fn thousands_of_icons_install_and_reload_within_budget() { + const ICONS: usize = 3000; + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let pkg = tmp.path().join("many"); + std::fs::create_dir_all(pkg.join("svg")).unwrap(); + let mut defs = serde_json::Map::new(); + let mut exts = serde_json::Map::new(); + for i in 0..ICONS { + let svg = format!( + r##"{}"##, + i * 2654435 % 0xff_ffff, + i % 100 + ); + std::fs::write(pkg.join(format!("svg/i{i}.svg")), svg).unwrap(); + defs.insert(format!("i{i}"), format!("svg/i{i}.svg").into()); + exts.insert(format!("x{i}"), format!("i{i}").into()); + } + let theme = serde_json::json!({ "iconDefinitions": defs, "file": "i0", "fileExtensions": exts }); + std::fs::write(pkg.join("theme.json"), theme.to_string()).unwrap(); + std::fs::write( + pkg.join("plugin.toml"), + "id = \"acme.many\"\nname = \"Many\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\n\ + [[contributes.iconThemes]]\nid = \"many\"\nlabel = \"Many\"\npath = \"theme.json\"\n", + ) + .unwrap(); + + let started = Instant::now(); + let info = f.install(&pkg); + let install = started.elapsed(); + assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error); + assert_eq!(f.host.assets("acme.many", &icon_theme_svg_prefix("many")).unwrap().len(), ICONS); + + let started = Instant::now(); + let again = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); + again.load_all(); + let reload = started.elapsed(); + assert_eq!(again.assets("acme.many", &icon_theme_svg_prefix("many")).unwrap().len(), ICONS); + eprintln!("{ICONS} icons: install {install:?}, load at start-up {reload:?} (from the contribution index)"); + // Guards against work that grows faster than the icon count, not a + // benchmark: a debug build takes ~1.6 s / ~0.35 s on a laptop; shared CI + // runners running the suite in parallel take several times that (Windows + // ~11 s to install). + assert!(install < Duration::from_secs(30), "install took {install:?}"); + assert!(reload < Duration::from_secs(10), "start-up load took {reload:?}"); + + // Start-up reads the validated declaration from the index, not the SVGs: + // a tampered icon file is not even looked at... + let index = f.plugins_dir.join(".cache/contributions"); + assert_eq!(std::fs::read_dir(&index).unwrap().count(), 1); + std::fs::write(f.installed("acme.many").join("svg/i1.svg"), "").unwrap(); + let third = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); + third.load_all(); + let icon = third.assets("acme.many", &icon_theme_svg_prefix("many")).unwrap(); + assert!(icon.iter().all(|(_, svg)| !svg.contains("script"))); + // ...and without the index everything is validated again. + std::fs::remove_dir_all(&index).unwrap(); + let fourth = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); + fourth.load_all(); + assert_eq!(fourth.info_of("acme.many").unwrap().status, PluginStatus::Failed, "the tampered icon is rejected"); +} + +#[test] +fn linked_development_plugins() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let pkg = tmp.path().join("toy"); + copy_dir(&sample("language-toy"), &pkg); + let info = f.host.link(&pkg).unwrap(); + assert_eq!(info.source, PluginSource::Linked); + assert_eq!(info.status, PluginStatus::NeedsConsent); + f.host.grant("language-toy", &Consent::default()).unwrap(); + assert_eq!(f.host.languages().len(), 1); + // Survives a restart (links.json) and keeps its grant (by path). + let again = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); + again.load_all(); + assert_eq!(again.info_of("language-toy").unwrap().status, PluginStatus::Static); + again.unlink("language-toy").unwrap(); + assert!(again.info_of("language-toy").is_err()); +} + +#[test] +fn catalog_lists_sample_packages() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let broken = tmp.path().join("broken"); + std::fs::create_dir_all(&broken).unwrap(); + std::fs::write( + broken.join("plugin.toml"), + "id = \"x\"\nname = \"X\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\nwasm = \"dist/plugin.wasm\"\n", + ) + .unwrap(); + std::fs::create_dir_all(tmp.path().join("junk")).unwrap(); + std::fs::write(tmp.path().join("junk/plugin.toml"), "garbage = ").unwrap(); + + let catalog = f.host.catalog(&[ + repo().join("crates/ide-plugin/tests/fixtures"), + repo().join("plugins/official"), + tmp.path().to_path_buf(), + ]); + let ids: Vec<&str> = catalog.iter().map(|c| c.id.as_str()).collect(); + for id in ["hello", "openidea.harbor-night", "language-toy", "x"] { + assert!(ids.contains(&id), "{id} missing from {ids:?}"); + } + let hello = catalog.iter().find(|c| c.id == "hello").unwrap(); + assert!(hello.has_code && hello.problem.is_none() && hello.change_notes.is_some()); + assert_eq!(hello.contributions.iter().find(|c| c.point == "commands").unwrap().count, 2); + let theme = catalog.iter().find(|c| c.id == "openidea.harbor-night").unwrap(); + assert!(!theme.has_code); + assert_eq!(theme.contributions[0].count, 1); + let x = catalog.iter().find(|c| c.id == "x").unwrap(); + assert!(x.problem.as_deref().unwrap().contains("plugin.wasm")); +} + +fn official(name: &str) -> PathBuf { + repo().join("plugins/official").join(name) +} + +/// String Tools: 26 commands show before the code loads; one command +/// edits every selection as one versioned change. +#[test] +fn official_string_tools() { + let f = fixture(Limits::default()); + let info = f.install(&official("string-tools")); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + let titles = f.command_titles("openidea.string-tools"); + assert_eq!(titles.len(), 26); + assert!(titles.contains(&"String Tools: To snake_case".to_owned())); + let categories: std::collections::BTreeSet = + f.host.ui_items(COMMANDS).iter().filter_map(|c| c.decl["category"].as_str().map(str::to_owned)).collect(); + assert_eq!(categories.len(), 4, "{categories:?}"); + + let editor = f.workspace.open("src/notes.txt", &[(0, 0, 0, 3), (1, 5, 1, 5)]); + let before = f.workspace.document(&editor.path).unwrap().0; + f.run_in(&editor, "openidea.string-tools", "upper-case").unwrap(); + assert_eq!(f.workspace.text("src/notes.txt"), "ONE two three\nfour FIVE\n"); + assert_eq!(f.workspace.document(&editor.path).unwrap().0, before + 1, "both selections in one change"); +} + +/// Key Promoter: action events are batched; an idle plugin is +/// woken once per batch, and its counts persist in storage. +#[test] +fn official_key_promoter() { + let f = fixture(Limits::default()); + f.install(&official("key-promoter")); + assert!(f.host.event_kinds().contains(&EventKind::ActionPerformed), "subscribed by its manifest"); + let menu = |action: &str| { + WorkbenchEvent::ActionPerformed(ActionPerformed { + action: action.into(), + title: "Duplicate Line".into(), + source: ActionSource::Menu, + shortcut: Some("Ctrl+D".into()), + }) + }; + let typed = WorkbenchEvent::ActionPerformed(ActionPerformed { + action: "editor.copy".into(), + title: "Copy".into(), + source: ActionSource::Keyboard, + shortcut: Some("Ctrl+C".into()), + }); + f.take_events(); + let now = Instant::now(); + f.host.post_events(Some("main"), vec![menu("code.duplicate"), typed]); + f.host.flush_events_at(now); + assert_eq!(f.host.instances(), 0, "an idle plugin collects a batch first"); + f.host.post_events(Some("main"), vec![menu("code.duplicate"), menu("code.duplicate")]); + f.host.flush_events_at(now + Duration::from_secs(3)); + assert!(f.host.wait_events(Duration::from_secs(10))); + let info = f.host.info_of("openidea.key-promoter").unwrap(); + assert_eq!((info.status, info.stats.activations, info.stats.calls), (PluginStatus::Active, 1, 1), "one wake-up"); + let tips: Vec<_> = f + .take_events() + .into_iter() + .filter_map(|(client, e)| match e { + PluginEvent::Notification { title, body, .. } => Some((client, title, body)), + _ => None, + }) + .collect(); + assert_eq!(tips.len(), 1, "{tips:?}"); + assert_eq!(tips[0].0.as_deref(), Some("main"), "shown in the window the actions came from"); + assert!(tips[0].1.contains("Ctrl+D") && tips[0].2.contains("3 times"), "{tips:?}"); + let stored = std::fs::read_to_string(f.plugins_dir.join(".data/openidea.key-promoter/storage.json")).unwrap(); + assert!(stored.contains("\"count:code.duplicate\":\"3\""), "{stored}"); + + // Uninstalling removes its data. + f.host.uninstall("openidea.key-promoter").unwrap(); + assert!(!f.plugins_dir.join(".data/openidea.key-promoter").exists()); + assert!(f.host.event_kinds().is_empty()); +} + +fn git(dir: &Path, args: &[&str]) { + let out = std::process::Command::new("git") + .args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "init.defaultBranch=main"]) + .args(args) + .current_dir(dir) + .output() + .expect("git"); + assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr)); +} + +/// Git Toolbox's scheduled fetch still runs after the +/// instance was reclaimed while idle, and the status bar follows. +#[test] +fn official_git_toolbox_fetches_on_schedule_after_idle_reclaim() { + let f = fixture(Limits { idle_timeout: Some(Duration::from_millis(50)), ..Limits::default() }); + let tmp = tempfile::tempdir().unwrap(); + // The project tracks a remote that gets one more commit. + let remote = tmp.path().join("remote.git"); + std::fs::create_dir(&remote).unwrap(); + git(&remote, &["init", "--bare", "-b", "main"]); + git(&f.project, &["init", "-b", "main"]); + git(&f.project, &["add", "."]); + git(&f.project, &["commit", "-m", "one"]); + git(&f.project, &["remote", "add", "origin", remote.to_str().unwrap()]); + git(&f.project, &["push", "-u", "origin", "main"]); + let other = tmp.path().join("other"); + git(tmp.path(), &["clone", remote.to_str().unwrap(), other.to_str().unwrap()]); + std::fs::write(other.join("b.txt"), "b").unwrap(); + git(&other, &["add", "."]); + git(&other, &["commit", "-m", "two"]); + git(&other, &["push"]); + + f.install(&official("git-toolbox")); + // Focusing an editor wakes it to show the branch (nothing fetched yet). + let now = Instant::now(); + f.host.post_events(Some("main"), vec![WorkbenchEvent::EditorFocused(Some("src/notes.txt".into()))]); + f.host.flush_events_at(now + Duration::from_secs(3)); + assert!(f.host.wait_events(Duration::from_secs(10))); + let item = |host: &PluginHost| { + host.status_items().into_iter().find(|(p, id, _)| p == "openidea.git-toolbox" && id == "branch") + }; + assert_eq!(item(&f.host).map(|(_, _, i)| i.text), Some("main".into())); + + // Idle: reclaimed. + std::thread::sleep(Duration::from_millis(100)); + f.host.tick(); + assert_eq!(f.host.instances(), 0); + assert_eq!(f.status("openidea.git-toolbox"), PluginStatus::Inactive); + assert!(item(&f.host).is_some(), "its status item stays while it sleeps"); + + // Five minutes later: activated by its schedule, fetches, shows ↓1. + f.take_events(); + f.host.tick_at(Instant::now() + Duration::from_secs(301)); + assert!(f.host.wait_events(Duration::from_secs(30))); + let info = f.host.info_of("openidea.git-toolbox").unwrap(); + assert_eq!(info.stats.activations, 2, "{:?}", info.error); + assert_eq!(item(&f.host).map(|(_, _, i)| i.text), Some("main ↓1".into())); + let events = f.take_events(); + assert!( + events.iter().any( + |(_, e)| matches!(e, PluginEvent::TaskStarted { title, cancellable: true, .. } if title == "Fetching") + ) + ); + assert!(events.iter().any(|(_, e)| matches!(e, PluginEvent::TaskEnded { .. }))); + let stored = std::fs::read_to_string(f.plugins_dir.join(".data/openidea.git-toolbox/storage.json")).unwrap(); + assert!(stored.contains("last-fetch:"), "{stored}"); +} + +/// Restricted Mode: git does not run in an untrusted project (no fetch). +#[test] +fn git_toolbox_does_not_fetch_untrusted_projects() { + let f = fixture(Limits::default()); + git(&f.project, &["init", "-b", "main"]); + f.install(&official("git-toolbox")); + let untrusted = Arc::new(TestWorkspace { + root: f.project.clone(), + documents: f.workspace.documents.clone(), + trusted: false, + diagnostics: Mutex::default(), + settings: Mutex::default(), + }); + f.host.set_workspace(Some(untrusted)); + let err = f.run("openidea.git-toolbox", "fetch", None).unwrap_err(); + assert!(err.contains("Restricted Mode"), "{err}"); +} + +/// A tiny HTTP server: each request is answered after `delay(n)` (n counts +/// requests) with `body`. Returns its port and the request bodies it got. +fn http_server( + body: &'static str, + delay: impl Fn(usize) -> Duration + Send + Sync + 'static, +) -> (u16, Arc>>) { + use std::io::{BufRead, BufReader, Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let seen: Arc>> = Arc::default(); + let (log, delay) = (seen.clone(), Arc::new(delay)); + std::thread::spawn(move || { + for (n, stream) in listener.incoming().flatten().enumerate() { + let (log, delay) = (log.clone(), delay.clone()); + std::thread::spawn(move || { + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut len = 0; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { + break; + } + if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") { + len = v.trim().parse().unwrap_or(0); + } + } + let mut req = vec![0; len]; + let _ = reader.read_exact(&mut req); + log.lock().push(String::from_utf8_lossy(&req).into_owned()); + std::thread::sleep(delay(n)); + let mut stream = stream; + let _ = write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + }); + } + }); + (port, seen) +} + +/// AI Completion: typing on cancels the previous request (the fetch +/// returns `cancelled`, the instance stays); the plugin's own work stays +/// within the edit-path budget. +#[test] +fn official_ai_completion_cancels_superseded_requests() { + let f = fixture(Limits::default()); + f.install(&official("ai-completion")); + let (port, seen) = http_server(r#"{"choices":[{"text":"a + b\n"}]}"#, |n| { + if n == 0 { Duration::from_secs(3) } else { Duration::ZERO } + }); + f.run("openidea.ai-completion", "set-endpoint", Some(&format!("http://localhost:{port}"))).unwrap(); + let doc = ide_plugin::ProviderDocument { + path: f.project.join("src/a.rs"), + language: "rust".into(), + version: 1, + text: "fn add(a: i32, b: i32) -> i32 {\n \n}\n".into(), + }; + let at = ide_core::Pos::new(1, 4); + let host = Arc::new(f); + // A slow request, superseded 200 ms later by the next keystroke's. + let first = ide_core::CancellationToken::new(); + let slow = { + let (host, doc, first) = (host.clone(), doc.clone(), first.clone()); + std::thread::spawn(move || { + let started = Instant::now(); + let r = host.host.provide_inline_completion(&doc, at, &first); + (r, started.elapsed()) + }) + }; + std::thread::sleep(Duration::from_millis(200)); + first.cancel(); + let started = Instant::now(); + let second = host.host.provide_inline_completion(&doc, at, &ide_core::CancellationToken::new()); + let took = started.elapsed(); + let (old, old_took) = slow.join().unwrap(); + assert!(old.is_none(), "the superseded request yields nothing"); + assert!(old_took < Duration::from_secs(1), "cancelled, not waited out: {old_took:?}"); + assert_eq!(second.map(|(_, s)| s.insert_text).as_deref(), Some("a + b")); + eprintln!("inline completion after cancelling the previous request: {took:?}"); + let info = host.host.info_of("openidea.ai-completion").unwrap(); + assert_eq!((info.stats.crashes, info.stats.activations), (0, 1), "cooperative: same instance"); + assert!(seen.lock()[1].contains("\"prompt\":\"fn add(a: i32, b: i32) -> i32 {\\n \""), "{:?}", seen.lock()); + + // The plugin's own share of a call (local server, no delay): edit-path budget. + let mut times = Vec::new(); + for _ in 0..10 { + let started = Instant::now(); + assert!(host.host.provide_inline_completion(&doc, at, &ide_core::CancellationToken::new()).is_some()); + times.push(started.elapsed()); + } + times.sort(); + eprintln!("inline completion round trip p95 (local server): {:?}", times[9]); + assert!(times[9] < Duration::from_millis(500), "{times:?}"); +} + +/// Checkstyle: a save runs the approved `checkstyle` and publishes +/// diagnostics; quick fixes come through the code-action provider; saving +/// again cancels the check still running. +#[cfg(unix)] +#[test] +fn official_checkstyle_checks_on_save() { + use std::os::unix::fs::PermissionsExt; + let f = fixture(Limits::default()); + let bin = f.plugins_dir.parent().unwrap().join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + // Reports a tab on line 2; files containing SLOW take 5 s. + std::fs::write( + bin.join("checkstyle"), + "#!/bin/sh\nfor a; do file=\"$a\"; done\ngrep -q SLOW \"$file\" && sleep 5\n\ + echo ''\n\ + echo ''\n\ + echo ''\nexit 1\n", + ) + .unwrap(); + std::fs::set_permissions(bin.join("checkstyle"), std::fs::Permissions::from_mode(0o755)).unwrap(); + let path = bin.clone(); + f.host.set_program_path(Arc::new(move || Some(path.clone().into_os_string()))); + let info = f.install(&official("checkstyle")); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + + let java = f.project.join("src/A.java"); + std::fs::write(&java, "class A {\n\tint x;\n}\n").unwrap(); + let saved = |f: &Fixture| { + f.host.post_events(Some("main"), vec![WorkbenchEvent::FileSaved(java.to_string_lossy().into_owned())]); + f.host.flush_events_at(Instant::now() + Duration::from_secs(3)); + }; + saved(&f); + assert!(f.host.wait_events(Duration::from_secs(20))); + let diagnostics = + |f: &Fixture| f.workspace.diagnostics.lock().get(&("openidea.checkstyle".into(), java.clone())).cloned(); + let d = diagnostics(&f).expect("published"); + assert_eq!((d.len(), d[0].code.as_deref(), d[0].range.start.line), (1, Some("FileTabCharacter"), 1)); + + // The quick fix, through the provider (as the editor asks for it). + let doc = ide_plugin::ProviderDocument { + path: java.clone(), + language: "java".into(), + version: 1, + text: std::fs::read_to_string(&java).unwrap(), + }; + let range = ide_core::Range::new(ide_core::Pos::new(1, 0), ide_core::Pos::new(1, 0)); + let actions = f.host.provide_code_actions(&doc, range); + assert_eq!(actions.len(), 1, "{actions:?}"); + assert_eq!(actions[0].1.title, "Checkstyle: Replace tabs with spaces"); + assert_eq!(actions[0].1.edits[0].1[0].new_text, " int x;"); + + // A slow check is cancelled by the next save. + f.workspace.diagnostics.lock().clear(); + std::fs::write(&java, "class A { // SLOW\n\tint x;\n}\n").unwrap(); + let started = Instant::now(); + saved(&f); + std::thread::sleep(Duration::from_millis(300)); + std::fs::write(&java, "class A {\n\tint y;\n}\n").unwrap(); + saved(&f); + assert!(f.host.wait_events(Duration::from_secs(20))); + assert!(started.elapsed() < Duration::from_secs(4), "the slow run was killed: {:?}", started.elapsed()); + assert_eq!(diagnostics(&f).map(|d| d.len()), Some(1), "published by the second check"); + let info = f.host.info_of("openidea.checkstyle").unwrap(); + assert_eq!(info.stats.crashes, 0); +} + +/// License Header: reported when a file opens, fixed through the provider, +/// and a project scan in a task reports the rest. +#[test] +fn official_license_header_reports_fixes_and_scans() { + let f = fixture(Limits::default()); + let info = f.install(&official("license-header")); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + let a = f.project.join("src/a.rs"); + let b = f.project.join("src/b.py"); + std::fs::write(&a, "fn a() {}\n").unwrap(); + std::fs::write(&b, "#!/usr/bin/env python3\nprint()\n").unwrap(); + let diagnostics = |path: &Path| { + f.workspace.diagnostics.lock().get(&("openidea.license-header".into(), path.to_path_buf())).cloned() + }; + + f.host.post_events(Some("main"), vec![WorkbenchEvent::FileOpened(a.to_string_lossy().into_owned())]); + f.host.flush_events_at(Instant::now() + Duration::from_secs(3)); + assert!(f.host.wait_events(Duration::from_secs(20))); + let d = diagnostics(&a).expect("published on open"); + assert_eq!((d.len(), d[0].code.as_deref()), (1, Some("missing-license-header"))); + assert!(diagnostics(&b).is_none(), "only the opened file"); + + let doc = ide_plugin::ProviderDocument { + path: b.clone(), + language: "python".into(), + version: 1, + text: std::fs::read_to_string(&b).unwrap(), + }; + let actions = f.host.provide_code_actions(&doc, ide_core::Range::default()); + assert_eq!(actions.len(), 1, "{actions:?}"); + let edit = &actions[0].1.edits[0].1[0]; + assert_eq!(edit.range.start.line, 1, "after the shebang"); + assert!( + edit.new_text.starts_with("# Copyright (c) 20") + && edit.new_text.contains("# SPDX-License-Identifier: Apache-2.0") + ); + + f.host.run_command("openidea.license-header", "scan", None, f.inv()).unwrap(); + assert_eq!(diagnostics(&b).map(|d| d.len()), Some(1), "found by the scan"); + std::fs::write(&a, "// Copyright (c) 2026 X\nfn a() {}\n").unwrap(); + f.host.post_events(Some("main"), vec![WorkbenchEvent::FileSaved(a.to_string_lossy().into_owned())]); + f.host.flush_events_at(Instant::now() + Duration::from_secs(3)); + assert!(f.host.wait_events(Duration::from_secs(20))); + assert_eq!(diagnostics(&a).map(|d| d.len()), Some(0), "cleared once the header is there"); + + // Disabling the plugin withdraws the problems it still shows. + f.host.set_enabled("openidea.license-header", false).unwrap(); + assert_eq!(diagnostics(&b).map(|d| d.len()), Some(0), "withdrawn with the plugin"); +} + +/// MyBatis Navigator: interface ↔ XML through the providers, on a +/// real project tree (`find-files`), within the edit-path budget. +#[test] +fn official_mybatis_navigates_between_interface_and_xml() { + let f = fixture(Limits::default()); + f.install(&official("mybatis")); + let java_path = f.project.join("src/main/java/com/acme/UserMapper.java"); + let xml_path = f.project.join("src/main/resources/mapper/UserMapper.xml"); + std::fs::create_dir_all(java_path.parent().unwrap()).unwrap(); + std::fs::create_dir_all(xml_path.parent().unwrap()).unwrap(); + let java = "package com.acme;\n\npublic interface UserMapper {\n User findById(long id);\n}\n"; + let xml = "\n \n\n"; + std::fs::write(&java_path, java).unwrap(); + std::fs::write(&xml_path, xml).unwrap(); + // Noise the index has to skip. + for i in 0..200 { + std::fs::write(f.project.join(format!("src/f{i}.xml")), "").unwrap(); + } + let doc = |path: &Path, language: &str, text: &str| ide_plugin::ProviderDocument { + path: path.to_path_buf(), + language: language.into(), + version: 1, + text: text.into(), + }; + let jdoc = doc(&java_path, "java", java); + // The first call indexes the XML files; on a slow machine that runs past the + // edit-path budget, so the answer is dropped (the index is kept) and calls + // queued behind it are skipped. The editor asks again; so does this. + let deadline = Instant::now() + Duration::from_secs(10); + let markers = loop { + let markers = f.host.provide_line_markers(&jdoc); + if !markers.is_empty() || Instant::now() > deadline { + break markers; + } + std::thread::sleep(Duration::from_millis(50)); + }; + assert_eq!(markers.len(), 1, "{markers:?}"); + let target = markers[0].1.target.clone().unwrap(); + assert_eq!((target.path, target.range.start), (xml_path.clone(), ide_core::Pos::new(1, 14))); + + let xdoc = doc(&xml_path, "xml", xml); + let to_java = f.host.provide_definition(&xdoc, ide_core::Pos::new(1, 16)); + assert_eq!( + to_java.iter().map(|l| (l.path.clone(), l.range.start)).collect::>(), + [(java_path.clone(), ide_core::Pos::new(3, 9))] + ); + assert!( + f.host.provide_definition(&doc(&f.project.join("src/a.rs"), "rust", ""), ide_core::Pos::new(0, 0)).is_empty(), + "not its language" + ); + + // Warm (index cached): well inside the edit-path budget. + let slow = f.host.info_of("openidea.mybatis").unwrap().stats.slow_calls; + let mut times = Vec::new(); + for _ in 0..20 { + let started = Instant::now(); + assert_eq!(f.host.provide_line_markers(&jdoc).len(), 1); + times.push(started.elapsed()); + } + times.sort(); + eprintln!("mybatis line markers p95: {:?}", times[18]); + assert!(times[18] < Duration::from_millis(50), "{times:?}"); + assert_eq!(f.host.info_of("openidea.mybatis").unwrap().stats.slow_calls, slow); +} + +/// CSV Editor: a custom editor renders the document as a table (the +/// rows asked for), and edits the document itself — versioned, so a text edit +/// made meanwhile is never overwritten. +#[test] +fn official_csv_editor_edits_the_shared_document() { + let f = fixture(Limits::default()); + let info = f.install(&official("csv-editor")); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + std::fs::write(f.project.join("people.csv"), "name,city\nAda,London\nBob,Oslo\n").unwrap(); + let editor = f.workspace.open("people.csv", &[]); + let inv = Invocation { editor: Some(editor.clone()), ..f.inv() }; + let viewport = Some(ide_plugin::Viewport { first_row: 1, rows: 10 }); + let view = f.host.render_view("openidea.csv-editor", "table", viewport, inv.clone()).unwrap(); + let ide_plugin::ViewBody::Table(t) = &view.body else { panic!("{view:?}") }; + assert_eq!((t.columns.clone(), t.total_rows, t.first_row), (vec!["name".to_owned(), "city".into()], 2, 1)); + assert_eq!(t.rows, [vec!["Bob".to_owned(), "Oslo".into()]]); + assert_eq!(view.status.as_deref(), Some("2 rows × 2 columns, delimiter ','")); + + let cell = ide_plugin::ViewEvent::Cell { row: 0, column: 1, value: "Paris, FR".into() }; + f.host.view_event("openidea.csv-editor", "table", cell, inv.clone()).unwrap(); + assert_eq!(f.workspace.text("people.csv"), "name,city\nAda,\"Paris, FR\"\nBob,Oslo\n"); + + // Settings: without a header row every record is a row. + let mut values = serde_json::Map::new(); + values.insert("firstRowIsHeader".into(), serde_json::Value::Bool(false)); + f.workspace.settings.lock().insert("openidea.csv-editor".into(), values); + let view = f.host.render_view("openidea.csv-editor", "table", None, inv.clone()).unwrap(); + let ide_plugin::ViewBody::Table(t) = &view.body else { panic!("{view:?}") }; + assert_eq!((t.columns[0].as_str(), t.total_rows), ("Column 1", 3)); + + // Undeclared views are refused before any code runs. + let err = f.host.render_view("openidea.csv-editor", "other", None, inv).unwrap_err(); + assert_eq!(err.kind, ide_core::error::ErrorKind::NotFound); +} + +/// The sample plugin makes a tool window with a tree view. +/// Its menus, shortcut and status bar item are declarations, listed before +/// any code runs; the tree is rendered by the code, which loads on first show. +#[test] +fn sample_plugin_tool_window_with_a_tree() { + let f = fixture(Limits::default()); + let info = f.install(&sample("hello")); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + for point in ["menus", "keymaps", "statusBar", "views"] { + assert_eq!(f.host.ui_items(point).len(), 1, "{point}"); + } + let view = f.host.ui_items("views").remove(0); + assert_eq!((view.key.as_str(), view.decl["location"].as_str()), ("greetings", Some("right"))); + assert_eq!(f.status("hello"), PluginStatus::Inactive, "declarations need no code"); + + let tree = |f: &Fixture| match f.host.render_view("hello", "greetings", None, f.inv()).unwrap().body { + ide_plugin::ViewBody::Tree(items) => items, + other => panic!("{other:?}"), + }; + assert_eq!(tree(&f).iter().map(|i| i.label.as_str()).collect::>(), ["English", "Deutsch", "日本語"]); + assert_eq!(f.status("hello"), PluginStatus::Active, "activated on show (on-view)"); + f.take_events(); + f.host.view_event("hello", "greetings", ide_plugin::ViewEvent::Expand { key: "English".into() }, f.inv()).unwrap(); + let refreshed = f.take_events().into_iter().any(|(_, e)| { + matches!(e, PluginEvent::ViewChanged { ref plugin_id, ref view } if plugin_id == "hello" && view == "greetings") + }); + assert!(refreshed, "the plugin asked for a refresh"); + let items = tree(&f); + assert_eq!(items.len(), 6); + assert_eq!(items[1].parent.as_deref(), Some("English")); + f.host + .view_event("hello", "greetings", ide_plugin::ViewEvent::Activate { key: "English/Hi".into() }, f.inv()) + .unwrap(); + assert!(f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::Notification { title, .. } if title == "Hi"))); + + // Disabling withdraws every declaration. + f.host.set_enabled("hello", false).unwrap(); + for point in ["menus", "keymaps", "statusBar", "views"] { + assert!(f.host.ui_items(point).is_empty(), "{point}"); + } +} + +/// Regex Tester: an `html` body its script talks to; the plugin answers in +/// view messages, in UTF-16 offsets. +#[test] +fn official_regex_tester_answers_its_page() { + let f = fixture(Limits::default()); + let info = f.install(&official("regex-tester")); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + let view = f.host.render_view("openidea.regex-tester", "regex", None, f.inv()).unwrap(); + let ide_plugin::ViewBody::Html(page) = &view.body else { panic!("{view:?}") }; + assert!(page.contains("openidea.postMessage") && page.contains(r#"{"flags":"m"}"#)); + + f.take_events(); + let run = serde_json::json!({ "op": "run", "seq": 3, "pattern": r"(\d+)", "flags": "", "text": "é 12 345" }); + let event = ide_plugin::ViewEvent::Message { text: run.to_string() }; + f.host.view_event("openidea.regex-tester", "regex", event, f.inv()).unwrap(); + let reply = f + .take_events() + .into_iter() + .find_map(|(_, e)| match e { + PluginEvent::ViewMessage { view, message, .. } if view == "regex" => Some(message), + _ => None, + }) + .expect("a reply"); + let reply: serde_json::Value = serde_json::from_str(&reply).unwrap(); + assert_eq!((reply["seq"].clone(), reply["count"].clone()), (serde_json::json!(3), serde_json::json!(2))); + assert_eq!(reply["matches"][0]["groups"][0], serde_json::json!([2, 4])); +} + +/// A tree filled from a pinned program's output, and a terminal for the +/// activated entry in the invoking window, titled and sized by the plugin's +/// settings (the `jobs` fixture). +#[cfg(unix)] +#[test] +fn pinned_programs_fill_views_and_open_terminals() { + use std::os::unix::fs::PermissionsExt; + let f = fixture(Limits::default()); + let bin = f.plugins_dir.parent().unwrap().join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + std::fs::write(bin.join("jobs"), "#!/bin/sh\n[ \"$1\" = list ] && printf 'build\\ndeploy\\n'\n").unwrap(); + std::fs::set_permissions(bin.join("jobs"), std::fs::Permissions::from_mode(0o755)).unwrap(); + let path = bin.clone(); + f.host.set_program_path(Arc::new(move || Some(path.clone().into_os_string()))); + let info = f.install(&sample("jobs")); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + + let view = f.host.render_view("jobs", "jobs", None, f.inv()).unwrap(); + let ide_plugin::ViewBody::Tree(items) = &view.body else { panic!("{view:?}") }; + assert_eq!(items.iter().map(|i| i.key.as_str()).collect::>(), ["build", "deploy"]); + + let open = |key: &str| { + f.take_events(); + f.host.view_event("jobs", "jobs", ide_plugin::ViewEvent::Activate { key: key.into() }, f.inv()).unwrap(); + f.take_events().into_iter().find_map(|(client, e)| match e { + PluginEvent::OpenTerminal { title, program, args, .. } => Some((client, title, program, args)), + _ => None, + }) + }; + let (client, title, program, args) = open("deploy").expect("a terminal"); + assert_eq!((client.as_deref(), title.as_str()), (Some("main"), "follow: deploy")); + assert_eq!(program.0, bin.join("jobs").canonicalize().unwrap()); + assert_eq!(args, ["follow", "deploy", "--lines=20"]); + + // The plugin's settings, string and number. + let values = serde_json::json!({ "title": "tail ", "lines": 5 }).as_object().unwrap().clone(); + f.workspace.settings.lock().insert("jobs".into(), values); + let (_, title, _, args) = open("build").expect("a terminal"); + assert_eq!(title, "tail build"); + assert_eq!(args, ["follow", "build", "--lines=5"]); +} + +/// A plugin with web views and no code: its pages and their files are +/// installed with it and served only from the declared directories, while +/// it is enabled and only for the installed version; file icons and +/// templates are projected too. +#[test] +fn web_views_serve_only_their_own_files() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let pkg = tmp.path().join("web-demo"); + for (path, text) in [ + ("web/index.html", "draw"), + ("web/assets/app.js", "console.log(1)"), + ("panel/index.html", "

panel

"), + ( + "icons/draw.svg", + r##""##, + ), + ("templates/new.draw", "{\"type\": \"drawing\"}\n"), + ("secret.txt", "not served"), + ] { + std::fs::create_dir_all(pkg.join(path).parent().unwrap()).unwrap(); + std::fs::write(pkg.join(path), text).unwrap(); + } + std::fs::write( + pkg.join("plugin.toml"), + r#"id = "web-demo" +name = "Web Demo" +version = "1.0.0" +engines.openidea = "^1.0" + +[capabilities] +optional = ["clipboard"] + +[[contributes.customEditors]] +id = "draw" +title = "Drawing" +patterns = ["*.draw"] +layout = "preview" +web = "web/index.html" + +[[contributes.views]] +id = "panel" +title = "Panel" +web = "panel/index.html" + +[[contributes.fileIcons]] +id = "draw" +patterns = ["*.draw"] +icon = "icons/draw.svg" + +[[contributes.fileTemplates]] +id = "draw" +name = "Drawing" +extension = "draw" +path = "templates/new.draw" +"#, + ) + .unwrap(); + let info = f.install(&pkg); + assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error); + assert!(info.capabilities.iter().any(|c| c.id == "clipboard" && c.granted), "{:?}", info.capabilities); + // The pages' directories are installed with the plugin; files nothing declares are not. + let installed = f.installed("web-demo"); + assert!(installed.join("web/assets/app.js").is_file() && installed.join("panel/index.html").is_file()); + assert!(!installed.join("secret.txt").exists()); + + let page = f.host.web_page("web-demo", "draw").unwrap(); + let (rev, entry) = page.path.strip_prefix("web-demo/").unwrap().split_once('/').unwrap(); + assert_eq!(entry, "web/index.html"); + let file = |path: &str| f.host.web_file("web-demo", path); + let js = file(&format!("{rev}/web/assets/app.js")).unwrap(); + assert_eq!((js.bytes.as_slice(), js.mime), (b"console.log(1)".as_slice(), "text/javascript; charset=utf-8")); + assert!(file(&format!("{rev}/panel/index.html")).is_ok()); + assert_eq!(f.host.web_page("web-demo", "panel").unwrap().path, format!("web-demo/{rev}/panel/index.html")); + for denied in [ + format!("{rev}/secret.txt"), + format!("{rev}/plugin.toml"), + format!("{rev}/web/../secret.txt"), + format!("{rev}/icons/draw.svg"), + "stale-revision/web/index.html".to_owned(), + ] { + assert!(file(&denied).is_err(), "{denied} was served"); + } + assert!(f.host.web_page("web-demo", "nope").is_err()); + + // File icons and templates. + let icon = f.host.assets("web-demo", "fileIcon/draw/").unwrap(); + assert_eq!(icon.len(), 1); + assert!(icon[0].0 == "fileIcon/draw/light" && icon[0].1.contains(" = (0..4) + .map(|i| { + let (host, done) = (host.clone(), done.clone()); + let root = f._tmp.path().join(format!("p{i}")); + std::thread::spawn(move || { + while !done.load(std::sync::atomic::Ordering::Relaxed) { + if i % 2 == 0 { + host.list(None); + } else { + host.restrict_project(&root); + } + } + }) + }) + .collect(); + std::thread::sleep(Duration::from_millis(500)); + done.store(true, std::sync::atomic::Ordering::Relaxed); + let started = Instant::now(); + for w in workers { + while !w.is_finished() { + assert!(started.elapsed() < Duration::from_secs(10), "deadlocked"); + std::thread::sleep(Duration::from_millis(10)); + } + w.join().unwrap(); + } +} + +/// Excalidraw: a web custom editor beside the text editor, with its fonts, +/// file icon, template and language — no code. +#[test] +fn official_excalidraw_installs_and_serves_its_page() { + let tmp = tempfile::tempdir().unwrap(); + let pkg = with_stand_in_page(&official("excalidraw"), tmp.path()); + let f = fixture(Limits::default()); + let info = f.install(&pkg); + assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error); + let page = f.host.web_page("openidea.excalidraw", "canvas").unwrap(); + let (rev, entry) = page.path.strip_prefix("openidea.excalidraw/").unwrap().split_once('/').unwrap(); + assert_eq!(entry, "web/index.html"); + let html = f.host.web_file("openidea.excalidraw", &format!("{rev}/{entry}")).unwrap(); + let html = String::from_utf8(html.bytes).unwrap(); + // Relative URLs only: the page is served from the package. + let script = html.split("src=\"").nth(1).unwrap().split('"').next().unwrap(); + assert!(script.starts_with("./assets/"), "{script}"); + assert!(f.host.web_file("openidea.excalidraw", &format!("{rev}/web/{}", &script[2..])).is_ok()); + let font = f.host.web_file("openidea.excalidraw", &format!("{rev}/web/fonts/Virgil/Virgil-Regular.woff2")).unwrap(); + assert_eq!(font.mime, "font/woff2"); + assert_eq!(f.host.ui_items("customEditors")[0].decl["layout"], "preview"); + assert!(f.host.languages().iter().any(|l| l.id.as_str() == "excalidraw")); + assert_eq!(f.host.assets("openidea.excalidraw", "fileIcon/excalidraw/").unwrap().len(), 2); +} + +/// A copy of the official plugin at `src` in `dir`, with a stand-in for its +/// built page (`web/` is built by plugins/build.sh, not checked in; build.sh +/// checks what the build produces): an entry loading a script and a font by +/// relative URL. +fn with_stand_in_page(src: &Path, dir: &Path) -> PathBuf { + let pkg = dir.join(src.file_name().unwrap()); + std::fs::create_dir_all(&pkg).unwrap(); + for entry in std::fs::read_dir(src).unwrap().flatten() { + let name = entry.file_name(); + if ["web", "web-src", "web.sources", "target"].iter().any(|n| name == *n) { + continue; + } + let to = pkg.join(&name); + if entry.path().is_dir() { + copy_dir(&entry.path(), &to) + } else { + std::fs::copy(entry.path(), to).map(|_| ()).unwrap() + } + } + std::fs::create_dir_all(pkg.join("web/assets")).unwrap(); + std::fs::create_dir_all(pkg.join("web/fonts/Virgil")).unwrap(); + std::fs::write( + pkg.join("web/index.html"), + r#""#, + ) + .unwrap(); + std::fs::write(pkg.join("web/assets/index.js"), "export {};").unwrap(); + std::fs::write(pkg.join("web/fonts/Virgil/Virgil-Regular.woff2"), b"wOF2").unwrap(); + pkg +} + +/// Graphviz: a web view with code. What the page reports about the graph +/// becomes the previewed file's problems. +#[test] +fn official_graphviz_turns_its_pages_reports_into_problems() { + let tmp = tempfile::tempdir().unwrap(); + let f = fixture(Limits::default()); + let info = f.install(&with_stand_in_page(&official("graphviz"), tmp.path())); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + assert_eq!(f.host.ui_items("customEditors")[0].decl["layout"], "split"); + assert!(f.host.languages().iter().any(|l| l.id.as_str() == "dot")); + assert!(f.host.web_page("openidea.graphviz", "preview").is_ok()); + + std::fs::write(f.project.join("flow.dot"), "digraph {\n a -> \n}\n").unwrap(); + let editor = f.workspace.open("flow.dot", &[]); + let inv = Invocation { editor: Some(editor), ..f.inv() }; + let report = + r#"{"op":"problems","items":[{"line":3,"message":"syntax error in line 3 near '}'","level":"error"}]}"#; + let event = ide_plugin::ViewEvent::Message { text: report.into() }; + f.host.view_event("openidea.graphviz", "preview", event, inv.clone()).unwrap(); + let path = f.project.join("flow.dot"); + let problems = + |f: &Fixture| f.workspace.diagnostics.lock().get(&("openidea.graphviz".into(), path.clone())).cloned(); + let d = problems(&f).expect("published"); + assert_eq!((d.len(), d[0].range.start.line), (1, 2)); + let cleared = ide_plugin::ViewEvent::Message { text: r#"{"op":"problems","items":[]}"#.into() }; + f.host.view_event("openidea.graphviz", "preview", cleared, inv).unwrap(); + assert_eq!(problems(&f).map(|d| d.len()), Some(0)); +} + +/// Zips `dir` as an archiver does: the folder itself at the top, plus macOS metadata. +fn zip_folder(dir: &Path, out: &Path) { + use std::io::Write; + let name = dir.file_name().unwrap().to_string_lossy().into_owned(); + let mut zip = zip::ZipWriter::new(std::fs::File::create(out).unwrap()); + let options = zip::write::SimpleFileOptions::default(); + let mut stack = vec![(dir.to_path_buf(), name.clone())]; + while let Some((real, rel)) = stack.pop() { + for entry in std::fs::read_dir(&real).unwrap().flatten() { + let (path, rel) = (entry.path(), format!("{rel}/{}", entry.file_name().to_string_lossy())); + if path.is_dir() { + stack.push((path, rel)); + } else { + zip.start_file(rel, options).unwrap(); + zip.write_all(&std::fs::read(&path).unwrap()).unwrap(); + } + } + } + zip.start_file(format!("__MACOSX/{name}/._plugin.toml"), options).unwrap(); + zip.write_all(b"metadata").unwrap(); + zip.finish().unwrap(); +} + +#[test] +fn a_zipped_plugin_folder_installs_like_the_folder() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let archive = tmp.path().join("language-toy.zip"); + zip_folder(&sample("language-toy"), &archive); + + let dir = f.host.unpack_package(&archive).unwrap(); + let preview = f.host.preview_install(&dir).unwrap(); + assert_eq!(preview.id, "language-toy"); + assert!(preview.unsigned); + let info = f.host.install_from_dir(&dir, &Consent::all()).unwrap(); + assert_eq!(info.id, "language-toy"); + assert_eq!(f.host.languages().len(), 1); + + // A zip that isn't an OpenIDEA plugin says so. + let other = tmp.path().join("intellij-plugin.zip"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&other).unwrap()); + zip.start_file("my-plugin/lib/my-plugin.jar", zip::write::SimpleFileOptions::default()).unwrap(); + zip.finish().unwrap(); + let err = f.host.unpack_package(&other).unwrap_err().message; + assert!(err.contains("is not an OpenIDEA plugin"), "{err}"); +} + +/// Secrets live outside the plugin's directory (the OS keychain on the +/// desktop): uninstalling the plugin deletes the ones it declares. +#[test] +fn uninstalling_deletes_the_plugins_secrets() { + #[derive(Default)] + struct Keychain(Mutex>); + impl SecretStore for Keychain { + fn get(&self, plugin: &str, name: &str) -> Option { + self.0.lock().get(&(plugin.into(), name.into())).cloned() + } + fn set(&self, plugin: &str, name: &str, value: Option<&str>) -> Result<(), String> { + let key = (plugin.to_owned(), name.to_owned()); + match value { + Some(v) => self.0.lock().insert(key, v.into()), + None => self.0.lock().remove(&key), + }; + Ok(()) + } + } + let f = fixture(Limits::default()); + let keychain = Arc::new(Keychain::default()); + f.host.set_secret_store(keychain.clone()); + f.install(&official("ai-completion")); + f.host.set_secret("openidea.ai-completion", "api-key", Some("sk-test")).unwrap(); + assert!(keychain.get("openidea.ai-completion", "api-key").is_some()); + f.host.uninstall("openidea.ai-completion").unwrap(); + assert!(keychain.0.lock().is_empty(), "{:?}", keychain.0.lock().keys().collect::>()); +} diff --git a/crates/ide-host/tests/remote_plugins.rs b/crates/ide-host/tests/remote_plugins.rs new file mode 100644 index 00000000..dd3bd868 --- /dev/null +++ b/crates/ide-host/tests/remote_plugins.rs @@ -0,0 +1,304 @@ +//! Code plugins of a remote project run on the +//! server. The desktop's plugin host syncs its live +//! code plugins over the remote protocol; Checkstyle then checks the file on +//! the server's disk when it is saved, and secrets come from the desktop. + +#![cfg(unix)] + +use ide_core::IdeEvent; +use ide_host::plugins::remote_host::{ + EVENT_NOTIFICATION, PackageSyncReport, PluginEventMessage, RemotePlugins, SECRET_REQUEST, SYNC_PACKAGES, + SecretRequest, +}; +use ide_host::plugins::{Consent, PluginEvent, PluginHost, PluginStatus, WorkbenchEvent}; +use ide_host::rpc::{self, Dispatcher, EventMessage, Invoke}; +use ide_host::{Host, HostConfig}; +use ide_jsonrpc::{Handler, Peer}; +use ide_plugin::Limits; +use parking_lot::Mutex; +use serde_json::{Value, json}; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, OnceLock}; +use std::time::Duration; + +#[derive(Default)] +struct Client { + events: Mutex>, + plugin_events: Mutex>, + secret_requests: Mutex>, +} + +impl Handler for Client { + fn on_notification(&self, method: &str, params: Value) { + match method { + "event" => self.events.lock().push(serde_json::from_value(params).unwrap()), + EVENT_NOTIFICATION => self.plugin_events.lock().push(serde_json::from_value(params).unwrap()), + _ => {} + } + } + + fn on_request(&self, method: &str, params: Value) -> Result { + if method == SECRET_REQUEST { + let r: SecretRequest = serde_json::from_value(params).unwrap(); + let value = (r.name == "api-key").then(|| "sk-desktop".to_owned()); + self.secret_requests.lock().push(r); + return Ok(serde_json::to_value(value).unwrap()); + } + Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, method.to_owned())) + } +} + +async fn invoke(peer: &Peer, cmd: &str, args: Value) -> Result { + let call = Invoke { window: "main".into(), cmd: cmd.into(), args }; + peer.request::<_, Value>("invoke", call, None).await.map_err(rpc::error_from_reply) +} + +async fn sync(peer: &Peer, desktop: &PluginHost, files: &[&str]) -> PackageSyncReport { + let files: serde_json::Map = files + .iter() + .map(|id| ((*id).to_owned(), serde_json::to_value(desktop.remote_package_files(id).unwrap()).unwrap())) + .collect(); + let args = json!({ "packages": desktop.remote_packages(), "files": files }); + serde_json::from_value(invoke(peer, SYNC_PACKAGES, args).await.unwrap()).unwrap() +} + +fn official(name: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../plugins/official").join(name) +} + +/// A test fixture plugin (`crates/ide-plugin/tests/fixtures/`). +fn fixture(name: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures").join(name) +} + +/// A `checkstyle` that reports a tab on line 2 of the file it is given. +fn fake_checkstyle(bin: &Path) { + std::fs::create_dir_all(bin).unwrap(); + std::fs::write( + bin.join("checkstyle"), + "#!/bin/sh\nfor a; do file=\"$a\"; done\ngrep -q '\t' \"$file\" || { echo ''; exit 0; }\n\ + echo ''\n\ + echo ''\n\ + echo ''\nexit 1\n", + ) + .unwrap(); + std::fs::set_permissions(bin.join("checkstyle"), std::fs::Permissions::from_mode(0o755)).unwrap(); +} + +async fn until(what: &str, secs: u64, mut done: impl FnMut() -> bool) { + for _ in 0..secs * 50 { + if done() { + return; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + panic!("timed out waiting for {what}"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn remote_projects_run_the_desktops_code_plugins_on_the_server() { + let tmp = tempfile::tempdir().unwrap(); + let bin = tmp.path().join("bin"); + fake_checkstyle(&bin); + let path_var = { + let bin = bin.clone(); + Arc::new(move || Some(bin.clone().into_os_string())) + }; + + // The desktop: Checkstyle and AI Completion installed and granted. + let desktop = + PluginHost::new(tmp.path().join("desktop/plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()) + .unwrap(); + desktop.set_program_path(path_var.clone()); + for name in ["checkstyle", "ai-completion"] { + let info = desktop.install_from_dir(&official(name), &Consent::all()).unwrap(); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + } + + // The server, with the project on "its" disk. + // Canonical, as the UI reports paths (macOS: /var → /private/var). + let project = tmp.path().join("remote/demo"); + std::fs::create_dir_all(project.join("src")).unwrap(); + let project = std::fs::canonicalize(project).unwrap(); + let base = tmp.path().join("server"); + let peer_slot = Arc::new(OnceLock::new()); + let sink_peer = peer_slot.clone(); + let host = Arc::new(Host::new(HostConfig { + config_dir: base.join("config"), + data_dir: base.join("data"), + local_data_dir: base.join("data"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(move |w| rpc::event_sink(sink_peer.clone(), Some(w.to_owned()))), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + })); + let plugins = RemotePlugins::start(&base.join("data"), &host, peer_slot.clone()).unwrap(); + plugins.host().set_program_path(path_var); + let mut dispatcher = Dispatcher::standard(); + plugins.register(&mut dispatcher); + let (client_io, server_io) = tokio::io::duplex(1 << 20); + let (sr, sw) = tokio::io::split(server_io); + tokio::spawn(rpc::serve(host.clone(), dispatcher, peer_slot, sr, sw)); + let (cr, cw) = tokio::io::split(client_io); + let client = Arc::new(Client::default()); + let peer = Peer::connect(cr, cw, client.clone()); + let _: Value = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap(); + invoke(&peer, "open_project", json!({ "path": project })).await.unwrap(); + invoke(&peer, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap(); + + // Digests first; then the files of what the server lacks; then nothing to do. + let first = sync(&peer, &desktop, &[]).await; + assert_eq!(first.missing, ["openidea.ai-completion", "openidea.checkstyle"], "{first:?}"); + let second = sync(&peer, &desktop, &["openidea.ai-completion", "openidea.checkstyle"]).await; + assert_eq!(second.installed.len(), 2, "{second:?}"); + assert!(second.failed.is_empty(), "{second:?}"); + assert_eq!(sync(&peer, &desktop, &[]).await, PackageSyncReport::default()); + let remote = plugins.host().info_of("openidea.checkstyle").unwrap(); + assert_eq!(remote.status, PluginStatus::Inactive, "{:?}", remote.error); + assert!(remote.capabilities.iter().any(|c| c.id == "process:checkstyle" && c.granted)); + + // The remote window's UI routes the run-time commands to the server. + let kinds = invoke(&peer, "plugin_event_kinds", json!({})).await.unwrap(); + assert!(kinds.as_array().unwrap().contains(&json!("file-saved")), "{kinds}"); + + // Saving a file that exists only on the server: Checkstyle reads that file. + let java = project.join("src/A.java"); + std::fs::write(&java, "class A {\n\tint x;\n}\n").unwrap(); + let saved = WorkbenchEvent::FileSaved(java.to_string_lossy().into_owned()); + invoke(&peer, "plugin_post_events", json!({ "events": [saved] })).await.unwrap(); + let published = || { + client.events.lock().iter().find_map(|m| match &m.event { + IdeEvent::Diagnostics { path, source, items } if source == "plugin:openidea.checkstyle" => { + Some((path.0.clone(), items.clone())) + } + _ => None, + }) + }; + until("remote checkstyle diagnostics", 20, || published().is_some()).await; + let (path, items) = published().unwrap(); + assert_eq!(path, java); + assert_eq!((items.len(), items[0].range.start.line), (1, 1)); + + // Secrets stay on the desktop: the server asks for them when used. + let secrets = plugins.host().secrets("openidea.ai-completion").unwrap(); + assert_eq!(secrets, [("api-key".to_owned(), true)]); + assert_eq!(client.secret_requests.lock()[0].plugin, "openidea.ai-completion"); + + // A command of a remote plugin, with this window as its client. + invoke( + &peer, + "plugin_run_command", + json!({ "pluginId": "openidea.ai-completion", "commandId": "toggle", "arg": null, "editor": null }), + ) + .await + .unwrap(); + until("the command's notification", 5, || { + client + .plugin_events + .lock() + .iter() + .any(|m| m.window.as_deref() == Some("main") && matches!(m.event, PluginEvent::Notification { .. })) + }) + .await; + + // Disabled on the desktop: gone from the server. + desktop.set_enabled("openidea.checkstyle", false).unwrap(); + let removed = sync(&peer, &desktop, &[]).await; + assert_eq!(removed.removed, ["openidea.checkstyle"]); + assert!(plugins.host().info_of("openidea.checkstyle").is_err()); + plugins.host().shutdown(); +} + +/// CSV Editor and a tool window with a terminal (the `jobs` fixture) in a +/// remote project. The table edits the document on the server; the jobs are +/// the server's `jobs` program's, and the terminal opens in the remote window. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn remote_projects_get_plugin_views_and_custom_editors() { + let tmp = tempfile::tempdir().unwrap(); + let bin = tmp.path().join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + std::fs::write(bin.join("jobs"), "#!/bin/sh\n[ \"$1\" = list ] && echo remote-job\n").unwrap(); + std::fs::set_permissions(bin.join("jobs"), std::fs::Permissions::from_mode(0o755)).unwrap(); + let path_var = { + let bin = bin.clone(); + Arc::new(move || Some(bin.clone().into_os_string())) + }; + let desktop = + PluginHost::new(tmp.path().join("desktop/plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()) + .unwrap(); + desktop.set_program_path(path_var.clone()); + for dir in [official("csv-editor"), fixture("jobs")] { + let info = desktop.install_from_dir(&dir, &Consent::all()).unwrap(); + assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error); + } + + let project = tmp.path().join("remote/demo"); + std::fs::create_dir_all(&project).unwrap(); + let project = std::fs::canonicalize(project).unwrap(); + std::fs::write(project.join("people.csv"), "name,city\nAda,London\n").unwrap(); + let base = tmp.path().join("server"); + let peer_slot = Arc::new(OnceLock::new()); + let sink_peer = peer_slot.clone(); + let host = Arc::new(Host::new(HostConfig { + config_dir: base.join("config"), + data_dir: base.join("data"), + local_data_dir: base.join("data"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(move |w| rpc::event_sink(sink_peer.clone(), Some(w.to_owned()))), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + })); + let plugins = RemotePlugins::start(&base.join("data"), &host, peer_slot.clone()).unwrap(); + plugins.host().set_program_path(path_var); + let mut dispatcher = Dispatcher::standard(); + plugins.register(&mut dispatcher); + let (client_io, server_io) = tokio::io::duplex(1 << 20); + let (sr, sw) = tokio::io::split(server_io); + tokio::spawn(rpc::serve(host.clone(), dispatcher, peer_slot, sr, sw)); + let (cr, cw) = tokio::io::split(client_io); + let client = Arc::new(Client::default()); + let peer = Peer::connect(cr, cw, client.clone()); + let _: Value = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap(); + invoke(&peer, "open_project", json!({ "path": project })).await.unwrap(); + invoke(&peer, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap(); + let report = sync(&peer, &desktop, &["openidea.csv-editor", "jobs"]).await; + assert_eq!(report.installed.len(), 2, "{report:?}"); + + // CSV Editor: the document is the server's. + let opened = invoke(&peer, "doc_open", json!({ "path": project.join("people.csv") })).await.unwrap(); + let doc = opened["id"].as_u64().expect("doc id"); + let args = |extra: Value| { + let mut a = json!({ "pluginId": "openidea.csv-editor", "view": "table", "doc": doc }); + a.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + a + }; + let view = + invoke(&peer, "plugin_view_render", args(json!({ "viewport": { "firstRow": 0, "rows": 50 } }))).await.unwrap(); + assert_eq!(view["body"]["kind"], "table"); + assert_eq!(view["body"]["value"]["rows"], json!([["Ada", "London"]])); + let cell = json!({ "event": { "kind": "cell", "row": 0, "column": 1, "value": "Oslo" } }); + invoke(&peer, "plugin_view_event", args(cell)).await.unwrap(); + let snap = invoke(&peer, "doc_snapshot", json!({ "doc": doc })).await.unwrap(); + assert_eq!(snap["text"], "name,city\nAda,Oslo\n"); + + // Jobs: the server's program; the terminal opens in this window. + let jobs = |event: Value| json!({ "pluginId": "jobs", "view": "jobs", "doc": null, "event": event }); + let view = + invoke(&peer, "plugin_view_render", json!({ "pluginId": "jobs", "view": "jobs", "doc": null })).await.unwrap(); + assert_eq!(view["body"]["value"][0]["label"], "remote-job", "{view}"); + invoke(&peer, "plugin_view_event", jobs(json!({ "kind": "select", "key": "remote-job" }))).await.unwrap(); + invoke(&peer, "plugin_view_event", jobs(json!({ "kind": "button", "id": "follow" }))).await.unwrap(); + until("the job's terminal", 5, || { + client.plugin_events.lock().iter().any(|m| { + m.window.as_deref() == Some("main") + && matches!(&m.event, PluginEvent::OpenTerminal { program, .. } if program.0.starts_with(bin.canonicalize().unwrap())) + }) + }) + .await; + plugins.host().shutdown(); +} diff --git a/crates/ide-http/src/client.rs b/crates/ide-http/src/client.rs index b7b9dfa5..05963a4c 100644 --- a/crates/ide-http/src/client.rs +++ b/crates/ide-http/src/client.rs @@ -35,8 +35,16 @@ pub fn build(proxy: &ProxySettings) -> IdeResult { .with_platform_verifier() .map_err(|e| fail(e.to_string()))? .with_no_client_auth(); + // `localhost` is tried on IPv4 first: local servers (Ollama, dev servers) + // usually listen there, and on Windows a refused `::1` costs ~2 s before + // the system resolver's order falls back. Ports come from the URL. + let loopback = [ + std::net::SocketAddr::from((std::net::Ipv4Addr::LOCALHOST, 0)), + std::net::SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, 0)), + ]; let builder = reqwest::Client::builder() .tls_backend_preconfigured(tls) + .resolve_to_addrs("localhost", &loopback) .connect_timeout(Duration::from_secs(30)) .user_agent(concat!("OpenIDEA-HttpClient/", env!("CARGO_PKG_VERSION"))); with_proxy(builder, proxy).build().map_err(|e| fail(e.to_string())) @@ -113,7 +121,11 @@ mod tests { /// A one-shot HTTP server on loopback: answers `200` and hands back the request head. fn server() -> (u16, std::thread::JoinHandle) { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + server_on("127.0.0.1:0") + } + + fn server_on(addr: &str) -> (u16, std::thread::JoinHandle) { + let listener = TcpListener::bind(addr).unwrap(); let port = listener.local_addr().unwrap().port(); let handle = std::thread::spawn(move || { let (stream, _) = listener.accept().unwrap(); @@ -141,6 +153,21 @@ mod tests { check_connection(proxy, url, &CancellationToken::new()).await } + /// `localhost` reaches a server on either loopback address. + #[tokio::test] + async fn localhost_reaches_ipv4_and_ipv6_servers() { + let direct = ProxySettings::default(); + let (port, v4) = server(); + assert_eq!(get(&direct, &format!("http://localhost:{port}/")).await.unwrap(), "200 OK"); + v4.join().unwrap(); + // Hosts without IPv6 loopback skip this half. + if TcpListener::bind("[::1]:0").is_ok() { + let (port, v6) = server_on("[::1]:0"); + assert_eq!(get(&direct, &format!("http://localhost:{port}/")).await.unwrap(), "200 OK"); + v6.join().unwrap(); + } + } + #[tokio::test] async fn builds_for_every_mode() { for mode in [ProxyMode::None, ProxyMode::Auto, ProxyMode::Manual] { diff --git a/crates/ide-language/Cargo.toml b/crates/ide-language/Cargo.toml index b830b706..4bda809a 100644 --- a/crates/ide-language/Cargo.toml +++ b/crates/ide-language/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true [dependencies] ide-core.workspace = true +ide-extension.workspace = true ide-text.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/crates/ide-language/src/lib.rs b/crates/ide-language/src/lib.rs index bd4fa6d5..cef38d97 100644 --- a/crates/ide-language/src/lib.rs +++ b/crates/ide-language/src/lib.rs @@ -8,16 +8,20 @@ use ide_core::{LanguageId, Range, SymbolKind}; use serde::{Deserialize, Serialize}; use specta::Type; use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; mod markers; +pub mod plugin_point; mod registry; mod syntax; pub use markers::marked_root; +pub use plugin_point::PluginLanguages; pub use registry::{FileTypes, LanguageRegistry}; pub use syntax::{ - CSS_CLASS, CSS_ID, CSS_VARIABLE, ConfigurationKey, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, - MAX_PARSE_BYTES, ParsedTree, SpellingKind, SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats, - SyntaxHighlightKind, SyntaxHighlights, TreeError, WebReference, WebReferenceKind, merge_visibility, + CSS_CLASS, CSS_ID, CSS_VARIABLE, ConfigurationKey, ExternalFold, ExternalSymbol, ExternalSyntax, ExternalToken, + FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, SpellingKind, SpellingRegion, + Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError, WebReference, + WebReferenceKind, merge_visibility, set_external_syntax, }; /// Parsed form of `languages/.toml`. Backend-only; the UI gets [`LanguageInfo`]. @@ -138,6 +142,9 @@ pub struct LanguageServerConfig { /// Register source files with tsserver when no project configuration exists. #[serde(default)] pub tsserver_project: bool, + /// Set on plugin languages: start exactly this approved program. + #[serde(skip)] + pub pinned: Option, } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -157,6 +164,41 @@ pub struct DebuggerConfig { pub connect: Option, #[serde(default)] pub install_hint: Option, + /// Set on plugin languages: start exactly this approved program. + #[serde(skip)] + pub pinned: Option, +} + +/// The program a plugin's `process:` grant approved: +/// a plugin language's server or debug adapter starts from this exact path, +/// and only while the file still has the approved content. Set by the plugin +/// host, never read from a definition. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ProgramPin { + pub path: PathBuf, + /// blake3 of the file when approved. + pub hash: String, +} + +impl ProgramPin { + /// Approves `path` as it is now. + pub fn approve(path: impl Into) -> std::io::Result { + let path = path.into(); + let hash = ide_extension::ledger::file_hash(&path)?; + Ok(Self { path, hash }) + } + + /// Checks the file right before it is started; the error tells the user what to do. + pub fn verify(&self) -> Result<&Path, String> { + match ide_extension::ledger::file_hash(&self.path) { + Ok(hash) if hash == self.hash => Ok(&self.path), + Ok(_) => Err(format!( + "{} changed since it was approved; review the plugin's permissions in Settings › Plugins", + self.path.display() + )), + Err(e) => Err(format!("{}: {e}", self.path.display())), + } + } } fn default_transport() -> String { diff --git a/crates/ide-language/src/plugin_point.rs b/crates/ide-language/src/plugin_point.rs new file mode 100644 index 00000000..b6558ff1 --- /dev/null +++ b/crates/ide-language/src/plugin_point.rs @@ -0,0 +1,294 @@ +//! The `languages` extension point: language definitions contributed by +//! plugins, in the same format as `languages/.toml`. +//! +//! ```toml +//! [[contributes.languages]] +//! path = "languages/solidity.toml" +//! ``` +//! +//! A definition that starts programs (`language-servers.command`, +//! `debugger.command`) needs `process:` for each: a declaration is a +//! capability too, or registering languages would bypass the sandbox. +//! Committed definitions live in [`PluginLanguages`], an overlay over the +//! built-in registry (built-in definitions win on id clashes): see +//! [`crate::LanguageRegistry::attach_plugins`]. A server or debugger whose +//! program is not granted is left out; the language itself still works. + +use crate::{LanguageConfig, ProgramPin}; +use ide_extension::{Capability, Disposable, ExtensionPoint, Package, Placement, Prepared, decode}; +use parking_lot::RwLock; +use serde::Deserialize; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +pub const POINT_ID: &str = "languages"; + +/// Decides whether a plugin may start a program: the approved file for a +/// granted `process:` capability, or `None`. +pub type ProcessPolicy = dyn Fn(&str, &Capability) -> Option + Send + Sync; + +/// Languages of enabled plugins, in commit order. +#[derive(Default)] +pub struct PluginLanguages { + items: RwLock>, + seq: AtomicU64, + revision: AtomicU64, + policy: RwLock>>, +} + +impl PluginLanguages { + pub fn new() -> Arc { + Arc::new(Self::default()) + } + + pub fn all(&self) -> Vec { + self.items.read().iter().map(|(_, _, c)| c.clone()).collect() + } + + /// `(plugin id, definition)` pairs. + pub fn with_owners(&self) -> Vec<(String, LanguageConfig)> { + self.items.read().iter().map(|(_, p, c)| (p.clone(), c.clone())).collect() + } + + /// The plugin that contributes language `id`. + pub fn owner_of(&self, id: &ide_core::LanguageId) -> Option { + self.items.read().iter().find(|(_, _, c)| &c.id == id).map(|(_, p, _)| p.clone()) + } + + /// Changes whenever [`effective`](Self::effective) may give something else. + pub fn revision(&self) -> u64 { + self.revision.load(Ordering::Acquire) + } + + /// Who may start what. Without a policy no plugin program starts. + pub fn set_process_policy(&self, policy: Arc) { + *self.policy.write() = Some(policy); + self.invalidate(); + } + + /// Grants changed: registries recompute [`effective`](Self::effective). + pub fn invalidate(&self) { + self.revision.fetch_add(1, Ordering::Release); + } + + /// The definitions as they take effect: servers and the debugger whose + /// program is granted are pinned to the approved file, the others are + /// left out. + pub fn effective(&self) -> Vec { + let policy = self.policy.read().clone(); + let pin = |plugin: &str, program: &str| { + policy.as_ref().and_then(|p| p(plugin, &Capability::Process(program.to_owned()))) + }; + self.items + .read() + .iter() + .map(|(_, plugin, cfg)| { + let mut cfg = cfg.clone(); + cfg.language_servers.retain_mut(|s| { + s.pinned = pin(plugin, &s.command); + s.pinned.is_some() + }); + let debugger_pin = cfg.debugger.as_ref().and_then(|d| pin(plugin, &d.command)); + match (&mut cfg.debugger, debugger_pin) { + (Some(d), Some(p)) => d.pinned = Some(p), + (debugger, _) => *debugger = None, + } + cfg + }) + .collect() + } + + /// Adds a definition until the returned handle is dropped. + pub fn add(self: &Arc, plugin: String, cfg: LanguageConfig) -> Disposable { + let seq = self.seq.fetch_add(1, Ordering::Relaxed); + self.items.write().push((seq, plugin, cfg)); + self.revision.fetch_add(1, Ordering::Release); + let weak = Arc::downgrade(self); + Disposable::new(move || { + if let Some(this) = weak.upgrade() { + this.items.write().retain(|(s, _, _)| *s != seq); + this.revision.fetch_add(1, Ordering::Release); + } + }) + } +} + +pub struct LanguagesPoint { + store: Arc, +} + +impl LanguagesPoint { + pub fn new(store: Arc) -> Self { + Self { store } + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Decl { + /// A `languages/.toml`-style file in the package. + path: PathBuf, +} + +/// Parses and checks one language definition. +pub fn parse_definition(src: &str) -> Result { + let cfg: LanguageConfig = toml::from_str(src).map_err(|e| format!("invalid language definition: {e}"))?; + validate_definition(&cfg)?; + Ok(cfg) +} + +/// Checks a definition that did not come from a package file (a remote sync). +pub fn validate_definition(cfg: &LanguageConfig) -> Result<(), String> { + let id = cfg.id.as_str(); + if id.is_empty() || cfg.name.trim().is_empty() { + return Err("language `id` and `name` must not be empty".into()); + } + if !id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '+')) || id.len() > 64 { + return Err(format!("invalid language id {id:?}")); + } + if let Some(first) = &cfg.first_line { + regex_lite::Regex::new(first).map_err(|e| format!("invalid first-line pattern: {e}"))?; + } + Ok(()) +} + +/// The programs a definition starts, as `process:` capabilities. +pub fn required_capabilities(cfg: &LanguageConfig) -> Vec { + let mut caps: Vec = Vec::new(); + let servers = cfg.language_servers.iter().map(|s| s.command.as_str()); + for program in servers.chain(cfg.debugger.iter().map(|d| d.command.as_str())) { + let cap = Capability::Process(program.to_owned()); + if !program.trim().is_empty() && !caps.contains(&cap) { + caps.push(cap); + } + } + caps +} + +impl ExtensionPoint for LanguagesPoint { + fn id(&self) -> &'static str { + POINT_ID + } + + fn placement(&self) -> Placement { + Placement::Workspace + } + + fn prepare(&self, pkg: &Package, decl: toml::Value) -> Result { + let decl: Decl = decode(POINT_ID, decl)?; + let src = pkg.read_text(&decl.path)?; + let cfg = parse_definition(&src).map_err(|e| format!("{}: {e}", decl.path.display()))?; + let caps = required_capabilities(&cfg); + let (store, plugin, key, label) = ( + self.store.clone(), + pkg.id().to_owned(), + cfg.id.to_string(), + format!("{} (.{})", cfg.name, cfg.extensions.join(", .")), + ); + let mut prepared = Prepared::new(label, move || Ok(store.add(plugin, cfg))).key(key).file(decl.path); + for cap in caps { + prepared = prepared.capability(cap); + } + Ok(prepared) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ide_extension::{ExtensionRegistry, Manifest}; + + #[test] + fn languages_point_registers_and_requires_process_capabilities() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::create_dir(tmp.path().join("l")).unwrap(); + std::fs::write( + tmp.path().join("l/sol.toml"), + "id = \"solidity\"\nname = \"Solidity\"\nextensions = [\"sol\"]\n\ + [[language-servers]]\nname = \"solc\"\ncommand = \"solc\"\nargs = [\"--lsp\"]\n", + ) + .unwrap(); + let src = "id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\n\ + [[contributes.languages]]\npath = \"l/sol.toml\""; + let pkg = Package::new(Manifest::parse(src).unwrap(), tmp.path().to_path_buf()); + let store = PluginLanguages::new(); + let reg = ExtensionRegistry::new(); + reg.register(Arc::new(LanguagesPoint::new(store.clone()))).unwrap(); + let set = reg.prepare(&pkg).unwrap(); + assert_eq!(set.capabilities, [Capability::Process("solc".into())]); + assert_eq!(set.files, [PathBuf::from("l/sol.toml")]); + reg.commit(set).unwrap(); + assert_eq!(store.all()[0].id.as_str(), "solidity"); + reg.dispose_plugin("p"); + assert!(store.all().is_empty()); + + let bad = |def: &str| parse_definition(def).unwrap_err(); + assert!(bad("not toml [").contains("invalid language")); + assert!(bad("id = \"\"\nname = \"x\"").contains("must not be empty")); + assert!(bad("id = \"a b\"\nname = \"x\"").contains("invalid language id")); + } + + #[test] + fn registry_overlay_follows_the_store_and_the_grants() { + use crate::LanguageRegistry; + use ide_core::LanguageId; + use std::path::Path; + + let base = LanguageRegistry::load(None).unwrap(); + let store = PluginLanguages::new(); + base.attach_plugins(store.clone()); + // Projects fork before plugins load: the fork follows the store anyway. + let project = base.fork(); + assert_eq!(project.detect(Path::new("a.sol"), None), LanguageId::plain_text()); + + let sol = parse_definition( + "id = \"solidity\"\nname = \"Solidity\"\nextensions = [\"sol\"]\n\ + [[language-servers]]\nname = \"solc\"\ncommand = \"solc\"\n\ + [debugger]\nadapter = \"soldbg\"\ncommand = \"soldbg\"\n", + ) + .unwrap(); + let rust_clash = parse_definition("id = \"rust\"\nname = \"Evil Rust\"\nextensions = [\"rs\"]").unwrap(); + let ext_clash = parse_definition( + "id = \"rusty\"\nname = \"Rusty\"\nextensions = [\"rs\", \"rsy\"]\nfilenames = [\"Cargo.lock\"]", + ) + .unwrap(); + let _sol = store.add("acme.sol".into(), sol); + let _clash = store.add("acme.evil".into(), rust_clash); + let _ext = store.add("acme.evil".into(), ext_clash); + + assert_eq!(project.detect(Path::new("a.sol"), None).as_str(), "solidity"); + let rust = project.get(&LanguageId::new("rust")).unwrap(); + assert_eq!(rust.name, "Rust", "built-in definitions win on id clashes"); + assert_eq!(project.detect(Path::new("main.rs"), None).as_str(), "rust", "and keep their extensions"); + assert_ne!(project.detect(Path::new("Cargo.lock"), None).as_str(), "rusty", "and file names"); + assert_eq!(project.detect(Path::new("x.rsy"), None).as_str(), "rusty"); + // No policy: the language works, its programs do not start. + let cfg = project.get(&LanguageId::new("solidity")).unwrap(); + assert!(cfg.language_servers.is_empty() && cfg.debugger.is_none()); + + let pin = ProgramPin { path: "/opt/solc".into(), hash: "h".into() }; + let granted = pin.clone(); + store.set_process_policy(Arc::new(move |plugin, cap| { + (plugin == "acme.sol" && *cap == Capability::Process("solc".into())).then(|| granted.clone()) + })); + let cfg = project.get(&LanguageId::new("solidity")).unwrap(); + assert_eq!(cfg.language_servers[0].pinned.as_ref(), Some(&pin)); + assert!(cfg.debugger.is_none(), "soldbg was not granted"); + + drop(_sol); + assert_eq!(project.detect(Path::new("a.sol"), None), LanguageId::plain_text()); + assert!(base.get(&LanguageId::new("solidity")).is_none()); + } + + #[test] + fn program_pins_check_the_file() { + let tmp = tempfile::tempdir().unwrap(); + let bin = tmp.path().join("tool"); + std::fs::write(&bin, "v1").unwrap(); + let pin = ProgramPin { path: bin.clone(), hash: ide_extension::ledger::file_hash(&bin).unwrap() }; + assert_eq!(pin.verify().unwrap(), bin); + std::fs::write(&bin, "v2").unwrap(); + assert!(pin.verify().unwrap_err().contains("changed since it was approved")); + } +} diff --git a/crates/ide-language/src/registry.rs b/crates/ide-language/src/registry.rs index 34caf951..83264595 100644 --- a/crates/ide-language/src/registry.rs +++ b/crates/ide-language/src/registry.rs @@ -1,10 +1,11 @@ use crate::LanguageConfig; +use crate::plugin_point::PluginLanguages; use ide_core::settings::{FileSettings, FileTypeAssociation}; use ide_core::{IdeError, IdeResult, LanguageId}; use parking_lot::RwLock; use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; /// Built-in definitions, embedded at compile time. Add new languages here. const BUILTIN: &[(&str, &str)] = &[ @@ -88,12 +89,22 @@ const BUILTIN: &[(&str, &str)] = &[ ]; pub struct LanguageRegistry { - languages: Vec, - /// Lookup tables of the definitions with the user's file types applied. - tables: RwLock>, + /// Built-in definitions and the user's `languages/*.toml`. + base: Vec, + /// Languages of enabled plugins, shared by every fork; `base` wins on id clashes. + plugins: OnceLock>, + state: RwLock>, file_types: RwLock, } +/// The effective definitions and their lookup tables (the user's file types applied). +struct State { + languages: Vec, + tables: Tables, + /// [`PluginLanguages::revision`] they were built from. + plugins_revision: u64, +} + /// The user's file type associations (Settings › Editor › File Types) and /// per-file overrides (Override File Type), resolved for one project. #[derive(Clone, Debug, Default, PartialEq)] @@ -247,12 +258,73 @@ impl LanguageRegistry { } } let tables = Tables::build(&languages, &FileTypes::default()); - Self { languages, tables: RwLock::new(Arc::new(tables)), file_types: RwLock::default() } + let state = State { languages: languages.clone(), tables, plugins_revision: 0 }; + Self { + base: languages, + plugins: OnceLock::new(), + state: RwLock::new(Arc::new(state)), + file_types: RwLock::default(), + } + } + + /// Adds the languages of enabled plugins (once, before projects fork the + /// registry). They follow the store: installing, disabling or changing a + /// grant takes effect on the next lookup in every fork. + pub fn attach_plugins(&self, plugins: Arc) { + if self.plugins.set(plugins).is_err() { + tracing::warn!("plugin languages are already attached"); + } } /// A registry with the same definitions and no user file types (one per project). pub fn fork(&self) -> Self { - Self::from_configs(self.languages.clone()) + let fork = Self::from_configs(self.base.clone()); + if let Some(p) = self.plugins.get() { + let _ = fork.plugins.set(p.clone()); + } + fork + } + + /// The current effective state, rebuilt when the plugin languages changed. + fn state(&self) -> Arc { + let Some(plugins) = self.plugins.get() else { return self.state.read().clone() }; + let revision = plugins.revision(); + { + let state = self.state.read(); + if state.plugins_revision == revision { + return state.clone(); + } + } + let file_types = self.file_types.read(); + let mut state = self.state.write(); + if state.plugins_revision != revision { + *state = Arc::new(self.build(&file_types, Some(revision))); + } + state.clone() + } + + fn build(&self, file_types: &FileTypes, revision: Option) -> State { + let mut languages = self.base.clone(); + let mut plugins_revision = 0; + if let Some(plugins) = self.plugins.get() { + plugins_revision = revision.unwrap_or_else(|| plugins.revision()); + // A plugin adds languages; it can't take over a built-in or user + // definition's id, extensions or file names (File Types can). + let base_ext: std::collections::HashSet = + self.base.iter().flat_map(|l| &l.extensions).map(|e| e.to_ascii_lowercase()).collect(); + let base_names: std::collections::HashSet<&str> = + self.base.iter().flat_map(|l| &l.filenames).map(String::as_str).collect(); + for mut cfg in plugins.effective() { + if languages.iter().any(|l| l.id == cfg.id) { + continue; + } + cfg.extensions.retain(|e| !base_ext.contains(&e.to_ascii_lowercase())); + cfg.filenames.retain(|n| !base_names.contains(n.as_str())); + languages.push(cfg); + } + } + let tables = Tables::build(&languages, file_types); + State { languages, tables, plugins_revision } } /// A copy with the same definitions and file types (to compare detection before / after a change). @@ -268,17 +340,19 @@ impl LanguageRegistry { if *current == file_types { return false; } - *self.tables.write() = Arc::new(Tables::build(&self.languages, &file_types)); + let state = self.build(&file_types, None); + *self.state.write() = Arc::new(state); *current = file_types; true } + /// Built-in, user and plugin definitions. pub fn all(&self) -> Vec { - self.languages.clone() + self.state().languages.clone() } pub fn get(&self, id: &LanguageId) -> Option { - self.languages.iter().find(|l| &l.id == id).cloned() + self.state().languages.iter().find(|l| &l.id == id).cloned() } /// The `framework-ui-modes` mode of a `language` file at `path`: the first @@ -286,7 +360,8 @@ impl LanguageRegistry { /// directory without one: loose files). `None` keeps the language's own /// `ui-mode`. pub fn framework_ui_mode(&self, language: &LanguageId, path: &Path, project_root: Option<&Path>) -> Option { - let cfg = self.languages.iter().find(|l| &l.id == language)?; + let state = self.state(); + let cfg = state.languages.iter().find(|l| &l.id == language)?; cfg.framework_ui_modes .iter() .find(|f| crate::marked_root(project_root, path, &f.root_markers).is_some()) @@ -296,7 +371,8 @@ impl LanguageRegistry { /// Creating or removing `path` can change a file's `framework_ui_mode`: /// it is a framework's root marker. pub fn is_framework_marker(&self, path: &Path) -> bool { - self.languages + self.state() + .languages .iter() .flat_map(|l| &l.framework_ui_modes) .any(|f| f.root_markers.iter().any(|m| crate::markers::is_marker_path(path, m))) @@ -307,33 +383,34 @@ impl LanguageRegistry { /// then hashbang / first line; falls back to plaintext. The user's patterns /// win over the definitions'. pub fn detect(&self, path: &Path, first_line: Option<&str>) -> LanguageId { - let t = self.tables.read().clone(); + let state = self.state(); + let (t, languages) = (&state.tables, &state.languages); if !t.overrides.is_empty() && let Some(&i) = t.overrides.get(path) { - return self.languages[i].id.clone(); + return languages[i].id.clone(); } let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default(); if let Some(&i) = t.by_name.get(file_name) { - return self.languages[i].id.clone(); + return languages[i].id.clone(); } if let Some((_, i)) = t.name_globs.iter().find(|(p, _)| wildcard_match(p, file_name)) { - return self.languages[*i].id.clone(); + return languages[*i].id.clone(); } let lower = file_name.to_ascii_lowercase(); let mut rest = lower.as_str(); while let Some(dot) = rest.find('.') { rest = &rest[dot + 1..]; if let Some(&i) = t.by_ext.get(rest) { - return self.languages[i].id.clone(); + return languages[i].id.clone(); } } if let Some(line) = first_line { if let Some((_, i)) = t.hashbangs.iter().find(|(h, _)| hashbang_runs(line, h)) { - return self.languages[*i].id.clone(); + return languages[*i].id.clone(); } if let Some((_, i)) = t.first_line.iter().find(|(re, _)| re.is_match(line)) { - return self.languages[*i].id.clone(); + return languages[*i].id.clone(); } } LanguageId::plain_text() diff --git a/crates/ide-language/src/syntax/cache.rs b/crates/ide-language/src/syntax/cache.rs index 038ace1c..393eb752 100644 --- a/crates/ide-language/src/syntax/cache.rs +++ b/crates/ide-language/src/syntax/cache.rs @@ -197,6 +197,7 @@ impl SyntaxCache { let query = g.outline_query()?; Some(outline::outline(g, query, tree, text)) }) + .or_else(|| super::external::outline(lang, text)) }, ) } @@ -211,6 +212,7 @@ impl SyntaxCache { self.with_tree(doc, lang, version, text, |g, tree, text| { Some(folding::folding(g.spec, g.kinds(), tree, text, self.syntax.comment_tokens(lang))) }) + .or_else(|| super::external::folding(lang, text)) .or_else(|| Some(self.syntax.custom_folding(lang, text))) }, ) @@ -227,6 +229,7 @@ impl SyntaxCache { self.with_tree(doc, lang, version, text, |g, tree, text| { Some(highlight::highlights(g.highlight_query()?, tree, text)) }) + .or_else(|| super::external::highlights(lang, text)) }, )) } diff --git a/crates/ide-language/src/syntax/external.rs b/crates/ide-language/src/syntax/external.rs new file mode 100644 index 00000000..6399a2f0 --- /dev/null +++ b/crates/ide-language/src/syntax/external.rs @@ -0,0 +1,239 @@ +//! Syntax from outside this crate for languages without a built-in grammar: a +//! plugin's `syntax-provider`. Providers return flat +//! results in UTF-8 byte offsets; they are validated and converted here into +//! the same [`OutlineItem`], [`FoldRange`] and highlight data the grammars +//! produce, so the editor can't tell the difference. Results are memoized per +//! document version by the [`super::SyntaxCache`] like the grammars' answers. + +use super::highlight::SyntaxHighlightKind; +use super::lines::LineIndex; +use crate::{FoldKind, FoldRange}; +use ide_core::{LanguageId, OutlineItem, SymbolKind}; +use parking_lot::RwLock; +use std::sync::Arc; + +/// A highlighted range (UTF-8 byte offsets); `kind` is a kebab-case +/// [`SyntaxHighlightKind`] name. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExternalToken { + pub start: u32, + pub end: u32, + pub kind: String, +} + +/// A structure-view symbol (UTF-8 byte offsets); `parent` indexes an earlier +/// symbol of the same list. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExternalSymbol { + pub name: String, + pub detail: Option, + pub kind: String, + pub start: u32, + pub end: u32, + pub name_start: u32, + pub name_end: u32, + pub parent: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExternalFold { + pub start_line: u32, + pub end_line: u32, + pub kind: String, +} + +/// Answers for languages it provides, `None` for the others. +pub trait ExternalSyntax: Send + Sync { + fn highlights(&self, lang: &LanguageId, text: &str) -> Option>; + fn outline(&self, lang: &LanguageId, text: &str) -> Option>; + fn folding(&self, lang: &LanguageId, text: &str) -> Option>; +} + +static PROVIDER: RwLock>> = RwLock::new(None); + +/// Installs (or removes) the provider every project's syntax cache consults. +pub fn set_external_syntax(provider: Option>) { + *PROVIDER.write() = provider; +} + +fn provider() -> Option> { + PROVIDER.read().clone() +} + +fn clamp(text: &str, offset: u32) -> usize { + let mut at = (offset as usize).min(text.len()); + while !text.is_char_boundary(at) { + at -= 1; + } + at +} + +/// `[from, to, kind]` triples in UTF-16 offsets, sorted and non-overlapping. +pub(crate) fn highlights(lang: &LanguageId, text: &str) -> Option> { + let mut tokens = provider()?.highlights(lang, text)?; + tokens.sort_by_key(|t| (t.start, t.end)); + let lines = LineIndex::new(text); + let mut data = Vec::with_capacity(tokens.len() * 3); + let mut covered = 0usize; + for t in tokens { + let Some(kind) = SyntaxHighlightKind::from_name(&t.kind) else { continue }; + let (start, end) = (clamp(text, t.start), clamp(text, t.end)); + if end <= start || start < covered { + continue; + } + covered = end; + let index = SyntaxHighlightKind::ALL.iter().position(|k| *k == kind).unwrap_or_default() as u32; + data.extend([lines.utf16_at(start) as u32, lines.utf16_at(end) as u32, index]); + } + Some(data) +} + +fn symbol_kind(name: &str) -> SymbolKind { + let camel: String = { + let mut out = String::with_capacity(name.len()); + let mut upper = false; + for c in name.chars() { + if c == '-' { + upper = true; + } else if upper { + out.push(c.to_ascii_uppercase()); + upper = false; + } else { + out.push(c); + } + } + out + }; + serde_json::from_value(serde_json::Value::String(camel)).unwrap_or(SymbolKind::Unknown) +} + +pub(crate) fn outline(lang: &LanguageId, text: &str) -> Option> { + let symbols = provider()?.outline(lang, text)?; + let lines = LineIndex::new(text); + // Built bottom-up: children are attached to their parent (an earlier index). + let mut items: Vec> = Vec::with_capacity(symbols.len()); + let mut parents: Vec> = Vec::with_capacity(symbols.len()); + for (i, s) in symbols.iter().enumerate() { + let (start, end) = (clamp(text, s.start), clamp(text, s.end.max(s.start))); + let name_start = clamp(text, s.name_start).clamp(start, end); + let name_end = clamp(text, s.name_end).clamp(name_start, end); + items.push(Some(OutlineItem { + name: s.name.clone(), + detail: s.detail.clone(), + kind: symbol_kind(&s.kind), + range: lines.range(start, end), + selection_range: lines.range(name_start, name_end), + children: Vec::new(), + visibility: None, + })); + parents.push(s.parent.map(|p| p as usize).filter(|&p| p < i)); + } + for i in (0..items.len()).rev() { + if let Some(p) = parents[i] { + let child = items[i].take().expect("each item is moved once"); + if let Some(parent) = items[p].as_mut() { + parent.children.insert(0, child); + } + } + } + Some(items.into_iter().flatten().collect()) +} + +pub(crate) fn folding(lang: &LanguageId, text: &str) -> Option> { + let folds = provider()?.folding(lang, text)?; + let last_line = LineIndex::new(text).line_of(text.len()) as u32; + let mut out: Vec = folds + .into_iter() + .filter(|f| f.start_line < f.end_line && f.end_line <= last_line) + .map(|f| FoldRange { + start_line: f.start_line, + end_line: f.end_line, + kind: match f.kind.as_str() { + "comment" => FoldKind::Comment, + "imports" => FoldKind::Imports, + _ => FoldKind::Region, + }, + }) + .collect(); + out.sort_by_key(|f| (f.start_line, std::cmp::Reverse(f.end_line))); + out.dedup_by_key(|f| (f.start_line, f.end_line)); + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + struct Fake; + + impl ExternalSyntax for Fake { + fn highlights(&self, lang: &LanguageId, _: &str) -> Option> { + (lang.as_str() == "fake").then(|| { + vec![ + ExternalToken { start: 9, end: 12, kind: "keyword".into() }, + // "é" is 2 bytes, 1 UTF-16 unit. + ExternalToken { start: 0, end: 6, kind: "string".into() }, + ExternalToken { start: 2, end: 4, kind: "number".into() }, // overlaps: dropped + ExternalToken { start: 13, end: 14, kind: "nonsense".into() }, + ExternalToken { start: 7, end: 99, kind: "doc-comment".into() }, + ] + }) + } + fn outline(&self, lang: &LanguageId, _: &str) -> Option> { + let sym = |name: &str, kind: &str, start, end, parent| ExternalSymbol { + name: name.into(), + detail: None, + kind: kind.into(), + start, + end, + name_start: start, + name_end: start + 1, + parent, + }; + (lang.as_str() == "fake").then(|| { + vec![ + sym("C", "class", 0, 14, None), + sym("f", "function", 8, 12, Some(0)), + sym("g", "event", 12, 13, Some(0)), + sym("bad", "method", 1, 2, Some(9)), + ] + }) + } + fn folding(&self, lang: &LanguageId, _: &str) -> Option> { + (lang.as_str() == "fake").then(|| { + vec![ + ExternalFold { start_line: 0, end_line: 1, kind: "comment".into() }, + ExternalFold { start_line: 1, end_line: 1, kind: "region".into() }, + ExternalFold { start_line: 0, end_line: 9, kind: "region".into() }, + ] + }) + } + } + + #[test] + fn converts_and_validates_provider_results() { + set_external_syntax(Some(Arc::new(Fake))); + let text = "\"héllo\"\nfn x(){}"; + let lang = LanguageId::new("fake"); + assert!(highlights(&LanguageId::new("other"), text).is_none()); + let data = highlights(&lang, text).unwrap(); + let string = SyntaxHighlightKind::ALL.iter().position(|k| *k == SyntaxHighlightKind::String).unwrap() as u32; + let doc = SyntaxHighlightKind::ALL.iter().position(|k| *k == SyntaxHighlightKind::DocComment).unwrap() as u32; + // UTF-16: `"héllo"` is 7 units (bytes 0..8 → 0..7); byte 6 is inside "o\"" → 5. + assert_eq!(&data[..3], &[0, 5, string]); + assert_eq!(&data[3..], &[6, 16, doc], "clamped to the text, keyword dropped as overlapping"); + + let outline = outline(&lang, text).unwrap(); + assert_eq!(outline.len(), 2, "orphan with a bad parent stays top-level"); + assert_eq!(outline[0].kind, SymbolKind::Class); + assert_eq!( + outline[0].children.iter().map(|c| c.kind).collect::>(), + [SymbolKind::Function, SymbolKind::Event] + ); + assert_eq!(outline[1].kind, SymbolKind::Method); + + let folds = folding(&lang, text).unwrap(); + assert_eq!(folds, [FoldRange { start_line: 0, end_line: 1, kind: FoldKind::Comment }]); + set_external_syntax(None); + } +} diff --git a/crates/ide-language/src/syntax/highlight.rs b/crates/ide-language/src/syntax/highlight.rs index 07c94249..fc43637b 100644 --- a/crates/ide-language/src/syntax/highlight.rs +++ b/crates/ide-language/src/syntax/highlight.rs @@ -72,6 +72,24 @@ impl SyntaxHighlightKind { Self::Operator, Self::Punctuation, ]; + + /// The kebab-case name plugins use (`doc-comment`, `function-call`, …). + pub fn from_name(name: &str) -> Option { + Self::ALL.into_iter().find(|k| { + let camel = serde_json::to_value(k).ok(); + let camel = camel.as_ref().and_then(|v| v.as_str()).unwrap_or_default(); + let mut kebab = String::with_capacity(camel.len() + 2); + for c in camel.chars() { + if c.is_ascii_uppercase() { + kebab.push('-'); + kebab.push(c.to_ascii_lowercase()); + } else { + kebab.push(c); + } + } + kebab == name + }) + } } /// Highlighted ranges of a whole document, packed like LSP semantic tokens. diff --git a/crates/ide-language/src/syntax/mod.rs b/crates/ide-language/src/syntax/mod.rs index e961eb35..8c0c9bf2 100644 --- a/crates/ide-language/src/syntax/mod.rs +++ b/crates/ide-language/src/syntax/mod.rs @@ -2,6 +2,7 @@ mod cache; mod configuration; +mod external; mod folding; mod grammars; mod highlight; @@ -14,6 +15,7 @@ mod web; use crate::{FoldRange, LanguageConfig, LanguageRegistry, SymbolTag}; pub use cache::{MAX_CACHED_TREES, SyntaxCache, SyntaxCacheStats}; pub use configuration::ConfigurationKey; +pub use external::{ExternalFold, ExternalSymbol, ExternalSyntax, ExternalToken, set_external_syntax}; use grammars::{SPECS, Spec}; pub use highlight::{SyntaxHighlightKind, SyntaxHighlights}; use ide_core::{LanguageId, OutlineItem, Pos, Range}; diff --git a/crates/ide-lsp/src/launch.rs b/crates/ide-lsp/src/launch.rs index 5c7d53c0..c8f68f0e 100644 --- a/crates/ide-lsp/src/launch.rs +++ b/crates/ide-lsp/src/launch.rs @@ -96,8 +96,12 @@ impl Launcher for ProcessLauncher { cancel: &CancellationToken, ) -> Result<(Peer, Option), LaunchError> { let search = server_search_path(config); - let binary = ide_core::tool_path::find_command(&config.command, &search, root) - .and_then(|b| resolve_rustup_proxy(&config.command, b)); + let binary = match &config.pinned { + // A plugin's server: the approved program, unchanged since. + Some(pin) => Some(pin.verify().map_err(LaunchError::Failed)?.to_path_buf()), + None => ide_core::tool_path::find_command(&config.command, &search, root) + .and_then(|b| resolve_rustup_proxy(&config.command, b)), + }; let mut env: Vec<(String, String)> = vec![("PATH".into(), search.to_string_lossy().into_owned())]; env.extend(config.env.iter().filter(|(k, _)| *k != "PATH").map(|(k, v)| (k.clone(), v.clone()))); if let Some(addr) = &config.connect { @@ -120,6 +124,9 @@ impl Launcher for ProcessLauncher { } fn available(&self, config: &LanguageServerConfig, root: &Path) -> bool { + if let Some(pin) = &config.pinned { + return pin.path.is_file(); + } ide_core::tool_path::find_command(&config.command, &server_search_path(config), root).is_some() } } diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index 5a600ec8..fef3fb36 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -228,6 +228,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig { max_java: None, launch_error: None, tsserver_project: false, + pinned: None, } } diff --git a/crates/ide-lsp/tests/real_servers.rs b/crates/ide-lsp/tests/real_servers.rs index 7ed98d3b..3bd92275 100644 --- a/crates/ide-lsp/tests/real_servers.rs +++ b/crates/ide-lsp/tests/real_servers.rs @@ -132,6 +132,7 @@ async fn missing_binary_is_reported_with_install_hint() { max_java: None, launch_error: None, tsserver_project: false, + pinned: None, }; let (mgr, events) = manager(dir.path(), LanguageRegistry::from_configs(vec![lang("nope", "nope", server)])); let path = dir.path().join("a.nope"); @@ -398,6 +399,7 @@ async fn typescript_language_server_end_to_end() { max_java: None, launch_error: None, tsserver_project: false, + pinned: None, }; let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![lang("typescript", "ts", server)])); let doc = DocId::next(); @@ -444,6 +446,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option) + Send>; + +/// Why an [`Actor::call`] produced no result. +#[derive(Debug)] +pub enum ActorError { + /// The plugin's own outcome: an error it returned, or a trap (the actor has ended). + Call(CallError), + /// The caller's wait ran out; the result, if any, is dropped. + SoftTimeout, + /// The actor ended (an earlier call trapped, or it was stopped) before running the call. + Stopped, + /// The caller cancelled the call (`call_cancellable`). + Cancelled, +} + +/// A call queued with [`Actor::submit`]. +pub struct Pending { + /// The outcome and when the plugin's thread produced it. + result: mpsc::Receiver<(Result, Instant)>, + give_up: Option, + alive: Arc, +} + +impl Pending { + /// Waits for the outcome, until the call's soft deadline if it has one. A + /// result produced after that deadline is dropped even when it is already + /// there (the caller was not scheduled in time, or waited on another call + /// first), so the deadline holds however busy the machine is; a failure is + /// still reported. + pub fn wait(self) -> Result { + let outcome = match self.give_up { + Some(t) => match self.result.recv_timeout(t.saturating_duration_since(Instant::now())) { + Ok((Ok(_), done)) if done > t => return Err(ActorError::SoftTimeout), + Ok((r, _)) => r, + Err(mpsc::RecvTimeoutError::Timeout) => return Err(ActorError::SoftTimeout), + Err(mpsc::RecvTimeoutError::Disconnected) => { + // Skipped as too late, or the actor ended. + let alive = self.alive.load(Ordering::Acquire); + return Err(if alive { ActorError::SoftTimeout } else { ActorError::Stopped }); + } + }, + None => self.result.recv().map_err(|_| ActorError::Stopped)?.0, + }; + outcome.map_err(ActorError::Call) + } +} + +pub struct Actor { + tx: Mutex>>, + thread: Mutex>>, + cancel: Arc, + alive: Arc, + /// The trap that ended the actor, until someone takes it to report it. + crash: Arc>>, + busy: Arc, + /// Milliseconds since `epoch` at the last call's end. + last_used: Arc, + epoch: Instant, +} + +impl Actor { + /// Moves an activated runtime onto its own thread. + pub fn spawn(name: &str, runtime: Runtime) -> std::io::Result { + let (tx, rx) = mpsc::channel::(); + let cancel = runtime.cancel_handle(); + let alive = Arc::new(AtomicBool::new(true)); + let busy = Arc::new(AtomicBool::new(false)); + let last_used = Arc::new(AtomicU64::new(0)); + let epoch = Instant::now(); + let thread = { + let (alive, busy, last_used) = (alive.clone(), busy.clone(), last_used.clone()); + std::thread::Builder::new().name(format!("plugin:{name}")).spawn(move || { + let mut slot = Some(runtime); + while let Ok(job) = rx.recv() { + busy.store(true, Ordering::Release); + job(&mut slot); + last_used.store(epoch.elapsed().as_millis() as u64, Ordering::Release); + busy.store(false, Ordering::Release); + if slot.is_none() { + break; + } + } + alive.store(false, Ordering::Release); + // Queued jobs are dropped with `rx`: their callers see `Stopped`. + drop(rx); + if let Some(mut rt) = slot { + rt.deactivate(); + } + })? + }; + Ok(Self { + tx: Mutex::new(Some(tx)), + thread: Mutex::new(Some(thread)), + cancel, + alive, + crash: Arc::default(), + busy, + last_used, + epoch, + }) + } + + /// Runs `f` on the plugin's thread. With `wait`, gives up after that long + /// (counting the time queued behind other calls) and the call, if it has + /// not started yet, is skipped. Without, waits for the outcome: the + /// runtime's own deadline bounds it. + pub fn call( + &self, + wait: Option, + f: impl FnOnce(&mut Runtime) -> Result + Send + 'static, + ) -> Result { + self.submit(wait, f)?.wait() + } + + /// Queues `f` like [`call`](Self::call) and returns at once, so a caller + /// can start calls on several plugins and then wait for all of them: the + /// wait is the slowest one's, not the sum. + pub fn submit( + &self, + wait: Option, + f: impl FnOnce(&mut Runtime) -> Result + Send + 'static, + ) -> Result, ActorError> { + let give_up = wait.map(|w| Instant::now() + w); + let (reply, result) = mpsc::sync_channel(1); + let (crash, alive) = (self.crash.clone(), self.alive.clone()); + let job: Job = Box::new(move |slot| { + if give_up.is_some_and(|t| Instant::now() >= t) { + return; + } + let Some(rt) = slot.as_mut() else { return }; + let outcome = f(rt); + if let Err(CallError::Trap(e)) = &outcome { + *crash.lock().unwrap_or_else(|e| e.into_inner()) = Some(e.clone()); + // Before the reply: the caller sees the actor dead. + alive.store(false, Ordering::Release); + *slot = None; + } + let _ = reply.send((outcome, Instant::now())); + }); + { + let tx = self.tx.lock().unwrap_or_else(|e| e.into_inner()); + let Some(tx) = tx.as_ref() else { return Err(ActorError::Stopped) }; + tx.send(job).map_err(|_| ActorError::Stopped)?; + } + Ok(Pending { result, give_up, alive: self.alive.clone() }) + } + + /// Like [`call`](Self::call) without a soft deadline, but `cancel` (the + /// caller's request was superseded) cancels the call cooperatively, and + /// interrupts it if it has not returned `grace` later. Returns + /// [`ActorError::Cancelled`] then. + pub fn call_cancellable( + &self, + cancel: &ide_core::CancellationToken, + grace: Duration, + f: impl FnOnce(&mut Runtime) -> Result + Send + 'static, + ) -> Result { + let (reply, result) = mpsc::sync_channel(1); + let (crash, alive) = (self.crash.clone(), self.alive.clone()); + let skip = cancel.clone(); + let job: Job = Box::new(move |slot| { + if skip.is_cancelled() { + return; + } + let Some(rt) = slot.as_mut() else { return }; + let outcome = f(rt); + if let Err(CallError::Trap(e)) = &outcome { + *crash.lock().unwrap_or_else(|e| e.into_inner()) = Some(e.clone()); + alive.store(false, Ordering::Release); + *slot = None; + } + let _ = reply.send(outcome); + }); + { + let tx = self.tx.lock().unwrap_or_else(|e| e.into_inner()); + let Some(tx) = tx.as_ref() else { return Err(ActorError::Stopped) }; + tx.send(job).map_err(|_| ActorError::Stopped)?; + } + let mut cancelled_at: Option = None; + loop { + match result.recv_timeout(Duration::from_millis(5)) { + Ok(outcome) if cancelled_at.is_some() => { + drop(outcome); + return Err(ActorError::Cancelled); + } + Ok(outcome) => return outcome.map_err(ActorError::Call), + Err(mpsc::RecvTimeoutError::Disconnected) => { + return Err(if cancel.is_cancelled() { ActorError::Cancelled } else { ActorError::Stopped }); + } + Err(mpsc::RecvTimeoutError::Timeout) => {} + } + if !cancel.is_cancelled() { + continue; + } + match cancelled_at { + None => { + cancelled_at = Some(Instant::now()); + if self.is_busy() { + self.cancel.cancel_soft(); + } + } + Some(at) if at.elapsed() >= grace => { + // Did not return in time: interrupt it (the instance is rebuilt). + self.cancel(); + return Err(ActorError::Cancelled); + } + Some(_) => {} + } + } + } + + /// Queues `f` without waiting; `done` gets the outcome on the actor's + /// thread (`Stopped` if the actor ended before running it). + pub fn post( + &self, + f: impl FnOnce(&mut Runtime) -> Result + Send + 'static, + done: impl FnOnce(Result) + Send + 'static, + ) { + let (crash, alive) = (self.crash.clone(), self.alive.clone()); + let job: Job = Box::new(move |slot| { + let Some(rt) = slot.as_mut() else { return done(Err(ActorError::Stopped)) }; + let outcome = f(rt); + if let Err(CallError::Trap(e)) = &outcome { + *crash.lock().unwrap_or_else(|e| e.into_inner()) = Some(e.clone()); + alive.store(false, Ordering::Release); + *slot = None; + } + done(outcome.map_err(ActorError::Call)); + }); + let tx = self.tx.lock().unwrap_or_else(|e| e.into_inner()); + // A job that can't be queued is dropped, and with it `done` (unrun): + // the caller sees the actor dead on its next look. + if let Some(tx) = tx.as_ref() { + let _ = tx.send(job); + } + } + + /// Cooperatively cancels the running call (see [`call_cancellable`](Self::call_cancellable)). + pub fn cancel_soft(&self) { + if self.is_busy() { + self.cancel.cancel_soft(); + } + } + + /// Interrupts the running call (it fails as a trap: the instance is dropped). + pub fn cancel(&self) { + if self.busy.load(Ordering::Acquire) { + self.cancel.cancel(); + } + } + + /// The trap that ended this actor; `Some` only for the first caller, which + /// reports it (also when the caller that saw it had stopped waiting). + pub fn take_crash(&self) -> Option { + self.crash.lock().unwrap_or_else(|e| e.into_inner()).take() + } + + /// The runtime is still usable (no call trapped, not stopped). + pub fn is_alive(&self) -> bool { + self.alive.load(Ordering::Acquire) + } + + pub fn is_busy(&self) -> bool { + self.busy.load(Ordering::Acquire) + } + + /// Time since the last call ended (or since start). + pub fn idle_for(&self) -> Duration { + let last = Duration::from_millis(self.last_used.load(Ordering::Acquire)); + self.epoch.elapsed().saturating_sub(last) + } + + /// Deactivates the plugin and ends the thread after the queued calls. + /// With `join`, waits for that (bounded by the runtime's deadlines). + pub fn stop(&self, join: bool) { + self.tx.lock().unwrap_or_else(|e| e.into_inner()).take(); + if join { + let thread = self.thread.lock().unwrap_or_else(|e| e.into_inner()).take(); + if let Some(t) = thread + && t.thread().id() != std::thread::current().id() + { + let _ = t.join(); + } + } + } +} + +impl Drop for Actor { + fn drop(&mut self) { + self.stop(false); + } +} diff --git a/crates/ide-plugin/src/lib.rs b/crates/ide-plugin/src/lib.rs index dc6a3ed4..fd27cb24 100644 --- a/crates/ide-plugin/src/lib.rs +++ b/crates/ide-plugin/src/lib.rs @@ -1,771 +1,24 @@ -//! Sandboxed WebAssembly plugin host (Zed-style). +//! The WebAssembly runtime for plugins (wasmtime, component model, WASI +//! preview 2). Package handling, extension points and grants live in +//! `ide-extension`; the host that assembles them is `ide-host::plugins`. //! -//! A plugin is a directory with a `plugin.toml` manifest ([`PluginManifest`]) -//! and, optionally, a WebAssembly component implementing the -//! `openidea:plugin/plugin@0.1.0` world (`wit/plugin.wit`). Contribution-only -//! plugins (themes, languages) need no code. -//! -//! Each plugin with code runs in its own wasmtime `Store` with WASI preview 2 -//! (no files, env, network), a fuel budget and wall-clock deadline per call, -//! and a linear-memory cap. A trap (panic, budget exhausted, permission -//! violation) drops the instance and marks the plugin `Failed` for the session; -//! the IDE keeps running. -//! -//! Sources: `//` (installed) and `/.openidea/plugins/*/` -//! (dev plugins, loaded by [`PluginHost::sync_project`]). +//! Each plugin with code runs in its own wasmtime `Store`: no files, env or +//! network beyond what [`HostApi`] grants, a fuel budget and wall-clock +//! deadline per call, and a linear-memory cap. A trap (panic, budget +//! exhausted, permission violation, cancellation) poisons the instance; the +//! host drops it. Each active plugin's runtime lives on its own [`Actor`] thread. -mod manifest; -mod package; +mod actor; mod runtime; mod sandbox; -mod theme; mod types; +mod wit_host; -pub use manifest::{ - API_VERSION, CommandDecl, Contributions, FileDecl, MANIFEST_FILE, Permission, PluginManifest, ThemeDecl, +pub use actor::{Actor, ActorError, Pending}; +pub use runtime::{ + API_VERSION, CANCELLED, CallCancel, CallError, GuestError, HostApi, PluginEngine, Runtime, RuntimeSetup, check_api, + component_api, host_api, }; -pub use sandbox::resolve_in_root; -pub use theme::{ThemeDef, ThemeKind}; +pub use sandbox::{MAX_READ_BYTES, read_text, resolve_in_root}; pub use types::*; - -use ide_core::{IdeError, IdeResult}; -use ide_language::LanguageConfig; -use parking_lot::{Condvar, Mutex, RwLock}; -use runtime::{CallEffects, CallError, PluginEngine, Registrations, Runtime, RuntimeSetup}; -use serde::{Deserialize, Serialize}; -use std::collections::{BTreeMap, BTreeSet, HashMap}; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::time::Duration; - -const STATE_FILE: &str = "state.json"; -/// Top-level files copied with a package on install besides those the manifest references. -const LICENSE_FILES: &[&str] = - &["LICENSE", "LICENSE.md", "LICENSE.txt", "NOTICE", "NOTICE.md", "NOTICE.txt", "COPYING"]; -/// Dev plugins live here, relative to a project root. -pub const DEV_PLUGINS_DIR: &str = ".openidea/plugins"; - -#[derive(Default, Serialize, Deserialize)] -struct PersistedState { - #[serde(default)] - disabled: BTreeSet, - #[serde(default)] - theme: Option, -} - -#[derive(Clone, PartialEq, Serialize, Deserialize)] -struct ThemeRef { - plugin: String, - theme: String, - /// The theme's window frame colour as the UI resolved it (`#rrggbb[aa]`), so - /// new windows open in it before the plugin is loaded. - #[serde(default, skip_serializing_if = "Option::is_none")] - frame: Option, -} - -struct Meta { - status: PluginStatus, - error: Option, -} - -struct LoadedPlugin { - manifest: PluginManifest, - dir: PathBuf, - source: PluginSource, - /// Project that owns a dev plugin. - dev_root: Option, - /// Manifest contributions, restored on every (re)start. - static_regs: Registrations, - registrations: Arc>, - meta: Mutex, - runtime: Mutex>, -} - -impl LoadedPlugin { - fn is_live(&self) -> bool { - matches!(self.meta.lock().status, PluginStatus::Active | PluginStatus::Static) - } - - fn set_failed(&self, error: String) { - let mut meta = self.meta.lock(); - meta.status = PluginStatus::Failed; - meta.error = Some(error); - } -} - -type ProjectPolicy = Arc bool + Send + Sync>; - -pub struct PluginHost { - project_policy: RwLock, - engine: PluginEngine, - plugins_dir: PathBuf, - sink: Arc, - limits: Limits, - plugins: RwLock>>, - state: Mutex, - /// client (window) → path of its focused editor. - active_files: Arc>>, - /// Serializes loading / unloading so concurrent windows can't race. - lifecycle: Mutex<()>, - /// Set once the first [`load_all`](Self::load_all) has finished. - initial_load: (Mutex, Condvar), -} - -impl PluginHost { - /// Creates the host; call [`load_all`](Self::load_all) to load installed plugins. - pub fn new(plugins_dir: PathBuf, sink: Arc, limits: Limits) -> IdeResult { - std::fs::create_dir_all(&plugins_dir)?; - let state = std::fs::read_to_string(plugins_dir.join(STATE_FILE)) - .ok() - .and_then(|s| serde_json::from_str(&s).ok()) - .unwrap_or_default(); - Ok(Self { - project_policy: RwLock::new(Arc::new(|_| false)), - engine: PluginEngine::new().map_err(IdeError::internal)?, - plugins_dir, - sink, - limits, - plugins: RwLock::default(), - state: Mutex::new(state), - active_files: Arc::default(), - lifecycle: Mutex::new(()), - initial_load: (Mutex::new(false), Condvar::new()), - }) - } - - pub fn plugins_dir(&self) -> &Path { - &self.plugins_dir - } - - /// Loads every package under the plugins directory (already loaded ones are kept). - pub fn load_all(&self) { - let _guard = self.lifecycle.lock(); - for dir in package_dirs(&self.plugins_dir) { - if !self.is_loaded_from(&dir) { - self.load_dir(&dir, PluginSource::Installed, None); - } - } - let (done, cv) = &self.initial_load; - *done.lock() = true; - cv.notify_all(); - self.emit(None, PluginEvent::CommandsChanged); - } - - /// Waits (at most `timeout`) for the first [`load_all`](Self::load_all), so a - /// listing made at startup already holds the installed plugins and the - /// selected theme. Returns whether loading has finished. - pub fn wait_initial_load(&self, timeout: Duration) -> bool { - let (done, cv) = &self.initial_load; - let mut done = done.lock(); - if !*done { - cv.wait_while_for(&mut done, |d| !*d, timeout); - } - *done - } - - /// Loads new dev plugins from `/.openidea/plugins/` and unloads vanished ones. - pub fn set_project_policy(&self, policy: ProjectPolicy) { - *self.project_policy.write() = policy; - } - - pub fn restrict_project(&self, root: &Path) { - let _guard = self.lifecycle.lock(); - let ids: Vec<_> = self - .plugins - .read() - .iter() - .filter(|(_, p)| p.dev_root.as_deref() == Some(root)) - .map(|(id, _)| id.clone()) - .collect(); - for id in ids { - self.unload(&id); - } - self.emit(None, PluginEvent::CommandsChanged); - } - - pub fn sync_project(&self, root: &Path) { - if !(self.project_policy.read())(root) { - self.restrict_project(root); - return; - } - let _guard = self.lifecycle.lock(); - let dirs = package_dirs(&ide_core::project_dir::path(root, "plugins")); - let stale: Vec = self - .plugins - .read() - .iter() - .filter(|(_, p)| p.dev_root.as_deref() == Some(root) && !dirs.contains(&p.dir)) - .map(|(id, _)| id.clone()) - .collect(); - let mut changed = !stale.is_empty(); - for id in stale { - self.unload(&id); - } - for dir in dirs { - if !self.is_loaded_from(&dir) { - self.load_dir(&dir, PluginSource::Dev, Some(root.to_path_buf())); - changed = true; - } - } - if changed { - self.emit(None, PluginEvent::CommandsChanged); - } - } - - /// Installed plugins plus the dev plugins of `project` (if any). - pub fn list(&self, project: Option<&Path>) -> PluginsSnapshot { - let mut plugins: Vec = self - .plugins - .read() - .values() - .filter(|p| p.dev_root.is_none() || p.dev_root.as_deref() == project) - .map(|p| self.info(p)) - .collect(); - plugins.sort_by_key(|p| p.name.to_lowercase()); - PluginsSnapshot { plugins, active_theme: self.active_theme() } - } - - pub fn info_of(&self, id: &str) -> IdeResult { - Ok(self.info(&*self.get(id)?)) - } - - pub fn set_enabled(&self, id: &str, enabled: bool) -> IdeResult<()> { - let _guard = self.lifecycle.lock(); - let plugin = self.get(id)?; - { - let mut state = self.state.lock(); - if enabled { - state.disabled.remove(id) - } else { - state.disabled.insert(id.to_owned()) - }; - } - self.save_state(); - self.stop(&plugin); - if enabled { - self.start(&plugin); - } else { - plugin.meta.lock().status = PluginStatus::Disabled; - } - self.emit(None, PluginEvent::CommandsChanged); - self.emit_theme_if_owned(id); - Ok(()) - } - - /// Re-reads a plugin from disk (e.g. after rebuilding a dev plugin). - pub fn reload(&self, id: &str) -> IdeResult { - let _guard = self.lifecycle.lock(); - let plugin = self.get(id)?; - let (dir, source, root) = (plugin.dir.clone(), plugin.source, plugin.dev_root.clone()); - self.unload(id); - let new_id = self.load_dir(&dir, source, root); - self.emit(None, PluginEvent::CommandsChanged); - self.emit_theme_if_owned(&new_id); - self.info_of(&new_id) - } - - /// Installs the package at `path`: a folder, its `plugin.toml`, or a `.zip` of the folder. - pub fn install_from_path(&self, path: &Path) -> IdeResult { - if package::is_zip(path) && path.is_file() { - // Outside the plugins directory: a crash must not leave a package that loads. - let unpacked = tempfile::Builder::new().prefix("openidea-plugin-").tempdir()?; - let root = package::unpack_zip(path, unpacked.path())?; - return self.install_from_dir(&root); - } - if path.file_name().is_some_and(|name| name == MANIFEST_FILE) && path.is_file() { - return self.install_from_dir(path.parent().unwrap_or(path)); - } - self.install_from_dir(path) - } - - /// Copies a plugin package (manifest + referenced files) into the plugins - /// directory, replacing an installed version with the same id. - pub fn install_from_dir(&self, src: &Path) -> IdeResult { - let _guard = self.lifecycle.lock(); - let manifest = PluginManifest::load(src).map_err(IdeError::invalid)?; - for file in manifest.files() { - if !src.join(file).is_file() { - return Err(IdeError::invalid(format!( - "{} is missing (referenced by plugin.toml); build the plugin first", - file.display() - ))); - } - } - if let Some(wasm) = &manifest.wasm { - self.engine.compile(&src.join(wasm)).map_err(IdeError::invalid)?; - } - let id = manifest.id.clone(); - if let Some(existing) = self.plugins.read().get(&id) - && existing.source == PluginSource::Dev - { - return Err(IdeError::new( - ide_core::error::ErrorKind::AlreadyExists, - format!("a dev plugin with id {id:?} is loaded from {}", existing.dir.display()), - )); - } - let target = self.plugins_dir.join(&id); - let same_dir = src.canonicalize().ok().zip(target.canonicalize().ok()).is_some_and(|(a, b)| a == b); - self.unload(&id); - if !same_dir { - let staging = self.plugins_dir.join(format!(".install-{id}")); - let _ = std::fs::remove_dir_all(&staging); - let copy = || -> std::io::Result<()> { - std::fs::create_dir_all(&staging)?; - std::fs::copy(src.join(MANIFEST_FILE), staging.join(MANIFEST_FILE))?; - for file in manifest.files() { - let to = staging.join(file); - if let Some(parent) = to.parent() { - std::fs::create_dir_all(parent)?; - } - std::fs::copy(src.join(file), to)?; - } - for name in LICENSE_FILES { - if src.join(name).is_file() { - std::fs::copy(src.join(name), staging.join(name))?; - } - } - if target.exists() { - std::fs::remove_dir_all(&target)?; - } - std::fs::rename(&staging, &target) - }; - if let Err(e) = copy() { - let _ = std::fs::remove_dir_all(&staging); - return Err(e.into()); - } - } - self.load_dir(&target, PluginSource::Installed, None); - self.emit(None, PluginEvent::CommandsChanged); - self.emit_theme_if_owned(&id); - self.info_of(&id) - } - - pub fn uninstall(&self, id: &str) -> IdeResult<()> { - let _guard = self.lifecycle.lock(); - let plugin = self.get(id)?; - if plugin.source != PluginSource::Installed { - return Err(IdeError::invalid("dev plugins are removed by deleting them from .openidea/plugins")); - } - self.unload(id); - std::fs::remove_dir_all(&plugin.dir)?; - let theme_cleared = { - let mut state = self.state.lock(); - state.disabled.remove(id); - let owned = state.theme.as_ref().is_some_and(|t| t.plugin == id); - if owned { - state.theme = None; - } - owned - }; - self.save_state(); - self.emit(None, PluginEvent::CommandsChanged); - if theme_cleared { - self.emit(None, PluginEvent::ThemeChanged { theme: None }); - } - Ok(()) - } - - /// Runs a plugin command. Blocks for up to the configured time limit. - pub fn run_command( - &self, - id: &str, - command: &str, - arg: Option<&str>, - invocation: Invocation, - ) -> IdeResult> { - let plugin = self.get(id)?; - let client = invocation.client.clone(); - let mut runtime = plugin.runtime.lock(); - let Some(rt) = runtime.as_mut() else { - let meta = plugin.meta.lock(); - return Err(IdeError::unavailable(match meta.status { - PluginStatus::Disabled => format!("plugin {id:?} is disabled"), - PluginStatus::Static => format!("plugin {id:?} has no code to run commands"), - _ => format!("plugin {id:?} is not running: {}", meta.error.as_deref().unwrap_or("failed")), - })); - }; - match rt.run_command(command, arg, invocation) { - Ok((value, fx)) => { - drop(runtime); - self.apply_effects(&plugin, fx); - Ok(value) - } - Err(CallError::Guest(e)) => Err(IdeError::internal(e)), - Err(CallError::Trap(e)) => { - *runtime = None; - drop(runtime); - self.fail(&plugin, &e, client.as_deref()); - Err(IdeError::internal(format!("plugin {id:?} {e}"))) - } - } - } - - /// The UI reports which file its focused editor shows (for `active-file`). - pub fn set_active_file(&self, client: &str, path: Option) { - let mut files = self.active_files.lock(); - match path { - Some(p) => files.insert(client.to_owned(), p), - None => files.remove(client), - }; - } - - /// Selects a plugin theme (`None` restores the built-in theme). - pub fn set_theme(&self, selection: Option<(&str, &str)>) -> IdeResult> { - if let Some((plugin, theme)) = selection { - let p = self.get(plugin)?; - if !p.registrations.lock().themes.iter().any(|t| t.id == theme) { - return Err(IdeError::not_found(format!("plugin {plugin:?} has no theme {theme:?}"))); - } - } - self.state.lock().theme = - selection.map(|(plugin, theme)| ThemeRef { plugin: plugin.into(), theme: theme.into(), frame: None }); - self.save_state(); - let active = self.active_theme(); - self.emit(None, PluginEvent::ThemeChanged { theme: active.clone() }); - Ok(active) - } - - /// Records the selected theme's resolved window frame colour (`#rgb`, - /// `#rrggbb` or `#rrggbbaa`); ignored without a selected theme. - pub fn set_theme_frame(&self, frame: Option<&str>) -> IdeResult<()> { - if let Some(f) = frame - && !is_hex_color(f) - { - return Err(IdeError::invalid(format!("not a hex colour: {f:?}"))); - } - let changed = match self.state.lock().theme.as_mut() { - Some(t) if t.frame.as_deref() != frame => { - t.frame = frame.map(str::to_owned); - true - } - _ => false, - }; - if changed { - self.save_state(); - } - Ok(()) - } - - /// Frame colour for a new window: the recorded one of the selected theme, - /// unless its plugin is disabled. Available before plugins are loaded. - pub fn startup_frame(&self) -> Option { - let state = self.state.lock(); - let t = state.theme.as_ref()?; - if state.disabled.contains(&t.plugin) { - return None; - } - t.frame.clone() - } - - /// The selected plugin theme, when its plugin is enabled and running. - pub fn active_theme(&self) -> Option { - let sel = self.state.lock().theme.clone()?; - let plugin = self.plugins.read().get(&sel.plugin).cloned()?; - if !plugin.is_live() { - return None; - } - let theme = plugin.registrations.lock().themes.iter().find(|t| t.id == sel.theme).cloned()?; - Some(ActiveTheme { plugin_id: sel.plugin, theme }) - } - - /// Languages contributed by live plugins (for runtime language registration). - pub fn languages(&self) -> Vec { - self.plugins - .read() - .values() - .filter(|p| p.is_live()) - .flat_map(|p| p.registrations.lock().languages.clone()) - .collect() - } - - /// Deactivates every plugin (also done on drop). - pub fn shutdown(&self) { - for plugin in self.plugins.read().values() { - if let Some(mut rt) = plugin.runtime.lock().take() { - rt.deactivate(); - } - } - } - - // ---- internals ---- - - fn get(&self, id: &str) -> IdeResult> { - let plugin = - self.plugins.read().get(id).cloned().ok_or_else(|| IdeError::not_found(format!("no plugin {id:?}")))?; - if plugin.dev_root.as_deref().is_some_and(|root| !(self.project_policy.read())(root)) { - return Err(IdeError::unavailable("Project is in Restricted Mode")); - } - Ok(plugin) - } - - fn is_loaded_from(&self, dir: &Path) -> bool { - self.plugins.read().values().any(|p| p.dir == dir) - } - - /// Loads one package and starts it unless disabled. Returns the plugin id. - fn load_dir(&self, dir: &Path, source: PluginSource, dev_root: Option) -> String { - let (manifest, static_regs, error) = match PluginManifest::load(dir) { - Ok(m) => match static_contributions(dir, &m) { - Ok(regs) => (m, regs, None), - Err(e) => (m, Registrations::default(), Some(e)), - }, - Err(e) => (placeholder_manifest(dir), Registrations::default(), Some(e)), - }; - let id = manifest.id.clone(); - let plugin = Arc::new(LoadedPlugin { - manifest, - dir: dir.to_path_buf(), - source, - dev_root, - registrations: Arc::new(Mutex::new(static_regs.clone())), - static_regs, - meta: Mutex::new(Meta { status: PluginStatus::Disabled, error: None }), - runtime: Mutex::new(None), - }); - { - let mut plugins = self.plugins.write(); - if let Some(existing) = plugins.get(&id) { - tracing::warn!( - "plugin {id:?} at {} ignored: already loaded from {}", - dir.display(), - existing.dir.display() - ); - return id; - } - plugins.insert(id.clone(), plugin.clone()); - } - if let Some(e) = error { - tracing::warn!("plugin {}: {e}", dir.display()); - plugin.set_failed(e); - } else if !self.state.lock().disabled.contains(&id) { - self.start(&plugin); - } - id - } - - fn unload(&self, id: &str) { - let Some(plugin) = self.plugins.write().remove(id) else { return }; - self.stop(&plugin); - } - - fn start(&self, plugin: &Arc) { - *plugin.registrations.lock() = plugin.static_regs.clone(); - let Some(wasm) = &plugin.manifest.wasm else { - *plugin.meta.lock() = Meta { status: PluginStatus::Static, error: None }; - return; - }; - let started = self.engine.compile(&plugin.dir.join(wasm)).and_then(|component| { - let active_files = self.active_files.clone(); - let setup = RuntimeSetup { - plugin_id: plugin.manifest.id.clone(), - version: plugin.manifest.version.clone(), - permissions: plugin.manifest.permissions.clone(), - registrations: plugin.registrations.clone(), - sink: self.sink.clone(), - active_file: Arc::new(move |client| client.and_then(|c| active_files.lock().get(c).cloned())), - limits: self.limits, - }; - let mut rt = Runtime::instantiate(&self.engine, &component, setup)?; - match rt.activate() { - Ok(fx) => Ok((rt, fx)), - Err(CallError::Guest(e)) => Err(format!("activation failed: {e}")), - Err(CallError::Trap(e)) => Err(format!("activation {e}")), - } - }); - match started { - Ok((rt, _fx)) => { - *plugin.runtime.lock() = Some(rt); - *plugin.meta.lock() = Meta { status: PluginStatus::Active, error: None }; - } - Err(e) => self.fail(plugin, &e, None), - } - } - - fn stop(&self, plugin: &LoadedPlugin) { - if let Some(mut rt) = plugin.runtime.lock().take() { - rt.deactivate(); - } - } - - fn fail(&self, plugin: &LoadedPlugin, error: &str, client: Option<&str>) { - tracing::warn!(plugin = %plugin.manifest.id, "disabled after failure: {error}"); - plugin.set_failed(error.to_owned()); - self.emit( - client, - PluginEvent::Notification { - plugin_id: plugin.manifest.id.clone(), - level: NotificationLevel::Error, - title: format!("Plugin \u{201c}{}\u{201d} was disabled", plugin.manifest.name), - body: error.to_owned(), - }, - ); - self.emit(None, PluginEvent::CommandsChanged); - self.emit_theme_if_owned(&plugin.manifest.id); - } - - fn apply_effects(&self, plugin: &LoadedPlugin, fx: CallEffects) { - if fx.commands_changed { - self.emit(None, PluginEvent::CommandsChanged); - } - let sel = self.state.lock().theme.clone(); - if let Some(sel) = sel - && sel.plugin == plugin.manifest.id - && fx.themes_changed.contains(&sel.theme) - { - self.emit(None, PluginEvent::ThemeChanged { theme: self.active_theme() }); - } - } - - fn emit_theme_if_owned(&self, id: &str) { - let owned = self.state.lock().theme.as_ref().is_some_and(|t| t.plugin == id); - if owned { - self.emit(None, PluginEvent::ThemeChanged { theme: self.active_theme() }); - } - } - - fn emit(&self, client: Option<&str>, event: PluginEvent) { - self.sink.emit(client, event); - } - - fn save_state(&self) { - let json = serde_json::to_string_pretty(&*self.state.lock()).unwrap_or_default(); - if let Err(e) = std::fs::write(self.plugins_dir.join(STATE_FILE), json) { - tracing::warn!("saving plugin state: {e}"); - } - } - - fn info(&self, p: &LoadedPlugin) -> PluginInfo { - let m = &p.manifest; - let regs = p.registrations.lock().clone(); - let meta = p.meta.lock(); - PluginInfo { - id: m.id.clone(), - name: m.name.clone(), - version: m.version.clone(), - description: m.description.clone(), - authors: m.authors.clone(), - homepage: m.homepage.clone(), - change_notes: m.change_notes.clone(), - source: p.source, - path: p.dir.clone().into(), - enabled: !self.state.lock().disabled.contains(&m.id), - status: meta.status, - error: meta.error.clone(), - has_code: m.wasm.is_some(), - permissions: m.permissions.clone(), - commands: regs.commands, - languages: regs - .languages - .iter() - .map(|l| PluginLanguage { - id: l.id.to_string(), - name: l.name.clone(), - extensions: l.extensions.clone(), - }) - .collect(), - themes: regs - .themes - .iter() - .map(|t| PluginTheme { id: t.id.clone(), name: t.name.clone(), kind: t.kind }) - .collect(), - } - } -} - -impl Drop for PluginHost { - fn drop(&mut self) { - self.shutdown(); - } -} - -fn is_hex_color(s: &str) -> bool { - s.strip_prefix('#').is_some_and(|h| matches!(h.len(), 3 | 6 | 8) && h.bytes().all(|b| b.is_ascii_hexdigit())) -} - -/// Plugin packages found in `dirs` (first occurrence of an id wins). Invalid -/// manifests are skipped; packages with missing files carry a `problem`. -pub fn scan_catalog(dirs: &[PathBuf]) -> Vec { - let mut out: Vec = Vec::new(); - for dir in dirs.iter().flat_map(|d| package_dirs(d)) { - let Ok(m) = PluginManifest::load(&dir) else { continue }; - if out.iter().any(|c| c.id == m.id) { - continue; - } - let problem = m - .files() - .into_iter() - .find(|f| !dir.join(f).is_file()) - .map(|f| format!("{} is missing; build the plugin first", f.display())); - out.push(CatalogPlugin { - has_code: m.wasm.is_some(), - language_count: m.contributes.languages.len() as u32, - theme_count: m.contributes.themes.len() as u32, - commands: m.contributes.commands.clone(), - permissions: m.permissions.clone(), - id: m.id, - name: m.name, - version: m.version, - description: m.description, - authors: m.authors, - homepage: m.homepage, - change_notes: m.change_notes, - path: dir.into(), - problem, - }); - } - out.sort_by_key(|a| a.name.to_lowercase()); - out -} - -/// Subdirectories of `dir` that contain a `plugin.toml`, sorted. -fn package_dirs(dir: &Path) -> Vec { - let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; - let mut dirs: Vec = entries - .flatten() - .map(|e| e.path()) - .filter(|p| { - p.join(MANIFEST_FILE).is_file() - && !p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with('.')) - }) - .collect(); - dirs.sort(); - dirs -} - -fn static_contributions(dir: &Path, m: &PluginManifest) -> Result { - let mut regs = Registrations::default(); - for cmd in &m.contributes.commands { - regs.add_command(cmd.clone()); - } - let read = |p: &Path| std::fs::read_to_string(dir.join(p)).map_err(|e| format!("{}: {e}", p.display())); - for f in &m.contributes.languages { - let cfg = runtime::parse_language(&read(&f.path)?).map_err(|e| format!("{}: {e}", f.path.display()))?; - regs.add_language(cfg); - } - for f in &m.contributes.themes { - let mut theme = ThemeDef::parse(&read(&f.path)?).map_err(|e| format!("{}: {e}", f.path.display()))?; - if let Some(scheme) = &f.editor_scheme { - theme.merge_editor_scheme(&read(scheme)?).map_err(|e| format!("{}: {e}", scheme.display()))?; - } - regs.add_theme(theme); - } - Ok(regs) -} - -/// Stand-in for a package whose manifest failed to parse, so it still shows up (as failed). -fn placeholder_manifest(dir: &Path) -> PluginManifest { - let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - PluginManifest { - id: format!("invalid-{}", name.to_lowercase().replace(|c: char| !c.is_ascii_alphanumeric(), "-")), - name, - version: "0.0.0".into(), - description: String::new(), - authors: Vec::new(), - homepage: None, - change_notes: None, - openidea_api: API_VERSION.into(), - wasm: None, - permissions: Vec::new(), - contributes: Contributions::default(), - } -} +pub use wasmtime::component::Component; diff --git a/crates/ide-plugin/src/manifest.rs b/crates/ide-plugin/src/manifest.rs deleted file mode 100644 index c32ac6ca..00000000 --- a/crates/ide-plugin/src/manifest.rs +++ /dev/null @@ -1,279 +0,0 @@ -//! `plugin.toml`: the plugin package manifest. - -use serde::{Deserialize, Serialize}; -use specta::Type; -use std::path::{Component, Path, PathBuf}; - -/// Plugin API version implemented by this host (`openidea-api` in the manifest). -pub const API_VERSION: &str = "0.1"; -pub const MANIFEST_FILE: &str = "plugin.toml"; - -/// Capabilities a plugin must declare to use the gated host functions. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Type)] -#[serde(rename_all = "kebab-case")] -pub enum Permission { - /// `workspace-root`, `read-file` (inside the project root only). - ProjectRead, - /// `active-file`. - EditorRead, - /// `insert-text`, `replace-selection`. - EditorWrite, -} - -impl Permission { - pub fn as_str(self) -> &'static str { - match self { - Permission::ProjectRead => "project-read", - Permission::EditorRead => "editor-read", - Permission::EditorWrite => "editor-write", - } - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case", deny_unknown_fields)] -pub struct PluginManifest { - pub id: String, - pub name: String, - pub version: String, - #[serde(default)] - pub description: String, - #[serde(default)] - pub authors: Vec, - #[serde(default)] - pub homepage: Option, - /// Release notes of this version (Settings › Plugins › What's New). - #[serde(default)] - pub change_notes: Option, - pub openidea_api: String, - /// Component file relative to the package directory; absent for - /// contribution-only plugins (themes, languages). - #[serde(default)] - pub wasm: Option, - #[serde(default)] - pub permissions: Vec, - #[serde(default)] - pub contributes: Contributions, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case", deny_unknown_fields)] -pub struct Contributions { - #[serde(default)] - pub commands: Vec, - #[serde(default)] - pub languages: Vec, - #[serde(default)] - pub themes: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub struct CommandDecl { - pub id: String, - pub title: String, - #[serde(default)] - pub category: Option, -} - -/// A contributed file, relative to the package directory. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct FileDecl { - pub path: PathBuf, -} - -/// A contributed theme: the UI theme file plus an optional editor colour scheme -/// whose tokens are merged over it (IntelliJ's `.theme.json` + `.icls`). -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case", deny_unknown_fields)] -pub struct ThemeDecl { - pub path: PathBuf, - #[serde(default)] - pub editor_scheme: Option, -} - -impl PluginManifest { - pub fn parse(src: &str) -> Result { - let manifest: Self = toml::from_str(src).map_err(|e| e.to_string())?; - manifest.validate()?; - Ok(manifest) - } - - pub fn load(dir: &Path) -> Result { - let path = dir.join(MANIFEST_FILE); - let src = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?; - Self::parse(&src).map_err(|e| format!("{}: {e}", path.display())) - } - - pub fn validate(&self) -> Result<(), String> { - validate_plugin_id(&self.id)?; - if self.name.trim().is_empty() { - return Err("`name` must not be empty".into()); - } - if !is_version(&self.version) { - return Err(format!("`version` must look like 1.2.3, got {:?}", self.version)); - } - if !api_compatible(&self.openidea_api) { - return Err(format!( - "unsupported openidea-api {:?} (this IDE implements {API_VERSION})", - self.openidea_api - )); - } - if let Some(wasm) = &self.wasm { - check_relative(wasm, "wasm")?; - } - let mut seen = std::collections::HashSet::new(); - for c in &self.contributes.commands { - validate_command_id(&c.id)?; - if !seen.insert(c.id.as_str()) { - return Err(format!("duplicate command id {:?}", c.id)); - } - if c.title.trim().is_empty() { - return Err(format!("command {:?} has an empty title", c.id)); - } - } - let theme_files = self.contributes.themes.iter().flat_map(|t| std::iter::once(&t.path).chain(&t.editor_scheme)); - for path in self.contributes.languages.iter().map(|f| &f.path).chain(theme_files) { - check_relative(path, "contributes path")?; - } - Ok(()) - } - - /// Every file of the package besides the manifest (what an install copies). - pub fn files(&self) -> Vec<&Path> { - let mut files: Vec<&Path> = self.wasm.iter().map(PathBuf::as_path).collect(); - files.extend(self.contributes.languages.iter().map(|f| f.path.as_path())); - for t in &self.contributes.themes { - files.push(t.path.as_path()); - files.extend(t.editor_scheme.as_deref()); - } - files - } - - pub fn has(&self, p: Permission) -> bool { - self.permissions.contains(&p) - } -} - -/// `[a-z0-9][a-z0-9_-]*`, at most 64 chars (no dots: it is one segment of an action id). -pub fn validate_plugin_id(id: &str) -> Result<(), String> { - validate_ident(id, "plugin id", false) -} - -/// `[a-z0-9][a-z0-9._-]*`, at most 64 chars. -pub fn validate_command_id(id: &str) -> Result<(), String> { - validate_ident(id, "command id", true) -} - -fn validate_ident(id: &str, what: &str, dots: bool) -> Result<(), String> { - let ok_first = id.chars().next().is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit()); - let ok_rest = - id.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_' || (dots && c == '.')); - if ok_first && ok_rest && id.len() <= 64 { - Ok(()) - } else { - let allowed = if dots { "a-z, 0-9, '.', '-', '_'" } else { "a-z, 0-9, '-', '_'" }; - Err(format!("invalid {what} {id:?}: use {allowed}, starting with a letter or digit (max 64)")) - } -} - -fn is_version(v: &str) -> bool { - let core = v.split(['-', '+']).next().unwrap_or_default(); - let parts: Vec<&str> = core.split('.').collect(); - parts.len() == 3 && parts.iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) -} - -/// `0.1` and `0.1.x` are compatible with API 0.1 (pre-1.0: minor is breaking). -fn api_compatible(v: &str) -> bool { - v == API_VERSION || v.strip_prefix(API_VERSION).is_some_and(|rest| rest.starts_with('.')) -} - -/// Package paths must stay inside the package directory. -fn check_relative(path: &Path, what: &str) -> Result<(), String> { - let ok = !path.as_os_str().is_empty() && path.components().all(|c| matches!(c, Component::Normal(_))); - if ok { Ok(()) } else { Err(format!("{what} {:?} must be a relative path inside the plugin", path.display())) } -} - -#[cfg(test)] -mod tests { - use super::*; - - const FULL: &str = r#" - id = "hello" - name = "Hello" - version = "0.1.0" - description = "Says hello" - authors = ["A"] - openidea-api = "0.1" - wasm = "dist/plugin.wasm" - permissions = ["project-read", "editor-write"] - - [[contributes.commands]] - id = "say.hi" - title = "Say Hi" - category = "Hello" - - [[contributes.themes]] - path = "themes/dark.json" - editor-scheme = "themes/dark.scheme.json" - "#; - - #[test] - fn parses_full_manifest() { - let m = PluginManifest::parse(FULL).unwrap(); - assert_eq!(m.id, "hello"); - assert_eq!(m.permissions, vec![Permission::ProjectRead, Permission::EditorWrite]); - assert_eq!(m.contributes.commands[0].category.as_deref(), Some("Hello")); - assert_eq!( - m.files(), - vec![Path::new("dist/plugin.wasm"), Path::new("themes/dark.json"), Path::new("themes/dark.scheme.json")] - ); - assert!(m.has(Permission::EditorWrite) && !m.has(Permission::EditorRead)); - } - - #[test] - fn minimal_contribution_only_manifest() { - let m = - PluginManifest::parse("id = \"t\"\nname = \"T\"\nversion = \"1.0.0\"\nopenidea-api = \"0.1.3\"").unwrap(); - assert!(m.wasm.is_none() && m.permissions.is_empty()); - } - - fn err(src: &str) -> String { - PluginManifest::parse(src).unwrap_err() - } - - #[test] - fn rejects_invalid_manifests() { - let base = |extra: &str, id: &str, api: &str| { - format!("id = \"{id}\"\nname = \"N\"\nversion = \"1.0.0\"\nopenidea-api = \"{api}\"\n{extra}") - }; - assert!(err(&base("", "Bad.Id", "0.1")).contains("invalid plugin id")); - assert!(err(&base("", "ok", "0.2")).contains("unsupported openidea-api")); - assert!(err(&base("", "ok", "0.10")).contains("unsupported openidea-api")); - assert!(err(&base("permissions = [\"network\"]", "ok", "0.1")).contains("unknown variant")); - assert!(err(&base("wasm = \"../evil.wasm\"", "ok", "0.1")).contains("relative path")); - assert!(err(&base("wasm = \"/abs.wasm\"", "ok", "0.1")).contains("relative path")); - assert!(err(&base("bogus = 1", "ok", "0.1")).contains("unknown field")); - let dup = - "[[contributes.commands]]\nid = \"a\"\ntitle = \"A\"\n[[contributes.commands]]\nid = \"a\"\ntitle = \"B\""; - assert!(err(&base(dup, "ok", "0.1")).contains("duplicate command")); - let traversal = "[[contributes.languages]]\npath = \"a/../../x.toml\""; - assert!(err(&base(traversal, "ok", "0.1")).contains("relative path")); - let scheme_escape = "[[contributes.themes]]\npath = \"t.json\"\neditor-scheme = \"../s.json\""; - assert!(err(&base(scheme_escape, "ok", "0.1")).contains("relative path")); - assert!(err("id = \"ok\"\nname = \"N\"\nversion = \"1.0\"\nopenidea-api = \"0.1\"").contains("version")); - assert!(err("id = \"ok\"\nname = \" \"\nversion = \"1.0.0\"\nopenidea-api = \"0.1\"").contains("name")); - } - - #[test] - fn ident_rules() { - assert!(validate_command_id("word-count.v2_x").is_ok()); - assert!(validate_command_id("-x").is_err()); - assert!(validate_command_id("").is_err()); - assert!(validate_command_id(&"a".repeat(65)).is_err()); - assert!(validate_plugin_id("a.b").is_err()); - assert!(is_version("1.2.3-beta.1+build")); - assert!(!is_version("1.2.x")); - } -} diff --git a/crates/ide-plugin/src/package.rs b/crates/ide-plugin/src/package.rs deleted file mode 100644 index cefb3fa9..00000000 --- a/crates/ide-plugin/src/package.rs +++ /dev/null @@ -1,74 +0,0 @@ -//! Plugin packages on disk: a folder, its `plugin.toml`, or a `.zip` of the folder. - -use crate::MANIFEST_FILE; -use ide_core::{IdeError, IdeResult}; -use std::fs::{self, File}; -use std::io::{self, BufReader, Read}; -use std::path::{Path, PathBuf}; - -/// Far above any real package; stops a zip bomb before it fills the disk. -const MAX_ENTRIES: usize = 10_000; -const MAX_UNPACKED_BYTES: u64 = 1024 * 1024 * 1024; - -pub(crate) fn is_zip(path: &Path) -> bool { - path.extension().is_some_and(|e| e.eq_ignore_ascii_case("zip")) -} - -fn invalid_zip(zip: &Path, reason: impl std::fmt::Display) -> IdeError { - IdeError::invalid(format!("{} is not a valid plugin archive: {reason}", zip.display())) -} - -/// Unpacks `zip` into `dest` and returns the package folder inside it. Refuses the -/// whole archive when an entry would leave `dest` or is a symbolic link. -pub(crate) fn unpack_zip(zip: &Path, dest: &Path) -> IdeResult { - let mut archive = zip::ZipArchive::new(BufReader::new(File::open(zip)?)).map_err(|e| invalid_zip(zip, e))?; - if archive.len() > MAX_ENTRIES { - return Err(invalid_zip(zip, format!("more than {MAX_ENTRIES} entries"))); - } - let mut budget = MAX_UNPACKED_BYTES; - for i in 0..archive.len() { - let mut entry = archive.by_index(i).map_err(|e| invalid_zip(zip, e))?; - let name = entry.name().to_owned(); - let Some(rel) = entry.enclosed_name() else { - return Err(invalid_zip(zip, format!("unsafe path {name:?}"))); - }; - if entry.is_symlink() { - return Err(invalid_zip(zip, format!("symbolic link {name:?}"))); - } - let out = dest.join(rel); - if entry.is_dir() { - fs::create_dir_all(&out)?; - continue; - } - if let Some(parent) = out.parent() { - fs::create_dir_all(parent)?; - } - // One byte over the budget tells a full budget from a file that exactly fits. - let written = - io::copy(&mut (&mut entry).take(budget + 1), &mut File::create(&out)?).map_err(|e| invalid_zip(zip, e))?; - if written > budget { - return Err(invalid_zip(zip, "it unpacks to more than 1 GB")); - } - budget -= written; - } - package_root(dest).ok_or_else(|| { - IdeError::invalid(format!( - "{} is not an OpenIDEA plugin: no {MANIFEST_FILE} at its root or in its only folder", - zip.display() - )) - }) -} - -/// `dir` itself, or its only folder as when a zip holds the package folder. -/// Archiver metadata (`__MACOSX`, dot files) does not count as a second folder. -fn package_root(dir: &Path) -> Option { - if dir.join(MANIFEST_FILE).is_file() { - return Some(dir.to_path_buf()); - } - let mut folders = fs::read_dir(dir).ok()?.flatten().map(|e| e.path()).filter(|p| { - let name = p.file_name().unwrap_or_default().to_string_lossy(); - p.is_dir() && !name.starts_with('.') && name != "__MACOSX" - }); - let only = folders.next().filter(|_| folders.next().is_none())?; - only.join(MANIFEST_FILE).is_file().then_some(only) -} diff --git a/crates/ide-plugin/src/runtime.rs b/crates/ide-plugin/src/runtime.rs index 83962044..fdb48019 100644 --- a/crates/ide-plugin/src/runtime.rs +++ b/crates/ide-plugin/src/runtime.rs @@ -1,41 +1,116 @@ -//! Wasmtime glue: one shared engine, one `Store` per plugin, host imports. +//! Wasmtime glue for the `openidea:plugin@1.0.0` world (`wit/`): one shared +//! engine, one `Store` per plugin. Everything a call may do outside the +//! sandbox goes through [`HostApi`], implemented by the host; the imports +//! themselves are in `wit_host`. -use crate::manifest::{API_VERSION, CommandDecl, Permission, validate_command_id}; -use crate::sandbox; -use crate::theme::ThemeDef; -use crate::types::{Invocation, Limits, NotificationLevel, PluginEvent, PluginEventSink}; -use ide_language::LanguageConfig; +use crate::types::{CodeAction, CompletionItem, InlineSuggestion, LineMarker, Location, ProviderDocument}; +use crate::types::{ + EventKind, HostError, HttpRequest, HttpResponse, Invocation, Limits, NotificationLevel, ProcessOutput, + RepositoryStatus, StatusItem, SyntaxFold, SyntaxSymbol, SyntaxToken, WorkbenchEvent, +}; +use crate::types::{ + FieldValue, View, ViewBody, ViewButton, ViewEvent, ViewField, ViewListItem, ViewTable, ViewTreeItem, Viewport, +}; +use crate::wit_host::{bindings, providers_bindings, syntax_bindings, views_bindings}; +use ide_core::CancellationToken; +use ide_extension::Capability; use parking_lot::Mutex; use std::path::Path; use std::sync::Arc; -use std::time::Duration; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::{Duration, Instant}; use wasmtime::component::{Component, HasSelf, Linker, ResourceTable}; -use wasmtime::{Config, Engine, Store, StoreLimits, StoreLimitsBuilder}; +use wasmtime::{Config, Engine, Store, StoreLimits, StoreLimitsBuilder, UpdateDeadline}; use wasmtime_wasi::p2::pipe::MemoryOutputPipe; use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView}; -mod bindings { - wasmtime::component::bindgen!({ - world: "plugin", - path: "../../wit", - imports: { default: trappable }, - }); +use bindings::openidea::plugin::events as wit_events; +use bindings::openidea::plugin::types as wit_types; +use providers_bindings::exports::openidea::plugin::providers as wit_prov; +use syntax_bindings::exports::openidea::plugin::syntax_provider as wit_syntax; +use views_bindings::exports::openidea::plugin::view_provider as wit_view; +use views_bindings::openidea::plugin::view_types as wit_vt; + +/// The API version of the world above, `major.minor` of [`host_api`]. +pub const API_VERSION: &str = "1.0"; +const EPOCH_TICK: Duration = Duration::from_millis(10); +pub(crate) const MAX_TEXT: usize = 1 << 20; +pub(crate) const MAX_TITLE: usize = 256; +const STDERR_CAPACITY: usize = 256 << 10; +/// Message of a call interrupted through [`Runtime::cancel_handle`]. +pub const CANCELLED: &str = "was cancelled"; + +/// What plugin code may ask of the IDE, per plugin. Implemented by the host, +/// which routes notifications and status items to windows and edits to open +/// documents. Capabilities are already checked when these are called. +pub trait HostApi: Send + Sync { + fn notify(&self, client: Option<&str>, level: NotificationLevel, title: String, body: String); + /// Sets (`Some`) or removes the plugin's status bar item `id`. + fn status_item(&self, id: &str, item: Option); + /// Roots of the open projects. + fn projects(&self) -> Vec; + /// Unsaved text of an open editor's file. + fn buffer_text(&self, path: &Path) -> Option; + /// Version and text of the open document at `path`. + fn document(&self, path: &Path) -> Option<(u64, String)>; + /// Applies edits to the open document at `path` if it is still at `version`. + fn apply_edits( + &self, + client: Option<&str>, + path: &Path, + version: u64, + edits: Vec, + ) -> Result; + fn storage_get(&self, key: &str) -> Result, HostError>; + /// Sets, or (`None`) deletes. + fn storage_set(&self, key: &str, value: Option) -> Result<(), HostError>; + fn storage_keys(&self, prefix: &str) -> Result, HostError>; + fn vcs_status(&self, root: &Path) -> Result, HostError>; + fn vcs_fetch(&self, root: &Path, cancel: &CancellationToken) -> Result<(), HostError>; + /// Subscribes to (or unsubscribes from) a kind of workbench event. + /// Project files matching `glob` (root-relative), at most `limit`. + fn find_files(&self, root: &Path, glob: &str, limit: usize) -> Result, HostError>; + /// Replaces the plugin's diagnostics for `path`. + fn publish_diagnostics(&self, path: &Path, items: Vec) -> Result<(), HostError>; + /// Performs `request` (its host is granted), filling in secret placeholders. + fn fetch(&self, request: HttpRequest, cancel: &CancellationToken) -> Result; + fn secret_is_set(&self, name: &str) -> bool; + /// Runs the approved file of `process:`. + fn run_process( + &self, + program: &str, + args: Vec, + cwd: Option<&Path>, + stdin: Option, + cancel: &CancellationToken, + timeout: Duration, + ) -> Result; + fn subscribe(&self, kind: EventKind, on: bool); + /// Starts a progress indicator; cancelling it from the UI cancels `cancel`. + fn task_begin(&self, client: Option<&str>, title: String, cancellable: bool, cancel: CancellationToken) -> u64; + fn task_report(&self, id: u64, done: u32, total: Option, message: Option); + fn task_cancelled(&self, id: u64) -> bool; + fn task_end(&self, id: u64); + /// The plugin's view (or custom editors) `view` must be rendered again. + fn refresh_view(&self, view: &str); + /// A message for the script of the `html` body of `view`. + fn post_view_message(&self, view: &str, message: String) -> Result<(), HostError>; + /// Opens a terminal in `client`'s window running the approved file of + /// `process:` in `cwd`. + fn open_terminal( + &self, + client: Option<&str>, + title: String, + program: &str, + args: Vec, + cwd: Option<&Path>, + ) -> Result<(), HostError>; + /// A setting of the plugin as JSON (project over global over the schema default). + fn setting(&self, root: Option<&Path>, key: &str) -> Option; } -use bindings::openidea::plugin::host::{self as wit_host}; -use bindings::openidea::plugin::types::{self as wit_types, LogLevel}; - -/// client → path of its focused editor. -pub(crate) type ActiveFileFn = Arc) -> Option + Send + Sync>; - -const EPOCH_TICK: Duration = Duration::from_millis(10); -const MAX_TEXT: usize = 1 << 20; -const MAX_TITLE: usize = 256; -const MAX_COMMANDS: usize = 256; -const STDERR_CAPACITY: usize = 256 << 10; - /// Shared compilation engine plus an epoch ticker thread for wall-clock limits. -pub(crate) struct PluginEngine { +pub struct PluginEngine { engine: Engine, linker: Linker, } @@ -65,73 +140,200 @@ impl PluginEngine { pub fn compile(&self, wasm: &Path) -> Result { let bytes = std::fs::read(wasm).map_err(|e| format!("{}: {e}", wasm.display()))?; - Component::new(&self.engine, &bytes) - .map_err(|e| format!("{}: not a valid plugin component: {e}", wasm.display())) + self.compile_bytes(&bytes).map_err(|e| format!("{}: {e}", wasm.display())) } -} -/// What a plugin contributed (manifest files + runtime registrations). -#[derive(Default, Clone)] -pub(crate) struct Registrations { - pub commands: Vec, - pub languages: Vec, - pub themes: Vec, -} + pub fn compile_bytes(&self, bytes: &[u8]) -> Result { + Component::new(&self.engine, bytes).map_err(|e| format!("not a valid plugin component: {e}")) + } -impl Registrations { - pub fn add_command(&mut self, cmd: CommandDecl) -> bool { - match self.commands.iter_mut().find(|c| c.id == cmd.id) { - Some(existing) if *existing == cmd => false, - Some(existing) => { - *existing = cmd; - true - } - None => { - self.commands.push(cmd); - true + /// Compiles `wasm`, or loads it precompiled from `cache_dir`: the key is the module's hash plus the engine's compatibility hash, + /// so an engine upgrade simply misses and recompiles. Cache failures only + /// cost the compilation. + pub fn compile_cached(&self, wasm: &Path, cache_dir: &Path) -> Result { + let bytes = std::fs::read(wasm).map_err(|e| format!("{}: {e}", wasm.display()))?; + let file = cache_dir.join(format!("{}.cwasm", self.cache_key(&bytes))); + if file.is_file() { + // SAFETY: the cache directory belongs to the IDE (inside its plugins + // directory) and is written only by `store_precompiled` below from + // components this engine compiled; a corrupt file fails validation. + match unsafe { Component::deserialize_file(&self.engine, &file) } { + Ok(component) => return Ok(component), + Err(e) => { + tracing::info!("discarding precompiled {}: {e}", file.display()); + let _ = std::fs::remove_file(&file); + } } } + let component = self.compile_bytes(&bytes).map_err(|e| format!("{}: {e}", wasm.display()))?; + store_precompiled(&component, &file); + Ok(component) } - pub fn add_language(&mut self, cfg: LanguageConfig) { - self.languages.retain(|l| l.id != cfg.id); - self.languages.push(cfg); + /// Fills the cache for `wasm` if needed (background warm-up). Returns the + /// cache file name, to keep it when pruning. + pub fn precompile(&self, wasm: &Path, cache_dir: &Path) -> Result { + let bytes = std::fs::read(wasm).map_err(|e| format!("{}: {e}", wasm.display()))?; + let name = format!("{}.cwasm", self.cache_key(&bytes)); + let file = cache_dir.join(&name); + if !file.is_file() { + let component = self.compile_bytes(&bytes)?; + store_precompiled(&component, &file); + } + Ok(name) } - pub fn add_theme(&mut self, theme: ThemeDef) { - self.themes.retain(|t| t.id != theme.id); - self.themes.push(theme); + fn cache_key(&self, bytes: &[u8]) -> String { + use std::hash::{Hash, Hasher}; + let mut engine = std::collections::hash_map::DefaultHasher::new(); + self.engine.precompile_compatibility_hash().hash(&mut engine); + let module = blake3::hash(bytes).to_hex(); + format!("{}-{:016x}", &module[..32], engine.finish()) + } + + pub fn engine(&self) -> &Engine { + &self.engine + } + + /// Rejects a component this host can't run, with a message that says what + /// to do: one importing interfaces outside the plugin API and WASI, or one + /// built for a plugin API this host doesn't implement (another major, or a + /// newer minor). Returns the API version the component was built for + /// (`None`: it uses no plugin interface). + pub fn check_component(&self, component: &Component) -> Result, String> { + let ty = component.component_type(); + let imports: Vec = ty.imports(&self.engine).map(|(name, _)| name.to_owned()).collect(); + let foreign: Vec<&str> = imports + .iter() + .map(String::as_str) + .filter(|i| !(i.starts_with(PLUGIN_PACKAGE_PREFIX) || i.starts_with("wasi:"))) + .collect(); + if !foreign.is_empty() { + return Err(format!("the component imports interfaces the IDE does not provide: {}", foreign.join(", "))); + } + let exports = ty.exports(&self.engine).map(|(name, _)| name.to_owned()).collect::>(); + let built_for = component_api(imports.iter().chain(&exports).map(String::as_str))?; + if let Some(v) = &built_for { + check_api(v, &host_api())?; + } + Ok(built_for) } } -pub(crate) fn parse_language(src: &str) -> Result { - let cfg: LanguageConfig = toml::from_str(src).map_err(|e| format!("invalid language definition: {e}"))?; - if cfg.id.as_str().is_empty() || cfg.name.trim().is_empty() { - return Err("language `id` and `name` must not be empty".into()); - } - Ok(cfg) +/// Interface names of the plugin API start with this (`openidea:plugin/log@1.0.0`). +const PLUGIN_PACKAGE_PREFIX: &str = "openidea:plugin/"; + +/// The plugin API this host implements: the version of the `wit/` package. +pub fn host_api() -> semver::Version { + semver::Version::parse(ide_extension::ENGINE_VERSION).expect("ENGINE_VERSION is a semantic version") } -/// Side effects of one call the host must act on afterwards. +/// The plugin API version a component was built for: the highest version on +/// its `openidea:plugin/*` imports and exports. An unversioned plugin +/// interface is an error, since nothing could tell compatible hosts apart. +pub fn component_api<'a>(names: impl IntoIterator) -> Result, String> { + let mut highest: Option = None; + for name in names { + let Some(rest) = name.strip_prefix(PLUGIN_PACKAGE_PREFIX) else { continue }; + let Some((_, version)) = rest.split_once('@') else { + return Err(format!("the component uses the unversioned plugin interface {name:?}")); + }; + let version = + semver::Version::parse(version).map_err(|e| format!("bad plugin API version in {name:?}: {e}"))?; + if highest.as_ref().is_none_or(|h| version > *h) { + highest = Some(version); + } + } + Ok(highest) +} + +/// A component built for `built_for` runs on a host implementing `host` when +/// the major versions match and the host's minor is at least as new (1.x only +/// adds; patches change no interface; 0.x makes no promise, so there every +/// minor is its own API). +pub fn check_api(built_for: &semver::Version, host: &semver::Version) -> Result<(), String> { + let (b, h) = ((built_for.major, built_for.minor), (host.major, host.minor)); + let same_line = b.0 == h.0 && (h.0 > 0 || b.1 == h.1); + if same_line && b <= h { + return Ok(()); + } + let newer = b > h; + let (b, h) = (format!("{}.{}", b.0, b.1), format!("{}.{}", h.0, h.1)); + Err(if newer { + format!("the component was built for plugin API {b}, newer than this IDE's {h}: update OpenIDEA") + } else { + format!("the component was built for plugin API {b}; this IDE runs {h}: rebuild it with the {h} SDK") + }) +} + +fn store_precompiled(component: &Component, file: &Path) { + let Ok(bytes) = component.serialize() else { return }; + if let Some(dir) = file.parent() { + let _ = std::fs::create_dir_all(dir); + } + // Unique per write: two threads may store the same component at once, and a + // shared temporary file could be renamed into place half written. + static WRITES: AtomicU64 = AtomicU64::new(0); + let tmp = file.with_extension(format!("tmp{}-{}", std::process::id(), WRITES.fetch_add(1, Ordering::Relaxed))); + if std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, file)).is_err() { + let _ = std::fs::remove_file(&tmp); + } +} + +/// Interrupts the running call: the epoch callback traps on `flag`, host +/// operations (a fetch) watch `token`. Reset when a call starts. #[derive(Default)] -pub(crate) struct CallEffects { - pub commands_changed: bool, - pub themes_changed: Vec, +pub struct CallCancel { + flag: AtomicBool, + token: Mutex, } -pub(crate) struct StoreData { +impl CallCancel { + pub fn cancel(&self) { + self.flag.store(true, Ordering::Release); + self.token.lock().cancel(); + } + + /// Cooperative cancellation: host operations (`net`, `process`, fetch) + /// return `cancelled` and tasks report it; the guest keeps its instance. + pub fn cancel_soft(&self) { + self.token.lock().cancel(); + } + + pub(crate) fn token(&self) -> CancellationToken { + self.token.lock().clone() + } + + fn is_set(&self) -> bool { + self.flag.load(Ordering::Acquire) + } + + fn reset(&self) { + self.flag.store(false, Ordering::Release); + *self.token.lock() = CancellationToken::new(); + } +} + +pub struct StoreData { + /// The running call is interrupted at the next epoch tick past this. + pub(crate) deadline: Instant, + /// Wall-clock limit of the running call (for the message). + pub(crate) timeout: Duration, + pub(crate) call_started: Instant, + pub(crate) cancel: Arc, + pub(crate) limits: Limits, wasi: WasiCtx, - table: ResourceTable, - limits: StoreLimits, + pub(crate) table: ResourceTable, + store_limits: StoreLimits, stderr: MemoryOutputPipe, stderr_seen: usize, - plugin_id: String, - permissions: Vec, - registrations: Arc>, - sink: Arc, - invocation: Invocation, - active_file: ActiveFileFn, - effects: CallEffects, + pub(crate) plugin_id: String, + pub(crate) granted: Vec, + pub(crate) host: Arc, + pub(crate) invocation: Invocation, + /// Tasks begun by the running call and not ended yet. + pub(crate) open_tasks: Vec, + pub(crate) last_report: Option, } impl WasiView for StoreData { @@ -141,21 +343,6 @@ impl WasiView for StoreData { } impl StoreData { - fn require(&self, p: Permission) -> wasmtime::Result<()> { - if self.permissions.contains(&p) { - Ok(()) - } else { - Err(wasmtime::Error::msg(format!( - "permission denied: add \"{}\" to `permissions` in plugin.toml", - p.as_str() - ))) - } - } - - fn emit(&self, event: PluginEvent) { - self.sink.emit(self.invocation.client.as_deref(), event); - } - /// New guest stderr output since the last call (panic messages, eprintln!). fn drain_stderr(&mut self) -> String { let all = self.stderr.contents(); @@ -165,7 +352,7 @@ impl StoreData { } } -fn clip(mut s: String, max: usize) -> String { +pub(crate) fn clip(mut s: String, max: usize) -> String { if s.len() > max { let mut end = max; while !s.is_char_boundary(end) { @@ -176,182 +363,407 @@ fn clip(mut s: String, max: usize) -> String { s } -impl wit_types::Host for StoreData {} - -impl wit_host::Host for StoreData { - fn log(&mut self, level: LogLevel, message: String) -> wasmtime::Result<()> { - let id = &self.plugin_id; - let message = clip(message, MAX_TEXT); - match level { - LogLevel::Trace => tracing::trace!(plugin = %id, "{message}"), - LogLevel::Debug => tracing::debug!(plugin = %id, "{message}"), - LogLevel::Info => tracing::info!(plugin = %id, "{message}"), - LogLevel::Warn => tracing::warn!(plugin = %id, "{message}"), - LogLevel::Error => tracing::error!(plugin = %id, "{message}"), - } - Ok(()) - } - - fn register_command(&mut self, id: String, title: String, category: Option) -> wasmtime::Result<()> { - validate_command_id(&id).map_err(wasmtime::Error::msg)?; - let title = clip(title, MAX_TITLE); - if title.trim().is_empty() { - return Err(wasmtime::Error::msg(format!("command {id:?} has an empty title"))); - } - let cmd = CommandDecl { id, title, category: category.map(|c| clip(c, MAX_TITLE)).filter(|c| !c.is_empty()) }; - let mut regs = self.registrations.lock(); - if regs.commands.len() >= MAX_COMMANDS && !regs.commands.iter().any(|c| c.id == cmd.id) { - return Err(wasmtime::Error::msg(format!("too many commands (max {MAX_COMMANDS})"))); - } - if regs.add_command(cmd) { - self.effects.commands_changed = true; - } - Ok(()) - } - - fn show_notification( - &mut self, - level: wit_types::NotificationLevel, - title: String, - body: String, - ) -> wasmtime::Result<()> { - let level = match level { - wit_types::NotificationLevel::Info => NotificationLevel::Info, - wit_types::NotificationLevel::Warning => NotificationLevel::Warning, - wit_types::NotificationLevel::Error => NotificationLevel::Error, - }; - self.emit(PluginEvent::Notification { - plugin_id: self.plugin_id.clone(), - level, - title: clip(title, MAX_TITLE), - body: clip(body, 16 << 10), - }); - Ok(()) - } - - fn workspace_root(&mut self) -> wasmtime::Result> { - self.require(Permission::ProjectRead)?; - Ok(self.invocation.workspace_root.as_ref().map(|p| p.to_string_lossy().into_owned())) - } - - fn active_file(&mut self) -> wasmtime::Result> { - self.require(Permission::EditorRead)?; - Ok((self.active_file)(self.invocation.client.as_deref())) - } - - fn read_file(&mut self, path: String) -> wasmtime::Result> { - self.require(Permission::ProjectRead)?; - let Some(root) = self.invocation.workspace_root.clone() else { - return Ok(Err("no project is open".into())); - }; - let real = match sandbox::resolve_in_root(&root, &path) { - Ok(real) => real, - Err(e) => return Ok(Err(e)), - }; - if let Some(text) = self.invocation.buffer_text.as_ref().and_then(|f| f(&real)) { - return Ok(Ok(text)); - } - Ok(sandbox::read_text(&real)) - } - - fn insert_text(&mut self, text: String) -> wasmtime::Result<()> { - self.require(Permission::EditorWrite)?; - self.emit(PluginEvent::InsertText { plugin_id: self.plugin_id.clone(), text: clip(text, MAX_TEXT) }); - Ok(()) - } - - fn replace_selection(&mut self, text: String) -> wasmtime::Result<()> { - self.require(Permission::EditorWrite)?; - self.emit(PluginEvent::ReplaceSelection { plugin_id: self.plugin_id.clone(), text: clip(text, MAX_TEXT) }); - Ok(()) - } - - fn register_language(&mut self, definition: String) -> wasmtime::Result> { - Ok(parse_language(&definition).map(|cfg| { - self.registrations.lock().add_language(cfg); - self.effects.commands_changed = true; - })) - } - - fn register_theme(&mut self, definition: String) -> wasmtime::Result> { - Ok(ThemeDef::parse(&definition).map(|theme| { - self.effects.themes_changed.push(theme.id.clone()); - self.registrations.lock().add_theme(theme); - self.effects.commands_changed = true; - })) - } -} - /// A call failed: either the plugin returned an error (it stays usable) or it /// trapped / ran out of budget (the instance is poisoned and must be dropped). #[derive(Debug)] -pub(crate) enum CallError { - Guest(String), +pub enum CallError { + /// The plugin returned an error. + Guest(GuestError), + /// The instance trapped (panic, fuel, memory, timeout) and is unusable. Trap(String), } -pub(crate) struct RuntimeSetup { +impl CallError { + fn missing_export(interface: &str) -> Self { + Self::Guest(GuestError::Failed(format!("the plugin does not export {interface}"))) + } +} + +impl std::fmt::Display for CallError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Guest(e) => e.fmt(f), + Self::Trap(e) => f.write_str(e), + } + } +} + +/// An error a plugin returned (the API's `error` variant). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum GuestError { + /// A capability it needs is not granted. + Denied(String), + Stale, + NotFound(String), + Invalid(String), + /// The user cancelled, or the plugin is being stopped. + Cancelled, + Failed(String), +} + +impl GuestError { + /// Whether this is the plugin failing, as opposed to an outcome the + /// user or the host caused (cancelling, a missing grant, bad input). + pub fn is_failure(&self) -> bool { + matches!(self, Self::Failed(_)) + } +} + +impl std::fmt::Display for GuestError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Denied(c) => write!(f, "permission {c} was not granted"), + Self::Stale => f.write_str("the document changed meanwhile"), + Self::NotFound(m) => write!(f, "not found: {m}"), + Self::Invalid(m) => write!(f, "invalid: {m}"), + Self::Cancelled => f.write_str("cancelled"), + Self::Failed(m) => f.write_str(m), + } + } +} + +impl From for ide_core::IdeError { + fn from(e: GuestError) -> Self { + use ide_core::error::ErrorKind; + let kind = match &e { + GuestError::Denied(_) => ErrorKind::PermissionDenied, + GuestError::Stale => ErrorKind::OutOfSync, + GuestError::NotFound(_) => ErrorKind::NotFound, + GuestError::Invalid(_) => ErrorKind::InvalidInput, + GuestError::Cancelled => ErrorKind::Cancelled, + GuestError::Failed(_) => ErrorKind::Internal, + }; + ide_core::IdeError::new(kind, e.to_string()) + } +} + +pub struct RuntimeSetup { pub plugin_id: String, pub version: String, - pub permissions: Vec, - pub registrations: Arc>, - pub sink: Arc, - pub active_file: ActiveFileFn, + /// Capabilities granted to the plugin. + pub granted: Vec, + pub host: Arc, pub limits: Limits, } -pub(crate) struct Runtime { +pub struct Runtime { store: Store, - plugin: bindings::Plugin, + exports: Exports, limits: Limits, version: String, } +/// What the component exports: the `plugin` world, plus optional interfaces. +struct Exports { + plugin: bindings::Plugin, + syntax: Option, + providers: Option, + views: Option, +} + +/// Most results one syntax call may return (more are dropped). +const MAX_SYNTAX_ITEMS: usize = 200_000; +/// Most events per delivered batch. +const MAX_BATCH: usize = 1000; + +fn event_to_wit(e: WorkbenchEvent) -> wit_events::Event { + use crate::types::ActionSource as S; + match e { + WorkbenchEvent::FileOpened(p) => wit_events::Event::FileOpened(p), + WorkbenchEvent::FileSaved(p) => wit_events::Event::FileSaved(p), + WorkbenchEvent::EditorFocused(p) => wit_events::Event::EditorFocused(p), + WorkbenchEvent::VcsChanged(p) => wit_events::Event::VcsChanged(p), + WorkbenchEvent::Scheduled => wit_events::Event::Scheduled, + WorkbenchEvent::ActionPerformed(a) => wit_events::Event::ActionPerformed(wit_events::ActionPerformed { + action: a.action, + title: a.title, + source: match a.source { + S::Keyboard => wit_events::ActionSource::Keyboard, + S::Menu => wit_events::ActionSource::Menu, + S::Toolbar => wit_events::ActionSource::Toolbar, + S::ContextMenu => wit_events::ActionSource::ContextMenu, + S::Search => wit_events::ActionSource::Search, + S::Other => wit_events::ActionSource::Other, + }, + shortcut: a.shortcut, + }), + } +} + impl Runtime { pub fn instantiate(engine: &PluginEngine, component: &Component, setup: RuntimeSetup) -> Result { let stderr = MemoryOutputPipe::new(STDERR_CAPACITY); // No preopened dirs, env, args or network: host imports are the only way out. let wasi = WasiCtx::builder().stderr(stderr.clone()).build(); - let limits = StoreLimitsBuilder::new() + let store_limits = StoreLimitsBuilder::new() .memory_size(setup.limits.memory_bytes) .instances(32) .tables(64) .memories(8) .trap_on_grow_failure(true) .build(); + let now = Instant::now(); let data = StoreData { + deadline: now + setup.limits.timeout, + timeout: setup.limits.timeout, + call_started: now, + cancel: Arc::default(), + limits: setup.limits, wasi, table: ResourceTable::new(), - limits, + store_limits, stderr, stderr_seen: 0, plugin_id: setup.plugin_id, - permissions: setup.permissions, - registrations: setup.registrations, - sink: setup.sink, + granted: setup.granted, + host: setup.host, invocation: Invocation::default(), - active_file: setup.active_file, - effects: CallEffects::default(), + open_tasks: Vec::new(), + last_report: None, }; let mut store = Store::new(&engine.engine, data); - store.limiter(|d| &mut d.limits); - store.epoch_deadline_trap(); - arm(&mut store, &setup.limits).map_err(|e| e.to_string())?; - let plugin = bindings::Plugin::instantiate(&mut store, component, &engine.linker) - .map_err(|e| describe_trap(&e, &setup.limits))?; - Ok(Self { store, plugin, limits: setup.limits, version: setup.version }) + store.limiter(|d| &mut d.store_limits); + // Checked every epoch tick: the per-call deadline and cancellation. + store.epoch_deadline_callback(|ctx| { + let data = ctx.data(); + if data.cancel.is_set() { + Err(wasmtime::Error::msg(CANCELLED)) + } else if Instant::now() >= data.deadline { + Err(wasmtime::Error::msg(format!("timed out after {:?}", data.timeout))) + } else { + Ok(UpdateDeadline::Continue(1)) + } + }); + arm(&mut store, &setup.limits, setup.limits.timeout).map_err(|e| e.to_string())?; + let api_hint = |e: wasmtime::Error| { + let msg = describe_trap(&e, &setup.limits); + if msg.contains("openidea:plugin/") { + format!("{msg} (the component was built for a different plugin API; this IDE runs API {API_VERSION})") + } else { + msg + } + }; + let pre = engine.linker.instantiate_pre(component).map_err(api_hint)?; + let plugin_indices = bindings::PluginIndices::new(&pre).map_err(api_hint)?; + let syntax_indices = wit_syntax::GuestIndices::new(&pre).ok(); + let provider_indices = wit_prov::GuestIndices::new(&pre).ok(); + let view_indices = wit_view::GuestIndices::new(&pre).ok(); + let instance = pre.instantiate(&mut store).map_err(api_hint)?; + let plugin = plugin_indices.load(&mut store, &instance).map_err(api_hint)?; + let syntax = match syntax_indices { + Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?), + None => None, + }; + let providers = match provider_indices { + Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?), + None => None, + }; + let views = match view_indices { + Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?), + None => None, + }; + Ok(Self { + store, + exports: Exports { plugin, syntax, providers, views }, + limits: setup.limits, + version: setup.version, + }) } - pub fn activate(&mut self) -> Result { + /// The component exports `syntax-provider`. + pub fn has_syntax(&self) -> bool { + self.exports.syntax.is_some() + } + + pub fn syntax_highlights( + &mut self, + language: &str, + text: &str, + timeout: Duration, + ) -> Result, CallError> { + let tokens = self.syntax_call(timeout, |s, store| s.call_highlights(store, language, text))?; + Ok(tokens + .into_iter() + .take(MAX_SYNTAX_ITEMS) + .map(|t| SyntaxToken { start: t.start, end: t.end, kind: clip(t.kind, 32) }) + .collect()) + } + + pub fn syntax_outline( + &mut self, + language: &str, + text: &str, + timeout: Duration, + ) -> Result, CallError> { + let symbols = self.syntax_call(timeout, |s, store| s.call_outline(store, language, text))?; + Ok(symbols + .into_iter() + .take(MAX_SYNTAX_ITEMS) + .map(|s| SyntaxSymbol { + name: clip(s.name, MAX_TITLE), + detail: s.detail.map(|d| clip(d, MAX_TITLE)), + kind: clip(s.kind, 32), + start: s.start, + end: s.end, + name_start: s.name_start, + name_end: s.name_end, + parent: s.parent, + }) + .collect()) + } + + pub fn syntax_folding( + &mut self, + language: &str, + text: &str, + timeout: Duration, + ) -> Result, CallError> { + let folds = self.syntax_call(timeout, |s, store| s.call_folding(store, language, text))?; + Ok(folds + .into_iter() + .take(MAX_SYNTAX_ITEMS) + .map(|f| SyntaxFold { start_line: f.start_line, end_line: f.end_line, kind: clip(f.kind, 32) }) + .collect()) + } + + fn syntax_call( + &mut self, + timeout: Duration, + f: impl FnOnce(&wit_syntax::Guest, &mut Store) -> wasmtime::Result, + ) -> Result { + if self.exports.syntax.is_none() { + return Err(CallError::missing_export("syntax-provider")); + } + self.call(Invocation::default(), timeout, |exports, store| f(exports.syntax.as_ref().expect("checked"), store)) + } + + /// The component exports `providers`. + pub fn has_providers(&self) -> bool { + self.exports.providers.is_some() + } + + fn provider_call( + &mut self, + timeout: Duration, + f: impl FnOnce(&wit_prov::Guest, &mut Store) -> wasmtime::Result, + ) -> Result { + if self.exports.providers.is_none() { + return Err(CallError::missing_export("providers")); + } + self.call(Invocation::default(), timeout, |e, store| f(e.providers.as_ref().expect("checked"), store)) + } + + pub fn provide_completion( + &mut self, + doc: &ProviderDocument, + at: ide_core::Pos, + trigger: Option<&str>, + timeout: Duration, + ) -> Result, CallError> { + let d = doc_to_wit(doc); + let items = self.provider_call(timeout, |p, s| p.call_completion(s, &d, pos_to_wit(at), trigger))?; + Ok(items + .into_iter() + .take(MAX_PROVIDER_ITEMS) + .map(|i| CompletionItem { + label: clip(i.label, MAX_TITLE), + detail: i.detail.map(|d| clip(d, MAX_TITLE)), + kind: i.kind.map(|k| clip(k, 32)), + insert_text: clip(i.insert_text, 64 << 10), + replace: i.replace.map(range_from_wit), + sort_text: i.sort_text.map(|t| clip(t, 64)), + documentation: i.documentation.map(|d| clip(d, 16 << 10)), + }) + .collect()) + } + + pub fn provide_inline_completion( + &mut self, + doc: &ProviderDocument, + at: ide_core::Pos, + timeout: Duration, + ) -> Result, CallError> { + let d = doc_to_wit(doc); + let s = self.provider_call(timeout, |p, s| p.call_inline_completion(s, &d, pos_to_wit(at)))?; + Ok(s.map(|s| InlineSuggestion { + insert_text: clip(s.insert_text, 64 << 10), + replace: s.replace.map(range_from_wit), + })) + } + + pub fn provide_code_actions( + &mut self, + doc: &ProviderDocument, + selection: ide_core::Range, + timeout: Duration, + ) -> Result, CallError> { + let d = doc_to_wit(doc); + let actions = self.provider_call(timeout, |p, s| p.call_code_actions(s, &d, range_to_wit(selection)))?; + Ok(actions + .into_iter() + .take(MAX_PROVIDER_ITEMS) + .map(|a| CodeAction { + title: clip(a.title, MAX_TITLE), + kind: a.kind.map(|k| clip(k, 64)), + preferred: a.preferred, + edits: a + .edits + .into_iter() + .map(|f| { + let edits = f + .edits + .into_iter() + .map(|e| ide_core::TextEdit { range: range_from_wit(e.range), new_text: e.text }) + .collect(); + (std::path::PathBuf::from(f.path), edits) + }) + .collect(), + }) + .collect()) + } + + pub fn provide_definition( + &mut self, + doc: &ProviderDocument, + at: ide_core::Pos, + timeout: Duration, + ) -> Result, CallError> { + let d = doc_to_wit(doc); + let locations = self.provider_call(timeout, |p, s| p.call_definition(s, &d, pos_to_wit(at)))?; + Ok(locations.into_iter().take(MAX_PROVIDER_ITEMS).map(location_from_wit).collect()) + } + + pub fn provide_line_markers( + &mut self, + doc: &ProviderDocument, + timeout: Duration, + ) -> Result, CallError> { + let d = doc_to_wit(doc); + let markers = self.provider_call(timeout, |p, s| p.call_line_markers(s, &d))?; + Ok(markers + .into_iter() + .take(MAX_PROVIDER_ITEMS) + .map(|m| LineMarker { + line: m.line, + icon: m.icon.map(|i| clip(i, 32)), + tooltip: clip(m.tooltip, 1024), + target: m.target.map(location_from_wit), + }) + .collect()) + } + + pub fn activate(&mut self) -> Result<(), CallError> { let data = self.store.data(); let ctx = wit_types::Context { plugin_id: data.plugin_id.clone(), plugin_version: self.version.clone(), api_version: API_VERSION.into(), - permissions: data.permissions.iter().map(|p| p.as_str().to_owned()).collect(), + capabilities: data.granted.iter().map(|c| c.to_string()).collect(), }; - self.call(Invocation::default(), |plugin, store| plugin.call_activate(store, &ctx)) - .and_then(|(r, fx)| r.map(|()| fx).map_err(CallError::Guest)) + self.call(Invocation::default(), self.limits.timeout, |e, store| { + e.plugin.openidea_plugin_lifecycle().call_activate(store, &ctx) + }) + .and_then(|r| r.map_err(|e| CallError::Guest(e.into()))) } pub fn run_command( @@ -359,37 +771,118 @@ impl Runtime { id: &str, arg: Option<&str>, invocation: Invocation, - ) -> Result<(Option, CallEffects), CallError> { - let (result, fx) = self.call(invocation, |plugin, store| plugin.call_run_command(store, id, arg))?; - result.map(|v| (v, fx)).map_err(CallError::Guest) + ) -> Result, CallError> { + let result = self.call(invocation, self.limits.timeout, |e, store| { + let ctx = store.data_mut().new_invocation()?; + let r = e.plugin.openidea_plugin_commands().call_run( + &mut *store, + id, + wasmtime::component::Resource::new_borrow(ctx.rep()), + arg, + ); + store.data_mut().drop_invocation(ctx); + r + })?; + result.map_err(|e| CallError::Guest(e.into())) + } + + /// The component exports `view-provider`. + pub fn has_views(&self) -> bool { + self.exports.views.is_some() + } + + /// Content of a view or custom editor (`invocation.editor`: its document). + pub fn render_view( + &mut self, + view: &str, + viewport: Option, + invocation: Invocation, + ) -> Result { + if self.exports.views.is_none() { + return Err(CallError::missing_export("view-provider")); + } + let viewport = viewport.map(|v| wit_vt::Viewport { first_row: v.first_row, rows: v.rows.min(MAX_TABLE_ROWS) }); + let result = self.call(invocation, self.limits.timeout, |e, store| { + let ctx = store.data_mut().new_invocation()?; + let views = e.views.as_ref().expect("checked"); + let r = + views.call_render(&mut *store, view, viewport, wasmtime::component::Resource::new_borrow(ctx.rep())); + store.data_mut().drop_invocation(ctx); + r + })?; + match result { + Ok(v) => Ok(view_from_wit(v)), + Err(e) => Err(CallError::Guest(e.into())), + } + } + + /// A user action in a view or custom editor. + pub fn view_event(&mut self, view: &str, event: ViewEvent, invocation: Invocation) -> Result<(), CallError> { + if self.exports.views.is_none() { + return Err(CallError::missing_export("view-provider")); + } + let event = event_to_wit_view(event); + let result = self.call(invocation, self.limits.timeout, |e, store| { + let ctx = store.data_mut().new_invocation()?; + let views = e.views.as_ref().expect("checked"); + let r = views.call_handle(&mut *store, view, &event, wasmtime::component::Resource::new_borrow(ctx.rep())); + store.data_mut().drop_invocation(ctx); + r + })?; + result.map_err(|e| CallError::Guest(e.into())) + } + + /// Delivers a batch of events (from the window in `invocation`). + pub fn handle_events(&mut self, events: Vec, invocation: Invocation) -> Result<(), CallError> { + let events: Vec = events.into_iter().take(MAX_BATCH).map(event_to_wit).collect(); + self.call(invocation, self.limits.timeout, |e, store| { + let ctx = store.data_mut().new_invocation()?; + let r = e.plugin.openidea_plugin_event_handler().call_handle( + &mut *store, + &events, + wasmtime::component::Resource::new_borrow(ctx.rep()), + ); + store.data_mut().drop_invocation(ctx); + r + }) } /// Best effort; errors are logged. pub fn deactivate(&mut self) { - if let Err(CallError::Trap(e) | CallError::Guest(e)) = - self.call(Invocation::default(), |plugin, store| plugin.call_deactivate(store)) - { + if let Err(e) = self.call(Invocation::default(), self.limits.timeout, |e, store| { + e.plugin.openidea_plugin_lifecycle().call_deactivate(store) + }) { tracing::warn!(plugin = %self.store.data().plugin_id, "deactivate failed: {e}"); } } + /// Interrupts the running call when cancelled (the instance is then + /// poisoned, like after a timeout). Reset when the next call starts. + pub fn cancel_handle(&self) -> Arc { + self.store.data().cancel.clone() + } + fn call( &mut self, invocation: Invocation, - f: impl FnOnce(&bindings::Plugin, &mut Store) -> wasmtime::Result, - ) -> Result<(R, CallEffects), CallError> { - arm(&mut self.store, &self.limits).map_err(|e| CallError::Trap(e.to_string()))?; + timeout: Duration, + f: impl FnOnce(&Exports, &mut Store) -> wasmtime::Result, + ) -> Result { + arm(&mut self.store, &self.limits, timeout).map_err(|e| CallError::Trap(e.to_string()))?; self.store.data_mut().invocation = invocation; - let result = f(&self.plugin, &mut self.store); + let result = f(&self.exports, &mut self.store); let data = self.store.data_mut(); data.invocation = Invocation::default(); - let effects = std::mem::take(&mut data.effects); + // Tasks don't outlive the call that began them. + for id in std::mem::take(&mut data.open_tasks) { + data.host.task_end(id); + } let stderr = data.drain_stderr(); if !stderr.trim().is_empty() { tracing::info!(plugin = %data.plugin_id, "stderr: {}", stderr.trim_end()); } match result { - Ok(r) => Ok((r, effects)), + Ok(r) => Ok(r), Err(e) => { let mut msg = describe_trap(&e, &self.limits); // Typically the panic message: "panicked at src/lib.rs:1:2:\nboom". @@ -405,17 +898,56 @@ impl Runtime { } } -fn arm(store: &mut Store, limits: &Limits) -> wasmtime::Result<()> { +/// Most items one provider call may return (more are dropped). +const MAX_PROVIDER_ITEMS: usize = 10_000; + +fn pos_to_wit(p: ide_core::Pos) -> wit_types::Position { + wit_types::Position { line: p.line, character: p.col } +} + +fn range_to_wit(r: ide_core::Range) -> wit_types::Range { + wit_types::Range { start: pos_to_wit(r.start), end: pos_to_wit(r.end) } +} + +fn range_from_wit(r: wit_types::Range) -> ide_core::Range { + ide_core::Range::new( + ide_core::Pos::new(r.start.line, r.start.character), + ide_core::Pos::new(r.end.line, r.end.character), + ) +} + +fn location_from_wit(l: wit_types::Location) -> Location { + Location { path: std::path::PathBuf::from(l.path), range: range_from_wit(l.range) } +} + +fn doc_to_wit(d: &ProviderDocument) -> wit_prov::Document { + wit_prov::Document { + path: d.path.to_string_lossy().into_owned(), + language: d.language.clone(), + version: d.version, + text: d.text.clone(), + } +} + +/// Resets the budgets for the next call: fuel, deadline, cancellation. +fn arm(store: &mut Store, limits: &Limits, timeout: Duration) -> wasmtime::Result<()> { store.set_fuel(limits.fuel)?; - let ticks = (limits.timeout.as_millis() / EPOCH_TICK.as_millis()).max(1) as u64; - store.set_epoch_deadline(ticks); + let data = store.data_mut(); + let now = Instant::now(); + data.call_started = now; + data.deadline = now + timeout; + data.timeout = timeout; + data.last_report = None; + data.cancel.reset(); + // The callback above runs every tick and decides. + store.set_epoch_deadline(1); Ok(()) } fn describe_trap(e: &wasmtime::Error, limits: &Limits) -> String { match e.downcast_ref::() { Some(wasmtime::Trap::OutOfFuel) => format!("exceeded its CPU budget ({} fuel per call)", limits.fuel), - Some(wasmtime::Trap::Interrupt) => format!("timed out after {:?}", limits.timeout), + Some(wasmtime::Trap::Interrupt) => CANCELLED.to_owned(), Some(wasmtime::Trap::UnreachableCodeReached) => "crashed (panic / unreachable)".to_owned(), Some(trap) => format!("trapped: {trap}"), None => { @@ -428,3 +960,110 @@ fn describe_trap(e: &wasmtime::Error, limits: &Limits) -> String { } } } + +/// Most table rows one render returns (and a viewport asks for). +const MAX_TABLE_ROWS: u32 = 2_000; +/// Most tree / list items and form fields per view. +const MAX_VIEW_ITEMS: usize = 20_000; +const MAX_CELL: usize = 64 << 10; +const MAX_HTML: usize = 4 << 20; + +fn opt_clip(s: Option, max: usize) -> Option { + s.map(|s| clip(s, max)) +} + +fn view_from_wit(v: wit_vt::View) -> View { + let body = match v.body { + wit_vt::Body::Message(m) => ViewBody::Message(clip(m, 16 << 10)), + wit_vt::Body::Tree(items) => ViewBody::Tree( + items + .into_iter() + .take(MAX_VIEW_ITEMS) + .map(|i| ViewTreeItem { + key: clip(i.key, 1024), + parent: opt_clip(i.parent, 1024), + label: clip(i.label, MAX_TITLE), + icon: opt_clip(i.icon, 64), + detail: opt_clip(i.detail, MAX_TITLE), + expandable: i.expandable, + expanded: i.expanded, + }) + .collect(), + ), + wit_vt::Body::List(items) => ViewBody::List( + items + .into_iter() + .take(MAX_VIEW_ITEMS) + .map(|i| ViewListItem { + key: clip(i.key, 1024), + label: clip(i.label, MAX_TITLE), + icon: opt_clip(i.icon, 64), + detail: opt_clip(i.detail, MAX_TITLE), + }) + .collect(), + ), + wit_vt::Body::Form(fields) => ViewBody::Form( + fields + .into_iter() + .take(MAX_VIEW_ITEMS) + .map(|f| ViewField { + key: clip(f.key, 128), + label: clip(f.label, MAX_TITLE), + value: match f.value { + wit_vt::FieldValue::Text(t) => FieldValue::Text(clip(t, MAX_CELL)), + wit_vt::FieldValue::Multiline(t) => FieldValue::Multiline(clip(t, 1 << 20)), + wit_vt::FieldValue::Checkbox(b) => FieldValue::Checkbox(b), + wit_vt::FieldValue::Choice((options, selected)) => FieldValue::Choice { + options: options.into_iter().take(1000).map(|o| clip(o, MAX_TITLE)).collect(), + selected: clip(selected, MAX_TITLE), + }, + }, + }) + .collect(), + ), + wit_vt::Body::Table(t) => ViewBody::Table(ViewTable { + columns: t.columns.into_iter().take(1000).map(|c| clip(c, MAX_TITLE)).collect(), + total_rows: t.total_rows, + first_row: t.first_row, + rows: t + .rows + .into_iter() + .take(MAX_TABLE_ROWS as usize) + .map(|r| r.into_iter().take(1000).map(|c| clip(c, MAX_CELL)).collect()) + .collect(), + editable: t.editable, + }), + wit_vt::Body::Html(h) => ViewBody::Html(clip(h, MAX_HTML)), + }; + View { + toolbar: v + .toolbar + .into_iter() + .take(32) + .map(|b| ViewButton { + id: clip(b.id, 64), + label: clip(b.label, MAX_TITLE), + icon: opt_clip(b.icon, 64), + enabled: b.enabled, + }) + .collect(), + body, + status: opt_clip(v.status, 1024), + } +} + +fn event_to_wit_view(e: ViewEvent) -> wit_vt::ViewEvent { + use wit_vt::ViewEvent as W; + match e { + ViewEvent::Button { id } => W::Button(id), + ViewEvent::Activate { key } => W::Activate(key), + ViewEvent::Select { key } => W::Select(key), + ViewEvent::Expand { key } => W::Expand(key), + ViewEvent::Collapse { key } => W::Collapse(key), + ViewEvent::Field { key, value } => W::Field((key, value)), + ViewEvent::Cell { row, column, value } => W::Cell(wit_vt::CellEdit { row, column, value }), + ViewEvent::InsertRow { before } => W::InsertRow(before), + ViewEvent::DeleteRows { rows } => W::DeleteRows(rows), + ViewEvent::Message { text } => W::Message(text), + } +} diff --git a/crates/ide-plugin/src/types.rs b/crates/ide-plugin/src/types.rs index 47890f3d..9b4dfed0 100644 --- a/crates/ide-plugin/src/types.rs +++ b/crates/ide-plugin/src/types.rs @@ -1,11 +1,8 @@ -//! UI-facing types and the event stream. +//! Types shared by the runtime and the host. -use crate::manifest::{CommandDecl, Permission}; -use crate::theme::{ThemeDef, ThemeKind}; use serde::{Deserialize, Serialize}; use specta::Type; -use std::path::{Path, PathBuf}; -use std::sync::Arc; +use std::path::PathBuf; use std::time::Duration; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] @@ -16,156 +13,457 @@ pub enum NotificationLevel { Error, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub enum PluginSource { - /// Installed under `/plugins//`. - Installed, - /// Loaded from `/.openidea/plugins//` while that project is open. - Dev, +/// The focused editor of the window a command came from. +#[derive(Clone, Debug, Default)] +pub struct EditorContext { + pub path: PathBuf, + pub language: String, + /// Selections when the command was invoked (cursors are empty ranges). + pub selections: Vec, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub enum PluginStatus { - /// Code loaded and activated. - Active, - /// No code; static contributions only. - Static, - Disabled, - /// Failed to load, or trapped and was disabled for this session (see `error`). - Failed, -} - -#[derive(Clone, Debug, Serialize, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub struct PluginLanguage { - pub id: String, - pub name: String, - pub extensions: Vec, -} - -#[derive(Clone, Debug, Serialize, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub struct PluginTheme { - pub id: String, - pub name: String, - pub kind: ThemeKind, -} - -#[derive(Clone, Debug, Serialize, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub struct PluginInfo { - pub id: String, - pub name: String, - pub version: String, - pub description: String, - pub authors: Vec, - pub homepage: Option, - pub change_notes: Option, - pub source: PluginSource, - /// Package directory. - pub path: ide_core::IpcPath, - pub enabled: bool, - pub status: PluginStatus, - pub error: Option, - pub has_code: bool, - pub permissions: Vec, - /// Commands contributed while enabled (manifest + registered at runtime). - pub commands: Vec, - pub languages: Vec, - pub themes: Vec, -} - -/// A plugin package available for installation from a local catalog -/// directory (the samples shipped with the IDE). Not installed by listing it. -#[derive(Clone, Debug, Serialize, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub struct CatalogPlugin { - pub id: String, - pub name: String, - pub version: String, - pub description: String, - pub authors: Vec, - pub homepage: Option, - pub change_notes: Option, - /// Package directory; install with `install_from_path(path)`. - pub path: ide_core::IpcPath, - pub has_code: bool, - pub permissions: Vec, - pub commands: Vec, - pub language_count: u32, - pub theme_count: u32, - /// Why the package cannot be installed as is (e.g. its WASM is not built). - pub problem: Option, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub struct ActiveTheme { - pub plugin_id: String, - pub theme: ThemeDef, -} - -#[derive(Clone, Debug, Serialize, Deserialize, Type)] -#[serde(rename_all = "camelCase")] -pub struct PluginsSnapshot { - pub plugins: Vec, - pub active_theme: Option, -} - -/// Backend → UI notifications (Tauri event `ide://plugin`). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] -#[serde(tag = "type", rename_all = "camelCase")] -pub enum PluginEvent { - /// Plugins, their status or their commands changed: re-fetch `plugin_list`. - CommandsChanged, - #[serde(rename_all = "camelCase")] - Notification { plugin_id: String, level: NotificationLevel, title: String, body: String }, - #[serde(rename_all = "camelCase")] - InsertText { plugin_id: String, text: String }, - #[serde(rename_all = "camelCase")] - ReplaceSelection { plugin_id: String, text: String }, - #[serde(rename_all = "camelCase")] - ThemeChanged { theme: Option }, -} - -/// Delivers events to the UI. `client` is the window that invoked the plugin -/// (`None` = broadcast, e.g. during activation). -pub trait PluginEventSink: Send + Sync { - fn emit(&self, client: Option<&str>, event: PluginEvent); -} - -impl, PluginEvent) + Send + Sync> PluginEventSink for F { - fn emit(&self, client: Option<&str>, event: PluginEvent) { - self(client, event) - } -} - -pub type BufferText = Arc Option + Send + Sync>; - -/// Where a command runs: the invoking window and its project. -#[derive(Clone, Default)] +/// Where a command or event batch comes from: the window and its project. +#[derive(Clone, Debug, Default)] pub struct Invocation { pub client: Option, pub workspace_root: Option, - /// Unsaved editor contents win over disk for `read-file`. - pub buffer_text: Option, + pub editor: Option, } -/// Per-call resource limits for plugin code. +/// A failed host call, as the plugin sees it (WIT `types.error`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum HostError { + /// Not granted; names the capability. + Denied(String), + /// The document changed since the version an edit was made for. + Stale, + NotFound(String), + Invalid(String), + Cancelled, + Failed(String), +} + +impl std::fmt::Display for HostError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Denied(c) => write!(f, "permission denied: {c} is not granted"), + Self::Stale => f.write_str("the document changed"), + Self::NotFound(m) => write!(f, "not found: {m}"), + Self::Invalid(m) => write!(f, "invalid: {m}"), + Self::Cancelled => f.write_str("cancelled"), + Self::Failed(m) => f.write_str(m), + } + } +} + +/// A plugin's status bar item. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct StatusItem { + pub text: String, + pub tooltip: Option, + /// One of the plugin's commands, run on click. + pub command: Option, +} + +/// Kinds of workbench events a plugin can subscribe to (`on-event:`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Type)] +#[serde(rename_all = "kebab-case")] +pub enum EventKind { + FileOpened, + FileSaved, + EditorFocused, + ActionPerformed, + VcsChanged, + Scheduled, +} + +impl EventKind { + pub const ALL: [Self; 6] = [ + Self::FileOpened, + Self::FileSaved, + Self::EditorFocused, + Self::ActionPerformed, + Self::VcsChanged, + Self::Scheduled, + ]; + + pub fn name(self) -> &'static str { + match self { + Self::FileOpened => "file-opened", + Self::FileSaved => "file-saved", + Self::EditorFocused => "editor-focused", + Self::ActionPerformed => "action-performed", + Self::VcsChanged => "vcs-changed", + Self::Scheduled => "scheduled", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|k| k.name() == s) + } + + /// The capability a subscription needs (`None`: `scheduled`, which the + /// manifest declares). + pub fn capability(self) -> Option { + match self { + Self::ActionPerformed => Some(ide_extension::Capability::InputEvents), + Self::Scheduled => None, + _ => Some(ide_extension::Capability::Events), + } + } +} + +/// How the user started an action. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum ActionSource { + Keyboard, + Menu, + Toolbar, + ContextMenu, + Search, + Other, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ActionPerformed { + pub action: String, + pub title: String, + pub source: ActionSource, + pub shortcut: Option, +} + +/// A workbench event delivered to plugins. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase", tag = "kind", content = "value")] +pub enum WorkbenchEvent { + FileOpened(String), + FileSaved(String), + EditorFocused(Option), + ActionPerformed(ActionPerformed), + VcsChanged(String), + Scheduled, +} + +impl WorkbenchEvent { + pub fn kind(&self) -> EventKind { + match self { + Self::FileOpened(_) => EventKind::FileOpened, + Self::FileSaved(_) => EventKind::FileSaved, + Self::EditorFocused(_) => EventKind::EditorFocused, + Self::ActionPerformed(_) => EventKind::ActionPerformed, + Self::VcsChanged(_) => EventKind::VcsChanged, + Self::Scheduled => EventKind::Scheduled, + } + } +} + +/// State of the repository containing a project (WIT `vcs.repository-status`). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RepositoryStatus { + pub root: String, + pub branch: Option, + pub commit: Option, + pub upstream: Option, + pub ahead: u32, + pub behind: u32, + pub operation: Option, + pub changed_files: u32, +} + +/// Resource limits and supervision policy for plugin code. #[derive(Clone, Copy, Debug)] pub struct Limits { /// Wasm fuel (≈ instructions) per host → plugin call. pub fuel: u64, - /// Wall-clock limit per call (epoch interruption). + /// Wall-clock limit of commands, events, activation and deactivation. pub timeout: Duration, + /// Wall-clock limit of a call that began a task (`tasks.begin`). + pub background: Duration, + /// Edit-path calls (syntax): the caller stops waiting after this and the + /// result is dropped; the plugin keeps its instance. + pub edit_soft: Duration, + /// Edit-path calls still running after this are interrupted (the instance + /// is rebuilt on next use). + pub edit_hard: Duration, /// Linear memory cap per plugin. pub memory_bytes: usize, + /// Wait before restarting after a crash; doubles with each consecutive crash. + pub restart_backoff: Duration, + /// Consecutive crashes after which the plugin is stopped for the session. + pub max_failures: u32, + /// Instances unused for this long are reclaimed (`None`: kept). + pub idle_timeout: Option, } impl Default for Limits { fn default() -> Self { - Self { fuel: 5_000_000_000, timeout: Duration::from_secs(5), memory_bytes: 256 << 20 } + Self { + fuel: 5_000_000_000, + timeout: Duration::from_secs(5), + background: Duration::from_secs(60), + edit_soft: Duration::from_millis(50), + edit_hard: Duration::from_millis(500), + memory_bytes: 256 << 20, + restart_backoff: Duration::from_secs(1), + max_failures: 3, + idle_timeout: Some(Duration::from_secs(300)), + } } } + +impl Limits { + /// Delay before the restart that follows the `failures`-th consecutive crash. + pub fn backoff(&self, failures: u32) -> Duration { + let factor = 1u32 << failures.saturating_sub(1).min(6); + (self.restart_backoff * factor).min(Duration::from_secs(60).max(self.restart_backoff)) + } +} + +/// A highlighted range from a plugin's `syntax-provider` (UTF-8 byte offsets). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SyntaxToken { + pub start: u32, + pub end: u32, + pub kind: String, +} + +/// A structure-view symbol from a plugin's `syntax-provider` (UTF-8 byte offsets). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SyntaxSymbol { + pub name: String, + pub detail: Option, + pub kind: String, + pub start: u32, + pub end: u32, + pub name_start: u32, + pub name_end: u32, + /// Index of the enclosing symbol in the same list. + pub parent: Option, +} + +/// A foldable line range from a plugin's `syntax-provider`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SyntaxFold { + pub start_line: u32, + pub end_line: u32, + pub kind: String, +} + +/// An HTTP request from a plugin (WIT `net.request`); headers may hold +/// `{{secret:}}` placeholders for the host to fill in. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HttpRequest { + pub method: String, + pub url: String, + pub headers: Vec<(String, String)>, + pub body: Option>, + pub timeout: Duration, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct HttpResponse { + pub status: u16, + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +/// What a one-off process printed (WIT `process.output`). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ProcessOutput { + pub status: Option, + pub stdout: String, + pub stderr: String, +} + +/// Where `net:` requests may go: the URL's host when it is `https`, or +/// `http` to the loopback interface. +pub fn net_host(url: &str) -> Result { + let (scheme, rest) = url.split_once("://").ok_or_else(|| format!("{url:?} is not an absolute URL"))?; + let authority = rest.split(['/', '?', '#']).next().unwrap_or_default(); + let authority = authority.rsplit_once('@').map_or(authority, |(_, h)| h); + let host = if let Some(v6) = authority.strip_prefix('[') { + v6.split(']').next().unwrap_or_default().to_owned() + } else { + authority.split(':').next().unwrap_or_default().to_ascii_lowercase() + }; + if host.is_empty() { + return Err(format!("{url:?} has no host")); + } + let loopback = matches!(host.as_str(), "localhost" | "127.0.0.1" | "::1"); + match scheme.to_ascii_lowercase().as_str() { + "https" => Ok(host), + "http" if loopback => Ok(host), + "http" => Err(format!("{url:?}: plain http is only allowed to localhost")), + other => Err(format!("{url:?}: unsupported scheme {other:?}")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn net_hosts() { + assert_eq!(net_host("https://API.example.com:8443/v1?x").unwrap(), "api.example.com"); + assert_eq!(net_host("http://localhost:11434/api").unwrap(), "localhost"); + assert_eq!(net_host("https://user:pw@h.io/").unwrap(), "h.io"); + assert!(net_host("http://example.com/").is_err()); + assert!(net_host("file:///etc/passwd").is_err()); + assert!(net_host("example.com").is_err()); + } +} + +/// The document a provider request is about. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ProviderDocument { + pub path: PathBuf, + pub language: String, + pub version: u64, + pub text: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Location { + pub path: PathBuf, + pub range: ide_core::Range, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CompletionItem { + pub label: String, + pub detail: Option, + /// WIT `completion-kind` name (`method`, `keyword`, …). + pub kind: Option, + pub insert_text: String, + pub replace: Option, + pub sort_text: Option, + pub documentation: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InlineSuggestion { + pub insert_text: String, + pub replace: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CodeAction { + pub title: String, + pub kind: Option, + pub preferred: bool, + pub edits: Vec<(PathBuf, Vec)>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LineMarker { + pub line: u32, + pub icon: Option, + pub tooltip: String, + pub target: Option, +} + +// ---- declarative views (wit/views.wit) --------------------------------------- + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ViewButton { + pub id: String, + pub label: String, + pub icon: Option, + pub enabled: bool, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ViewTreeItem { + pub key: String, + pub parent: Option, + pub label: String, + pub icon: Option, + pub detail: Option, + pub expandable: bool, + pub expanded: bool, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ViewListItem { + pub key: String, + pub label: String, + pub icon: Option, + pub detail: Option, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase", tag = "kind", content = "value")] +pub enum FieldValue { + Text(String), + Multiline(String), + Checkbox(bool), + Choice { options: Vec, selected: String }, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ViewField { + pub key: String, + pub label: String, + pub value: FieldValue, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ViewTable { + pub columns: Vec, + pub total_rows: u32, + pub first_row: u32, + pub rows: Vec>, + pub editable: bool, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase", tag = "kind", content = "value")] +pub enum ViewBody { + Message(String), + Tree(Vec), + List(Vec), + Form(Vec), + Table(ViewTable), + Html(String), +} + +/// What a view or custom editor shows. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct View { + pub toolbar: Vec, + pub body: ViewBody, + pub status: Option, +} + +/// The table rows the UI shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct Viewport { + pub first_row: u32, + pub rows: u32, +} + +/// A user action in a view. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase", tag = "kind")] +pub enum ViewEvent { + Button { id: String }, + Activate { key: String }, + Select { key: String }, + Expand { key: String }, + Collapse { key: String }, + Field { key: String, value: String }, + Cell { row: u32, column: u32, value: String }, + InsertRow { before: u32 }, + DeleteRows { rows: Vec }, + Message { text: String }, +} diff --git a/crates/ide-plugin/src/wit_host.rs b/crates/ide-plugin/src/wit_host.rs new file mode 100644 index 00000000..265f992a --- /dev/null +++ b/crates/ide-plugin/src/wit_host.rs @@ -0,0 +1,662 @@ +//! The host side of the `openidea:plugin@1.0.0` world: bindings, resource +//! types and the implementation of every import. Capabilities are checked +//! here; a missing one returns `error::denied` (the plugin can degrade). + +use crate::runtime::{StoreData, clip}; +use crate::sandbox; +use crate::types::{EditorContext, EventKind, HostError, HttpRequest, NotificationLevel, StatusItem, net_host}; +use ide_extension::Capability; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; +use wasmtime::component::Resource; + +pub(crate) mod bindings { + wasmtime::component::bindgen!({ + world: "plugin", + path: "../../wit", + imports: { default: trappable }, + with: { + "openidea:plugin/workspace.project": super::ProjectRes, + "openidea:plugin/editor.text-editor": super::EditorRes, + "openidea:plugin/invocation.invocation": super::InvocationRes, + "openidea:plugin/tasks.task": super::TaskRes, + }, + }); +} + +/// The optional `syntax-provider` export, bound on its own when present. +pub(crate) mod syntax_bindings { + wasmtime::component::bindgen!({ + world: "plugin-syntax", + path: "../../wit", + imports: { default: trappable }, + with: { + "openidea:plugin/types": super::bindings::openidea::plugin::types, + "openidea:plugin/log": super::bindings::openidea::plugin::log, + "openidea:plugin/ui": super::bindings::openidea::plugin::ui, + "openidea:plugin/storage": super::bindings::openidea::plugin::storage, + "openidea:plugin/workspace": super::bindings::openidea::plugin::workspace, + "openidea:plugin/editor": super::bindings::openidea::plugin::editor, + "openidea:plugin/invocation": super::bindings::openidea::plugin::invocation, + "openidea:plugin/vcs": super::bindings::openidea::plugin::vcs, + "openidea:plugin/events": super::bindings::openidea::plugin::events, + "openidea:plugin/tasks": super::bindings::openidea::plugin::tasks, + "openidea:plugin/diagnostics": super::bindings::openidea::plugin::diagnostics, + "openidea:plugin/net": super::bindings::openidea::plugin::net, + "openidea:plugin/secrets": super::bindings::openidea::plugin::secrets, + "openidea:plugin/process": super::bindings::openidea::plugin::process, + "openidea:plugin/views": super::bindings::openidea::plugin::views, + "openidea:plugin/settings": super::bindings::openidea::plugin::settings, + }, + }); +} + +/// The optional `providers` export. +pub(crate) mod providers_bindings { + wasmtime::component::bindgen!({ + world: "plugin-providers", + path: "../../wit", + imports: { default: trappable }, + with: { + "openidea:plugin/types": super::bindings::openidea::plugin::types, + "openidea:plugin/log": super::bindings::openidea::plugin::log, + "openidea:plugin/ui": super::bindings::openidea::plugin::ui, + "openidea:plugin/storage": super::bindings::openidea::plugin::storage, + "openidea:plugin/workspace": super::bindings::openidea::plugin::workspace, + "openidea:plugin/editor": super::bindings::openidea::plugin::editor, + "openidea:plugin/invocation": super::bindings::openidea::plugin::invocation, + "openidea:plugin/vcs": super::bindings::openidea::plugin::vcs, + "openidea:plugin/events": super::bindings::openidea::plugin::events, + "openidea:plugin/tasks": super::bindings::openidea::plugin::tasks, + "openidea:plugin/diagnostics": super::bindings::openidea::plugin::diagnostics, + "openidea:plugin/net": super::bindings::openidea::plugin::net, + "openidea:plugin/secrets": super::bindings::openidea::plugin::secrets, + "openidea:plugin/process": super::bindings::openidea::plugin::process, + "openidea:plugin/views": super::bindings::openidea::plugin::views, + "openidea:plugin/settings": super::bindings::openidea::plugin::settings, + }, + }); +} + +/// The optional `view-provider` export. +pub(crate) mod views_bindings { + wasmtime::component::bindgen!({ + world: "plugin-views", + path: "../../wit", + imports: { default: trappable }, + with: { + "openidea:plugin/types": super::bindings::openidea::plugin::types, + "openidea:plugin/log": super::bindings::openidea::plugin::log, + "openidea:plugin/ui": super::bindings::openidea::plugin::ui, + "openidea:plugin/storage": super::bindings::openidea::plugin::storage, + "openidea:plugin/workspace": super::bindings::openidea::plugin::workspace, + "openidea:plugin/editor": super::bindings::openidea::plugin::editor, + "openidea:plugin/invocation": super::bindings::openidea::plugin::invocation, + "openidea:plugin/vcs": super::bindings::openidea::plugin::vcs, + "openidea:plugin/events": super::bindings::openidea::plugin::events, + "openidea:plugin/tasks": super::bindings::openidea::plugin::tasks, + "openidea:plugin/diagnostics": super::bindings::openidea::plugin::diagnostics, + "openidea:plugin/net": super::bindings::openidea::plugin::net, + "openidea:plugin/secrets": super::bindings::openidea::plugin::secrets, + "openidea:plugin/process": super::bindings::openidea::plugin::process, + "openidea:plugin/views": super::bindings::openidea::plugin::views, + "openidea:plugin/settings": super::bindings::openidea::plugin::settings, + }, + }); +} + +use bindings::openidea::plugin::{ + diagnostics, editor, events, invocation, log, net, process, secrets, settings, storage, tasks, types as wit, ui, + vcs, views, workspace, +}; + +/// A project handle: its root. +pub struct ProjectRes { + root: PathBuf, +} + +/// The invoking window's focused editor. +pub struct EditorRes { + ctx: EditorContext, +} + +/// The current call's invocation (read from [`StoreData`]). +pub struct InvocationRes; + +pub struct TaskRes { + id: u64, +} + +const MAX_EDITS: usize = 10_000; +const MAX_DIAGNOSTICS: usize = 5_000; +const MAX_REQUEST_BODY: usize = 8 << 20; +const MAX_FIND: u32 = 10_000; +const MAX_STATUS_TEXT: usize = 128; + +type Fallible = wasmtime::Result>; + +pub(crate) fn to_wit(e: HostError) -> wit::Error { + match e { + HostError::Denied(c) => wit::Error::Denied(c), + HostError::Stale => wit::Error::Stale, + HostError::NotFound(m) => wit::Error::NotFound(m), + HostError::Invalid(m) => wit::Error::Invalid(m), + HostError::Cancelled => wit::Error::Cancelled, + HostError::Failed(m) => wit::Error::Failed(m), + } +} + +/// A guest's `error` as text (`denied: net:example.com`, `stale`, …). +impl From for crate::runtime::GuestError { + fn from(e: wit::Error) -> Self { + let clip = |m: String| clip(m, crate::runtime::MAX_TITLE * 16); + match e { + wit::Error::Denied(c) => Self::Denied(clip(c)), + wit::Error::Stale => Self::Stale, + wit::Error::NotFound(m) => Self::NotFound(clip(m)), + wit::Error::Invalid(m) => Self::Invalid(clip(m)), + wit::Error::Cancelled => Self::Cancelled, + wit::Error::Failed(m) => Self::Failed(clip(m)), + } + } +} + +fn pos(p: wit::Position) -> ide_core::Pos { + ide_core::Pos::new(p.line, p.character) +} + +fn range_to_wit(r: &ide_core::Range) -> wit::Range { + wit::Range { + start: wit::Position { line: r.start.line, character: r.start.col }, + end: wit::Position { line: r.end.line, character: r.end.col }, + } +} + +impl StoreData { + fn require(&self, cap: Capability) -> Result<(), wit::Error> { + if self.granted.iter().any(|g| g.covers(&cap)) { Ok(()) } else { Err(wit::Error::Denied(cap.to_string())) } + } + + fn client(&self) -> Option<&str> { + self.invocation.client.as_deref() + } + + fn push(&mut self, value: T) -> wasmtime::Result> { + Ok(self.table.push(value)?) + } + + pub(crate) fn new_invocation(&mut self) -> wasmtime::Result> { + self.push(InvocationRes) + } + + pub(crate) fn drop_invocation(&mut self, res: Resource) { + let _ = self.table.delete(res); + } +} + +impl wit::Host for StoreData {} + +impl log::Host for StoreData { + fn log(&mut self, level: wit::LogLevel, message: String) -> wasmtime::Result<()> { + let id = &self.plugin_id; + let message = clip(message, crate::runtime::MAX_TEXT); + match level { + wit::LogLevel::Trace => tracing::trace!(plugin = %id, "{message}"), + wit::LogLevel::Debug => tracing::debug!(plugin = %id, "{message}"), + wit::LogLevel::Info => tracing::info!(plugin = %id, "{message}"), + wit::LogLevel::Warn => tracing::warn!(plugin = %id, "{message}"), + wit::LogLevel::Error => tracing::error!(plugin = %id, "{message}"), + } + Ok(()) + } +} + +impl ui::Host for StoreData { + fn show_notification( + &mut self, + level: wit::NotificationLevel, + title: String, + body: String, + ) -> wasmtime::Result<()> { + let level = match level { + wit::NotificationLevel::Info => NotificationLevel::Info, + wit::NotificationLevel::Warning => NotificationLevel::Warning, + wit::NotificationLevel::Error => NotificationLevel::Error, + }; + let max = crate::runtime::MAX_TITLE; + self.host.notify(self.client(), level, clip(title, max), clip(body, 16 << 10)); + Ok(()) + } + + fn set_status_item(&mut self, id: String, item: ui::StatusItem) -> wasmtime::Result<()> { + let item = StatusItem { + text: clip(item.text, MAX_STATUS_TEXT), + tooltip: item.tooltip.map(|t| clip(t, 1024)), + command: item.command.map(|c| clip(c, 128)), + }; + self.host.status_item(&clip(id, 64), Some(item)); + Ok(()) + } + + fn remove_status_item(&mut self, id: String) -> wasmtime::Result<()> { + self.host.status_item(&clip(id, 64), None); + Ok(()) + } +} + +impl storage::Host for StoreData { + fn get(&mut self, key: String) -> Fallible> { + if let Err(e) = self.require(Capability::Storage) { + return Ok(Err(e)); + } + Ok(self.host.storage_get(&key).map_err(to_wit)) + } + + fn set(&mut self, key: String, value: String) -> Fallible<()> { + if let Err(e) = self.require(Capability::Storage) { + return Ok(Err(e)); + } + Ok(self.host.storage_set(&key, Some(value)).map_err(to_wit)) + } + + fn delete(&mut self, key: String) -> Fallible<()> { + if let Err(e) = self.require(Capability::Storage) { + return Ok(Err(e)); + } + Ok(self.host.storage_set(&key, None).map_err(to_wit)) + } + + fn keys(&mut self, prefix: String) -> Fallible> { + if let Err(e) = self.require(Capability::Storage) { + return Ok(Err(e)); + } + Ok(self.host.storage_keys(&prefix).map_err(to_wit)) + } +} + +impl workspace::Host for StoreData { + fn projects(&mut self) -> Fallible>> { + if let Err(e) = self.require(Capability::ProjectRead) { + return Ok(Err(e)); + } + let mut out = Vec::new(); + for root in self.host.projects() { + out.push(self.push(ProjectRes { root })?); + } + Ok(Ok(out)) + } +} + +impl workspace::HostProject for StoreData { + fn root(&mut self, this: Resource) -> Fallible { + if let Err(e) = self.require(Capability::ProjectRead) { + return Ok(Err(e)); + } + Ok(Ok(self.table.get(&this)?.root.to_string_lossy().into_owned())) + } + + fn read_file(&mut self, this: Resource, path: String) -> Fallible { + if let Err(e) = self.require(Capability::ProjectRead) { + return Ok(Err(e)); + } + let root = self.table.get(&this)?.root.clone(); + let real = match sandbox::resolve_in_root(&root, &path) { + Ok(real) => real, + Err(e) => return Ok(Err(wit::Error::Invalid(e))), + }; + if let Some(text) = self.host.buffer_text(&real) { + return Ok(Ok(text)); + } + Ok(sandbox::read_text(&real).map_err(wit::Error::Failed)) + } + + fn find_files(&mut self, this: Resource, glob: String, limit: u32) -> Fallible> { + if let Err(e) = self.require(Capability::ProjectRead) { + return Ok(Err(e)); + } + let root = self.table.get(&this)?.root.clone(); + Ok(self.host.find_files(&root, &glob, limit.min(MAX_FIND) as usize).map_err(to_wit)) + } + + fn drop(&mut self, rep: Resource) -> wasmtime::Result<()> { + self.table.delete(rep)?; + Ok(()) + } +} + +impl editor::Host for StoreData {} + +impl editor::HostTextEditor for StoreData { + fn path(&mut self, this: Resource) -> wasmtime::Result { + Ok(self.table.get(&this)?.ctx.path.to_string_lossy().into_owned()) + } + + fn language(&mut self, this: Resource) -> wasmtime::Result { + Ok(self.table.get(&this)?.ctx.language.clone()) + } + + fn document(&mut self, this: Resource) -> Fallible { + if let Err(e) = self.require(Capability::EditorRead) { + return Ok(Err(e)); + } + let path = self.table.get(&this)?.ctx.path.clone(); + Ok(match self.host.document(&path) { + Some((version, text)) => Ok(editor::Document { version, text }), + None => Err(wit::Error::NotFound(format!("{} is not open", path.display()))), + }) + } + + fn selections(&mut self, this: Resource) -> Fallible> { + if let Err(e) = self.require(Capability::EditorRead) { + return Ok(Err(e)); + } + Ok(Ok(self.table.get(&this)?.ctx.selections.iter().map(range_to_wit).collect())) + } + + fn apply_edits(&mut self, this: Resource, version: u64, edits: Vec) -> Fallible { + if let Err(e) = self.require(Capability::EditorWrite) { + return Ok(Err(e)); + } + if edits.len() > MAX_EDITS { + return Ok(Err(wit::Error::Invalid(format!("more than {MAX_EDITS} edits")))); + } + let total: usize = edits.iter().map(|e| e.text.len()).sum(); + if total > crate::runtime::MAX_TEXT * 8 { + return Ok(Err(wit::Error::Invalid("edits too large".into()))); + } + let path = self.table.get(&this)?.ctx.path.clone(); + let edits: Vec = edits + .into_iter() + .map(|e| ide_core::TextEdit { + range: ide_core::Range::new(pos(e.range.start), pos(e.range.end)), + new_text: e.text, + }) + .collect(); + let client = self.invocation.client.clone(); + Ok(self.host.apply_edits(client.as_deref(), &path, version, edits).map_err(to_wit)) + } + + fn drop(&mut self, rep: Resource) -> wasmtime::Result<()> { + self.table.delete(rep)?; + Ok(()) + } +} + +impl invocation::Host for StoreData {} + +impl invocation::HostInvocation for StoreData { + fn project(&mut self, _this: Resource) -> wasmtime::Result>> { + match self.invocation.workspace_root.clone() { + Some(root) => Ok(Some(self.push(ProjectRes { root })?)), + None => Ok(None), + } + } + + fn editor(&mut self, _this: Resource) -> wasmtime::Result>> { + match self.invocation.editor.clone() { + Some(ctx) => Ok(Some(self.push(EditorRes { ctx })?)), + None => Ok(None), + } + } + + fn drop(&mut self, rep: Resource) -> wasmtime::Result<()> { + // Owned by the host for the duration of the call. + let _ = rep; + Ok(()) + } +} + +impl vcs::Host for StoreData { + fn status(&mut self, project: Resource) -> Fallible> { + if let Err(e) = self.require(Capability::VcsRead) { + return Ok(Err(e)); + } + let root = self.table.get(&project)?.root.clone(); + Ok(self + .host + .vcs_status(&root) + .map(|s| { + s.map(|s| vcs::RepositoryStatus { + root: s.root, + branch: s.branch, + commit: s.commit, + upstream: s.upstream, + ahead: s.ahead, + behind: s.behind, + operation: s.operation, + changed_files: s.changed_files, + }) + }) + .map_err(to_wit)) + } + + fn fetch(&mut self, project: Resource) -> Fallible<()> { + if let Err(e) = self.require(Capability::VcsWrite) { + return Ok(Err(e)); + } + let root = self.table.get(&project)?.root.clone(); + let token = self.cancel.token(); + Ok(self.host.vcs_fetch(&root, &token).map_err(to_wit)) + } +} + +fn kind_from_wit(k: events::EventKind) -> EventKind { + match k { + events::EventKind::FileOpened => EventKind::FileOpened, + events::EventKind::FileSaved => EventKind::FileSaved, + events::EventKind::EditorFocused => EventKind::EditorFocused, + events::EventKind::ActionPerformed => EventKind::ActionPerformed, + events::EventKind::VcsChanged => EventKind::VcsChanged, + events::EventKind::Scheduled => EventKind::Scheduled, + } +} + +impl events::Host for StoreData { + fn subscribe(&mut self, kind: events::EventKind) -> Fallible<()> { + let kind = kind_from_wit(kind); + if let Some(cap) = kind.capability() + && let Err(e) = self.require(cap) + { + return Ok(Err(e)); + } + self.host.subscribe(kind, true); + Ok(Ok(())) + } + + fn unsubscribe(&mut self, kind: events::EventKind) -> wasmtime::Result<()> { + self.host.subscribe(kind_from_wit(kind), false); + Ok(()) + } +} + +impl tasks::Host for StoreData { + fn begin(&mut self, title: String, cancellable: bool) -> wasmtime::Result> { + let token = self.cancel.token(); + let id = self.host.task_begin(self.client(), clip(title, crate::runtime::MAX_TITLE), cancellable, token); + self.open_tasks.push(id); + // The call may now run for the background budget. + let extended = self.call_started + self.limits.background; + if extended > self.deadline { + self.deadline = extended; + self.timeout = self.limits.background; + } + self.push(TaskRes { id }) + } +} + +impl tasks::HostTask for StoreData { + fn report( + &mut self, + this: Resource, + done: u32, + total: Option, + message: Option, + ) -> wasmtime::Result<()> { + let id = self.table.get(&this)?.id; + let now = Instant::now(); + // At most ~10 updates per second reach the UI. + if self.last_report.is_none_or(|t| now.duration_since(t).as_millis() >= 100) || total.is_some_and(|t| done >= t) + { + self.last_report = Some(now); + self.host.task_report(id, done, total, message.map(|m| clip(m, 256))); + } + Ok(()) + } + + fn is_cancelled(&mut self, this: Resource) -> wasmtime::Result { + let id = self.table.get(&this)?.id; + Ok(self.cancel.token().is_cancelled() || self.host.task_cancelled(id)) + } + + fn drop(&mut self, rep: Resource) -> wasmtime::Result<()> { + let id = self.table.delete(rep)?.id; + self.open_tasks.retain(|t| *t != id); + self.host.task_end(id); + Ok(()) + } +} + +impl StoreData { + /// What is left of the running call's wall-clock budget (host operations + /// can't be interrupted by the epoch callback, so they get this as timeout). + fn remaining(&self) -> Duration { + self.deadline.saturating_duration_since(Instant::now()) + } +} + +impl diagnostics::Host for StoreData { + fn publish(&mut self, path: String, items: Vec) -> Fallible<()> { + if let Err(e) = self.require(Capability::ProjectRead) { + return Ok(Err(e)); + } + let source = self.plugin_id.clone(); + let items = items + .into_iter() + .take(MAX_DIAGNOSTICS) + .map(|d| ide_core::Diagnostic { + range: ide_core::Range::new(pos(d.range.start), pos(d.range.end)), + severity: match d.severity { + diagnostics::Severity::Error => ide_core::Severity::Error, + diagnostics::Severity::Warning => ide_core::Severity::Warning, + diagnostics::Severity::Info => ide_core::Severity::Info, + diagnostics::Severity::Hint => ide_core::Severity::Hint, + }, + message: clip(d.message, 4096), + source: Some(source.clone()), + code: d.code.map(|c| clip(c, 128)), + unnecessary: false, + deprecated: false, + server: Some(source.clone()), + }) + .collect(); + Ok(self.host.publish_diagnostics(Path::new(&path), items).map_err(to_wit)) + } +} + +impl net::Host for StoreData { + fn fetch(&mut self, req: net::Request) -> Fallible { + let host = match net_host(&req.url) { + Ok(h) => h, + Err(e) => return Ok(Err(wit::Error::Invalid(e))), + }; + if let Err(e) = self.require(Capability::Net(host)) { + return Ok(Err(e)); + } + if req.headers.iter().any(|h| h.value.contains("{{secret:")) + && let Err(e) = self.require(Capability::Secrets) + { + return Ok(Err(e)); + } + if req.body.as_ref().is_some_and(|b| b.len() > MAX_REQUEST_BODY) { + return Ok(Err(wit::Error::Invalid("request body larger than 8 MiB".into()))); + } + let wanted = Duration::from_millis(u64::from(req.timeout_ms.unwrap_or(30_000))); + let request = HttpRequest { + method: req.method, + url: req.url, + headers: req.headers.into_iter().map(|h| (h.name, h.value)).collect(), + body: req.body, + timeout: wanted.min(self.remaining()), + }; + let token = self.cancel.token(); + Ok(self + .host + .fetch(request, &token) + .map(|r| net::Response { + status: r.status, + headers: r.headers.into_iter().map(|(name, value)| net::Header { name, value }).collect(), + body: r.body, + }) + .map_err(to_wit)) + } +} + +impl secrets::Host for StoreData { + fn is_set(&mut self, name: String) -> wasmtime::Result { + Ok(self.granted.iter().any(|g| g.covers(&Capability::Secrets)) && self.host.secret_is_set(&name)) + } +} + +impl process::Host for StoreData { + fn run( + &mut self, + program: String, + args: Vec, + cwd: Option>, + stdin: Option, + ) -> Fallible { + if let Err(e) = self.require(Capability::Process(program.clone())) { + return Ok(Err(e)); + } + let cwd = match &cwd { + Some(p) => Some(self.table.get(p)?.root.clone()), + None => None, + }; + let token = self.cancel.token(); + let timeout = self.remaining(); + Ok(self + .host + .run_process(&program, args, cwd.as_deref(), stdin, &token, timeout) + .map(|o| process::Output { status: o.status, stdout: o.stdout, stderr: o.stderr }) + .map_err(to_wit)) + } +} + +impl views::Host for StoreData { + fn refresh(&mut self, view: String) -> wasmtime::Result<()> { + self.host.refresh_view(&clip(view, 64)); + Ok(()) + } + + fn post_message(&mut self, view: String, message: String) -> Fallible<()> { + if message.len() > MAX_VIEW_MESSAGE { + return Ok(Err(wit::Error::Invalid(format!("messages are limited to {MAX_VIEW_MESSAGE} bytes")))); + } + Ok(self.host.post_view_message(&clip(view, 64), message).map_err(to_wit)) + } + + fn open_terminal(&mut self, title: String, program: String, args: Vec) -> Fallible<()> { + if let Err(e) = self.require(Capability::Process(program.clone())) { + return Ok(Err(e)); + } + if args.len() > 256 || args.iter().any(|a| a.len() > 4096) { + return Ok(Err(wit::Error::Invalid("too many or too long arguments".into()))); + } + let cwd = self.invocation.workspace_root.clone(); + let client = self.invocation.client.clone(); + let title = clip(title, crate::runtime::MAX_TITLE); + Ok(self.host.open_terminal(client.as_deref(), title, &program, args, cwd.as_deref()).map_err(to_wit)) + } +} + +impl settings::Host for StoreData { + fn get(&mut self, key: String) -> wasmtime::Result> { + let root = self.invocation.workspace_root.clone(); + Ok(self.host.setting(root.as_deref(), &clip(key, 128))) + } +} + +impl views_bindings::openidea::plugin::view_types::Host for StoreData {} + +/// Largest message between a plugin and its view's frame. +const MAX_VIEW_MESSAGE: usize = 1 << 20; diff --git a/crates/ide-plugin/tests/api_compat.rs b/crates/ide-plugin/tests/api_compat.rs new file mode 100644 index 00000000..7ec2a34e --- /dev/null +++ b/crates/ide-plugin/tests/api_compat.rs @@ -0,0 +1,270 @@ +//! Plugin API versioning (plugins/README.md, "Evolving the plugin API"). +//! +//! - The `wit/` package version, `ENGINE_VERSION` and `API_VERSION` agree. +//! - The version check accepts components the host can run and explains the rest. +//! - Components built for 1.0 link against a host of a later 1.x minor that +//! adds functions and interfaces (wasmtime resolves `@1.0.0` names to a +//! semver-compatible definition), and the host finds their exports under +//! the newer name; a 2.0 host does not link them. The newer host is +//! simulated with a linker that stubs every plugin import the component has +//! at the newer version, so no copy of the WIT is needed. +//! +//! Components: the checked-in `dist/plugin.wasm` of the `hello` fixture, the +//! official plugins (`plugins/build.sh` rebuilds them). + +use ide_plugin::{API_VERSION, PluginEngine, check_api, component_api, host_api}; +use std::path::{Path, PathBuf}; +use wasmtime::component::types::ComponentItem; +use wasmtime::component::{Component, Linker, ResourceTable, ResourceType}; +use wasmtime::{Config, Engine}; +use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView}; + +fn repo() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") +} + +/// Every component the repository builds for users: the official plugins with code, plus the `hello` fixture. +fn components() -> Vec { + let mut out = vec![repo().join("crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm")]; + let official = repo().join("plugins/official"); + let mut dirs: Vec<_> = std::fs::read_dir(&official).unwrap().map(|e| e.unwrap().path()).collect(); + dirs.sort(); + out.extend(dirs.into_iter().map(|d| d.join("dist/plugin.wasm")).filter(|p| p.is_file())); + assert!(out.len() >= 9, "expected hello and the official plugins, found {out:?}"); + out +} + +fn v(s: &str) -> semver::Version { + semver::Version::parse(s).unwrap() +} + +#[test] +fn wit_package_engine_and_api_versions_agree() { + let host = host_api(); + assert_eq!(API_VERSION, format!("{}.{}", host.major, host.minor)); + let want = format!("package openidea:plugin@{host};"); + let mut files = 0; + for entry in std::fs::read_dir(repo().join("wit")).unwrap() { + let path = entry.unwrap().path(); + if path.extension().is_some_and(|e| e == "wit") { + let src = std::fs::read_to_string(&path).unwrap(); + assert!(src.lines().any(|l| l.trim() == want), "{} does not declare `{want}`", path.display()); + files += 1; + } + } + assert!(files > 1); +} + +/// The SDK ships its own copy of `wit/` (it builds outside this repository); +/// it must be the API this host implements. +#[test] +fn the_sdk_carries_the_hosts_wit() { + let read = |dir: PathBuf| { + let mut files: Vec<(String, String)> = std::fs::read_dir(&dir) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| p.extension().is_some_and(|e| e == "wit")) + .map(|p| (p.file_name().unwrap().to_string_lossy().into_owned(), std::fs::read_to_string(&p).unwrap())) + .collect(); + files.sort(); + files + }; + let host = read(repo().join("wit")); + let sdk = read(repo().join("sdk/rust/openidea-plugin/wit")); + let names = |f: &[(String, String)]| f.iter().map(|(n, _)| n.clone()).collect::>(); + assert_eq!(names(&sdk), names(&host), "sdk/rust/openidea-plugin/wit has other files than wit/"); + for ((name, a), (_, b)) in host.iter().zip(&sdk) { + assert!(a == b, "sdk/rust/openidea-plugin/wit/{name} differs from wit/{name}: copy wit/ into the SDK"); + } +} + +#[test] +fn the_version_check_runs_compatible_components_and_explains_the_rest() { + let host = v("1.3.0"); + for ok in ["1.0.0", "1.3.0", "1.3.7", "1.0.0-rc.1"] { + assert_eq!(check_api(&v(ok), &host), Ok(()), "{ok}"); + } + let newer = check_api(&v("1.4.0"), &host).unwrap_err(); + assert!(newer.contains("1.4") && newer.contains("update OpenIDEA"), "{newer}"); + assert!(check_api(&v("2.0.0"), &host).unwrap_err().contains("update OpenIDEA")); + let older = check_api(&v("0.2.0"), &host).unwrap_err(); + assert!(older.contains("rebuild it with the 1.3 SDK"), "{older}"); + // 0.x: every minor is its own API. + assert_eq!(check_api(&v("0.2.0"), &v("0.2.5")), Ok(())); + assert!(check_api(&v("0.1.0"), &v("0.2.0")).is_err()); + assert!(check_api(&v("0.3.0"), &v("0.2.0")).is_err()); +} + +#[test] +fn a_components_api_is_the_highest_plugin_interface_version() { + let names = ["wasi:io/poll@0.2.6", "openidea:plugin/log@1.0.0", "openidea:plugin/views@1.2.0"]; + assert_eq!(component_api(names), Ok(Some(v("1.2.0")))); + assert_eq!(component_api(["wasi:cli/stdout@0.2.6"]), Ok(None)); + assert!(component_api(["openidea:plugin/log"]).unwrap_err().contains("unversioned")); +} + +#[test] +fn shipped_components_are_built_for_this_api() { + let engine = PluginEngine::new().unwrap(); + let host = host_api(); + for wasm in components() { + let component = engine.compile(&wasm).unwrap(); + let built_for = engine.check_component(&component).unwrap_or_else(|e| panic!("{}: {e}", wasm.display())); + let built_for = built_for.unwrap_or_else(|| panic!("{} uses no plugin interface", wasm.display())); + assert_eq!((built_for.major, built_for.minor), (host.major, host.minor), "{}", wasm.display()); + } +} + +// --- a later host, simulated ------------------------------------------------------------- + +struct Data { + wasi: WasiCtx, + table: ResourceTable, +} + +impl WasiView for Data { + fn ctx(&mut self) -> WasiCtxView<'_> { + WasiCtxView { ctx: &mut self.wasi, table: &mut self.table } + } +} + +/// Distinct host types for the stubbed resources (a component may import several). +struct Stub; + +fn stub_resource(n: usize) -> ResourceType { + macro_rules! pick { ($($i:literal)*) => { match n { $($i => ResourceType::host::>(),)* _ => panic!("more than 16 resources") } } } + pick!(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) +} + +enum Host<'a> { + /// Defines everything the component imports, plus a function and an + /// interface the component doesn't know. + Superset, + /// Leaves out one function, so linking must fail. + Without(&'a str), +} + +/// A linker with WASI and every `openidea:plugin/*` interface `component` +/// imports, defined at `version` with functions that are never called. +fn host_at(engine: &Engine, component: &Component, version: &str, host: Host<'_>) -> Linker { + let mut linker = Linker::new(engine); + wasmtime_wasi::p2::add_to_linker_sync(&mut linker).unwrap(); + // The component's resource → its stub. A resource re-exported through + // `use` (`invocation` uses `editor.text-editor`) is the same type, so it + // must get the same stub. + let mut resources: Vec<(ResourceType, ResourceType)> = Vec::new(); + for (name, item) in component.component_type().imports(engine) { + let Some(rest) = name.strip_prefix("openidea:plugin/") else { continue }; + let iface = rest.split_once('@').map_or(rest, |(i, _)| i); + let ComponentItem::ComponentInstance(instance) = item.ty else { panic!("{name} is not an instance") }; + let mut defined = linker.instance(&format!("openidea:plugin/{iface}@{version}")).unwrap(); + for (export, item) in instance.exports(engine) { + match item.ty { + ComponentItem::ComponentFunc(_) if !matches!(host, Host::Without(f) if f == export) => { + defined.func_new(export, |_, _, _, _| Err(wasmtime::Error::msg("stub"))).unwrap(); + } + ComponentItem::Resource(ty) => { + let stub = match resources.iter().find(|(r, _)| *r == ty) { + Some((_, stub)) => *stub, + None => { + let stub = stub_resource(resources.len()); + resources.push((ty, stub)); + stub + } + }; + defined.resource(export, stub, |_, _| Ok(())).unwrap(); + } + _ => {} + } + } + if matches!(host, Host::Superset) { + defined.func_new("added-in-a-later-minor", |_, _, _, _| Ok(())).unwrap(); + } + } + if matches!(host, Host::Superset) { + let mut added = linker.instance(&format!("openidea:plugin/added-interface@{version}")).unwrap(); + added.func_new("call", |_, _, _, _| Ok(())).unwrap(); + } + linker +} + +fn engine() -> Engine { + let mut config = Config::new(); + config.wasm_component_model(true); + Engine::new(&config).unwrap() +} + +/// The next minor of the API this host implements. +fn next_minor() -> String { + let host = host_api(); + format!("{}.{}.0", host.major, host.minor + 1) +} + +#[test] +fn components_link_against_a_later_minor_that_adds_functions_and_interfaces() { + let engine = engine(); + let next = next_minor(); + for wasm in components() { + let component = Component::from_file(&engine, &wasm).unwrap(); + let linker = host_at(&engine, &component, &next, Host::Superset); + linker.instantiate_pre(&component).unwrap_or_else(|e| panic!("{}: {e:?}", wasm.display())); + + let exports: Vec = component + .component_type() + .exports(&engine) + .map(|(n, _)| n.to_owned()) + .filter(|n| n.starts_with("openidea:plugin/")) + .collect(); + assert!(!exports.is_empty(), "{} exports no plugin interface", wasm.display()); + for name in exports { + let iface = name.split_once('@').unwrap().0; + let newer = format!("{iface}@{next}"); + assert!( + component.get_export_index(None, &newer).is_some(), + "{}: a {next} host can't find export {name}", + wasm.display() + ); + } + } +} + +#[test] +fn components_do_not_link_against_another_major() { + let engine = engine(); + let next_major = format!("{}.0.0", host_api().major + 1); + let wasm = repo().join("crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm"); + let component = Component::from_file(&engine, &wasm).unwrap(); + let linker = host_at(&engine, &component, &next_major, Host::Superset); + assert!(linker.instantiate_pre(&component).is_err()); + let iface = component + .component_type() + .exports(&engine) + .map(|(n, _)| n.to_owned()) + .find(|n| n.starts_with("openidea:plugin/")) + .unwrap(); + let newer = format!("{}@{next_major}", iface.split_once('@').unwrap().0); + assert!(component.get_export_index(None, &newer).is_none()); +} + +#[test] +fn a_later_minor_that_drops_a_function_does_not_link() { + // Keeps the test above honest: the stub host really is type-checked. + let engine = engine(); + let wasm = repo().join("crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm"); + let component = Component::from_file(&engine, &wasm).unwrap(); + let (iface, func) = component + .component_type() + .imports(&engine) + .filter(|(n, _)| n.starts_with("openidea:plugin/")) + .find_map(|(n, item)| match item.ty { + ComponentItem::ComponentInstance(i) => i + .exports(&engine) + .find(|(_, it)| matches!(it.ty, ComponentItem::ComponentFunc(_))) + .map(|(f, _)| (n.to_owned(), f.to_owned())), + _ => None, + }) + .expect("hello imports a plugin function"); + let linker = host_at(&engine, &component, &next_minor(), Host::Without(&func)); + let err = linker.instantiate_pre(&component).err().unwrap_or_else(|| panic!("{iface} without {func} linked")); + assert!(format!("{err:?}").contains(&func), "{err:?}"); +} diff --git a/plugins/hello/Cargo.lock b/crates/ide-plugin/tests/fixtures/hello/Cargo.lock similarity index 98% rename from plugins/hello/Cargo.lock rename to crates/ide-plugin/tests/fixtures/hello/Cargo.lock index 2e617884..2ba582e7 100644 --- a/plugins/hello/Cargo.lock +++ b/crates/ide-plugin/tests/fixtures/hello/Cargo.lock @@ -95,12 +95,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] -name = "openidea-plugin-hello" +name = "openidea-plugin" version = "0.1.0" dependencies = [ "wit-bindgen", ] +[[package]] +name = "openidea-plugin-hello" +version = "0.1.0" +dependencies = [ + "openidea-plugin", +] + [[package]] name = "prettyplease" version = "0.3.0" diff --git a/plugins/hello/Cargo.toml b/crates/ide-plugin/tests/fixtures/hello/Cargo.toml similarity index 73% rename from plugins/hello/Cargo.toml rename to crates/ide-plugin/tests/fixtures/hello/Cargo.toml index 10ed4602..d4abeda5 100644 --- a/plugins/hello/Cargo.toml +++ b/crates/ide-plugin/tests/fixtures/hello/Cargo.toml @@ -8,10 +8,10 @@ publish = false [workspace] [lib] -crate-type = ["cdylib"] +crate-type = ["cdylib", "rlib"] [dependencies] -wit-bindgen = "0.63" +openidea-plugin = { path = "../../../../../sdk/rust/openidea-plugin" } [profile.release] opt-level = "s" diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm new file mode 100644 index 00000000..b0c8caee Binary files /dev/null and b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources new file mode 100644 index 00000000..2edfa822 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources @@ -0,0 +1 @@ +86dfe70a30ab1f7955a16e96c1b32c8be663456b871cc4d3bed7dc6052c062da diff --git a/crates/ide-plugin/tests/fixtures/hello/plugin.toml b/crates/ide-plugin/tests/fixtures/hello/plugin.toml new file mode 100644 index 00000000..6145272b --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/hello/plugin.toml @@ -0,0 +1,52 @@ +id = "hello" +name = "Hello" +version = "0.3.0" +description = "Sample plugin: inserts today's date, counts words in the active file and shows a tool window with a tree." +authors = ["OpenIDEA contributors"] +change-notes = """ +0.3.0 — a Greetings tool window (tree view), an editor context menu entry, a shortcut and a status bar item. +0.2.0 — plugin API 0.2: edits are versioned, one undo step for every cursor. +0.1.0 — first release: Insert Date and Word Count of Active File commands. +""" +engines.openidea = "^1.0" +wasm = "dist/plugin.wasm" +# Loaded the first time one of its commands runs. +activation = ["on-command:*", "on-view:greetings"] + +[capabilities] +required = ["editor.read", "editor.write"] + +# Static declarations make the commands visible before the plugin activates; +# a command must be declared here to exist. +[[contributes.commands]] +id = "insert-date" +title = "Hello: Insert Date" +category = "Hello" + +[[contributes.commands]] +id = "word-count" +title = "Hello: Word Count of Active File" +category = "Hello" + +# Declarative UI: shown without loading the plugin's code. +[[contributes.menus]] +menu = "editor.context" +command = "word-count" + +[[contributes.keymaps]] +command = "insert-date" +key = "Ctrl+Alt+D" +mac = "Meta+Alt+D" + +[[contributes.statusBar]] +id = "hello" +text = "Hello" +tooltip = "Word count of the active file" +command = "word-count" + +# A tool window whose tree the plugin renders (view-provider). +[[contributes.views]] +id = "greetings" +title = "Greetings" +icon = "plugin" +location = "right" diff --git a/crates/ide-plugin/tests/fixtures/hello/src/lib.rs b/crates/ide-plugin/tests/fixtures/hello/src/lib.rs new file mode 100644 index 00000000..26f75410 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/hello/src/lib.rs @@ -0,0 +1,180 @@ +//! Sample OpenIDEA plugin, written with the `openidea-plugin` SDK. +//! Build with `openidea-plugin build plugins/hello` (see plugins/README.md). + +use openidea_plugin::views::{Body, Button, TreeItem, View, ViewEvent, Viewport, Views}; +use openidea_plugin::{Context, Error, Invocation, LogLevel, NotificationLevel, Plugin, host, register_plugin}; +use std::collections::BTreeSet; + +#[derive(Default)] +struct Hello { + /// Expanded languages of the Greetings tree. + expanded: BTreeSet, +} + +/// The Greetings tree: languages, then their greetings (loaded when expanded). +const GREETINGS: &[(&str, &[&str])] = &[ + ("English", &["Hello", "Good morning", "Hi"]), + ("Deutsch", &["Hallo", "Guten Morgen", "Servus"]), + ("日本語", &["こんにちは", "おはよう"]), +]; + +impl Plugin for Hello { + fn activate(&mut self, ctx: &Context) -> Result<(), Error> { + host::log(LogLevel::Info, &format!("hello {} activated", ctx.plugin_version)); + Ok(()) + } + + fn deactivate(&mut self) { + host::log(LogLevel::Info, "hello deactivated"); + } + + fn run_command(&mut self, id: &str, ctx: &Invocation, _arg: Option<&str>) -> Result, Error> { + let editor = ctx.editor().ok_or("no file is open in the editor")?; + match id { + "insert-date" => { + // Replaces every selection (inserts at every cursor), as one undo step. + let date = today(); + editor.transform_selections(|_| date.clone())?; + Ok(Some(date)) + } + "word-count" => { + let text = editor.document()?.text; + let path = editor.path(); + let words = text.split_whitespace().count(); + let lines = text.lines().count(); + let name = path.rsplit(['/', '\\']).next().unwrap_or(&path); + let body = format!("{words} words, {lines} lines, {} characters", text.chars().count()); + host::notify(NotificationLevel::Info, &format!("Word count: {name}"), &body); + Ok(Some(body)) + } + other => Err(Error::NotFound(format!("command {other}"))), + } + } +} + +impl Views for Hello { + fn render(&mut self, view: &str, _viewport: Option, _ctx: &Invocation) -> Result { + if view != "greetings" { + return Err(Error::NotFound(view.into())); + } + let mut items = Vec::new(); + for (language, words) in GREETINGS { + let open = self.expanded.contains(*language); + items.push( + TreeItem::new(language, language).icon("folder").detail(&words.len().to_string()).expandable(open), + ); + if open { + for w in *words { + items.push(TreeItem::new(&format!("{language}/{w}"), w).parent(language).icon("text")); + } + } + } + Ok(View::new(Body::Tree(items)) + .button(Button::new("collapse", "Collapse All").icon("collapse-all").enabled(!self.expanded.is_empty())) + .status(&format!("{} languages", GREETINGS.len()))) + } + + fn handle(&mut self, view: &str, event: ViewEvent, _ctx: &Invocation) -> Result<(), Error> { + match event { + ViewEvent::Expand(key) => { + self.expanded.insert(key); + } + ViewEvent::Collapse(key) => { + self.expanded.remove(&key); + } + ViewEvent::Button(b) if b == "collapse" => self.expanded.clear(), + ViewEvent::Activate(key) => { + if let Some((language, word)) = key.split_once('/') { + host::notify(NotificationLevel::Info, word, &format!("A greeting in {language}")); + } + return Ok(()); + } + _ => return Ok(()), + } + host::refresh_view(view); + Ok(()) + } +} + +register_plugin!(Hello, views); + +/// Today's UTC date as `YYYY-MM-DD` (WASI wall clock). +fn today() -> String { + let secs = + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0); + let (y, m, d) = civil_from_days(secs.div_euclid(86_400)); + format!("{y:04}-{m:02}-{d:02}") +} + +/// Howard Hinnant's days-to-civil algorithm. +fn civil_from_days(z: i64) -> (i64, u32, u32) { + let z = z + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = (doy - (153 * mp + 2) / 5 + 1) as u32; + let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; + let y = yoe + era * 400 + i64::from(m <= 2); + (y, m, d) +} + +#[cfg(test)] +mod tests { + use super::*; + use openidea_plugin::mock::MockHost; + + #[test] + fn civil_dates() { + assert_eq!(civil_from_days(0), (1970, 1, 1)); + assert_eq!(civil_from_days(19_782), (2024, 2, 29)); + } + + #[test] + fn word_count_reads_the_focused_editor() { + let host = MockHost::install(); + host.open_editor("/project/notes.txt", "text", "one two\nthree\n", &[]); + let out = Hello::default().run_command("word-count", &host.invocation(), None).unwrap(); + assert_eq!(out.as_deref(), Some("3 words, 2 lines, 14 characters")); + assert_eq!(host.notifications()[0].title, "Word count: notes.txt"); + } + + #[test] + fn insert_date_replaces_every_selection_at_once() { + let host = MockHost::install(); + host.open_editor("/project/a.txt", "text", "a\nXX b", &[(0, 1, 0, 1), (1, 0, 1, 2)]); + let date = Hello::default().run_command("insert-date", &host.invocation(), None).unwrap().unwrap(); + assert_eq!(host.editor_text(), format!("a{date}\n{date} b")); + assert_eq!(host.editor_version(), 2, "one change"); + } + + #[test] + fn the_greetings_tree_loads_children_when_expanded() { + let host = MockHost::install(); + let mut p = Hello::default(); + let tree = |p: &mut Hello| match p.render("greetings", None, &host.invocation()).unwrap().body { + Body::Tree(items) => items, + other => panic!("{other:?}"), + }; + assert_eq!(tree(&mut p).len(), 3); + p.handle("greetings", ViewEvent::Expand("Deutsch".into()), &host.invocation()).unwrap(); + let items = tree(&mut p); + assert_eq!(items.len(), 6); + assert_eq!((items[2].label.as_str(), items[2].parent.as_deref()), ("Hallo", Some("Deutsch"))); + assert_eq!(host.refreshed_views(), ["greetings"]); + p.handle("greetings", ViewEvent::Activate("Deutsch/Servus".into()), &host.invocation()).unwrap(); + assert_eq!(host.notifications()[0].title, "Servus"); + p.handle("greetings", ViewEvent::Button("collapse".into()), &host.invocation()).unwrap(); + assert_eq!(tree(&mut p).len(), 3); + } + + #[test] + fn without_editor_write_the_command_fails_cleanly() { + let host = MockHost::install().with_capabilities(&["editor.read"]); + host.open_editor("/project/a.txt", "text", "", &[(0, 0, 0, 0)]); + let err = Hello::default().run_command("insert-date", &host.invocation(), None).unwrap_err(); + assert_eq!(err, Error::Denied("editor.write".into())); + assert_eq!(host.editor_text(), ""); + } +} diff --git a/crates/ide-plugin/tests/fixtures/jobs/Cargo.lock b/crates/ide-plugin/tests/fixtures/jobs/Cargo.lock new file mode 100644 index 00000000..2c35dac7 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/jobs/Cargo.lock @@ -0,0 +1,333 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "openidea-plugin-jobs" +version = "0.1.0" +dependencies = [ + "openidea-plugin", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[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 = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +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 = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/crates/ide-plugin/tests/fixtures/jobs/Cargo.toml b/crates/ide-plugin/tests/fixtures/jobs/Cargo.toml new file mode 100644 index 00000000..78b77753 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/jobs/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "openidea-plugin-jobs" +version = "0.1.0" +edition = "2024" +publish = false + +# Test fixture for the plugin host: built by `plugins/build.sh `, checked in as dist/plugin.wasm. +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../../../sdk/rust/openidea-plugin" } + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm new file mode 100644 index 00000000..aaa324d9 Binary files /dev/null and b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources new file mode 100644 index 00000000..61e1857b --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources @@ -0,0 +1 @@ +0dacb82ac35c1f132dc66e85dbf0663b729f818279d3b32cd06403e502fbf880 diff --git a/crates/ide-plugin/tests/fixtures/jobs/plugin.toml b/crates/ide-plugin/tests/fixtures/jobs/plugin.toml new file mode 100644 index 00000000..8a3d2c89 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/jobs/plugin.toml @@ -0,0 +1,29 @@ +# Test fixture: a tool window listing what an external program reports, and a +# terminal following one entry. Covers pinned programs (`process:`), terminals, +# settings and tree views, locally and in remote projects. +id = "jobs" +name = "Jobs" +version = "0.1.0" +description = "Test fixture: lists the jobs `jobs list` prints and follows one in the terminal." +authors = ["OpenIDEA contributors"] +engines.openidea = "^1.0" +wasm = "dist/plugin.wasm" +activation = ["on-view:jobs", "on-command:*"] + +[capabilities] +required = ["process:jobs"] + +[[contributes.views]] +id = "jobs" +title = "Jobs" +icon = "toolwindow-services" +location = "right" + +[[contributes.commands]] +id = "follow" +title = "Jobs: Follow Selected Job" +category = "Jobs" + +[contributes.settings] +title = "Jobs" +schema = "settings.schema.json" diff --git a/crates/ide-plugin/tests/fixtures/jobs/settings.schema.json b/crates/ide-plugin/tests/fixtures/jobs/settings.schema.json new file mode 100644 index 00000000..69784b26 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/jobs/settings.schema.json @@ -0,0 +1,14 @@ +{ + "properties": { + "title": { + "type": "string", + "title": "Terminal title prefix", + "default": "follow: " + }, + "lines": { + "type": "integer", + "title": "Lines to show first", + "default": 20 + } + } +} diff --git a/crates/ide-plugin/tests/fixtures/jobs/src/lib.rs b/crates/ide-plugin/tests/fixtures/jobs/src/lib.rs new file mode 100644 index 00000000..b6686393 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/jobs/src/lib.rs @@ -0,0 +1,74 @@ +//! Test fixture: a tree of the jobs `jobs list` prints (one per line, through +//! the pinned `process:jobs`), and a terminal running `jobs follow ` for +//! the activated one, titled and sized by the plugin's settings. + +use openidea_plugin::host; +use openidea_plugin::views::{Body, Button, TreeItem, View, ViewEvent, Viewport, Views}; +use openidea_plugin::{Error, Invocation, Plugin, register_plugin}; + +pub const VIEW: &str = "jobs"; + +#[derive(Default)] +pub struct Jobs { + selected: Option, +} + +fn list() -> Result, Error> { + let out = host::run_process("jobs", &["list".to_owned()], None)?; + if out.status != Some(0) { + return Err(Error::Failed(out.stderr.trim().to_owned())); + } + Ok(out.stdout.lines().map(str::trim).filter(|l| !l.is_empty()).map(str::to_owned).collect()) +} + +impl Jobs { + fn follow(&self) -> Result<(), Error> { + let job = self.selected.as_deref().ok_or_else(|| Error::Invalid("select a job first".into()))?; + let title = host::setting_string("title").unwrap_or_else(|| "follow: ".into()); + let lines = host::setting_number("lines").map_or(20, |n| n.max(0.0) as u64); + let args = ["follow".to_owned(), job.to_owned(), format!("--lines={lines}")]; + host::open_terminal(&format!("{title}{job}"), "jobs", &args) + } +} + +impl Plugin for Jobs { + fn run_command(&mut self, id: &str, _ctx: &Invocation, _arg: Option<&str>) -> Result, Error> { + match id { + "follow" => self.follow().map(|()| None), + _ => Err(Error::NotFound(format!("command {id}"))), + } + } +} + +impl Views for Jobs { + fn render(&mut self, view: &str, _viewport: Option, _ctx: &Invocation) -> Result { + if view != VIEW { + return Err(Error::NotFound(view.into())); + } + let follow = Button::new("follow", "Follow").icon("terminal").enabled(self.selected.is_some()); + Ok(match list() { + Ok(jobs) => View::new(Body::Tree(jobs.iter().map(|j| TreeItem::new(j, j).icon("run")).collect())), + Err(e) => View::message(&format!("jobs: {e}")), + } + .button(follow)) + } + + fn handle(&mut self, view: &str, event: ViewEvent, _ctx: &Invocation) -> Result<(), Error> { + if view != VIEW { + return Err(Error::NotFound(view.into())); + } + match event { + ViewEvent::Select(key) => self.selected = Some(key), + ViewEvent::Activate(key) => { + self.selected = Some(key); + return self.follow(); + } + ViewEvent::Button(b) if b == "follow" => return self.follow(), + _ => return Ok(()), + } + host::refresh_view(VIEW); + Ok(()) + } +} + +register_plugin!(Jobs, views); diff --git a/plugins/language-toy/languages/toy.toml b/crates/ide-plugin/tests/fixtures/language-toy/languages/toy.toml similarity index 100% rename from plugins/language-toy/languages/toy.toml rename to crates/ide-plugin/tests/fixtures/language-toy/languages/toy.toml diff --git a/plugins/language-toy/plugin.toml b/crates/ide-plugin/tests/fixtures/language-toy/plugin.toml similarity index 100% rename from plugins/language-toy/plugin.toml rename to crates/ide-plugin/tests/fixtures/language-toy/plugin.toml diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm index dfc65c7a..d6018357 100644 Binary files a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources new file mode 100644 index 00000000..1c5ed64f --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources @@ -0,0 +1 @@ +0ad2e4c6977a576b7eb27fc1e535fd056dd9da64bdfe6cfda9ca9f57537d0384 diff --git a/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml b/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml index daf0dbdd..29dba7d6 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml +++ b/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml @@ -1,7 +1,42 @@ id = "misbehave" name = "Misbehave" -version = "0.0.1" -description = "Test fixture: traps, spins, allocates, probes permissions." -openidea-api = "0.1" +version = "0.0.2" +description = "Test fixture: traps, spins, allocates, probes capabilities." +engines.openidea = "^1.0" wasm = "dist/plugin.wasm" -permissions = ["project-read"] +activation = ["on-command:*"] + +[capabilities] +required = ["project.read"] + +[[contributes.commands]] +id = "echo" +title = "echo" + +[[contributes.commands]] +id = "panic" +title = "panic" + +[[contributes.commands]] +id = "spin" +title = "spin" + +[[contributes.commands]] +id = "alloc" +title = "alloc" + +[[contributes.commands]] +id = "read" +title = "read" + +[[contributes.commands]] +id = "root" +title = "root" + +[[contributes.commands]] +id = "insert" +title = "insert" + +[[contributes.commands]] +id = "cancel" +title = "cancel" diff --git a/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs b/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs index 8f4ad071..cd6d6511 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs +++ b/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs @@ -1,25 +1,44 @@ //! Test fixture for the ide-plugin sandbox. Never shipped. +// `plugin` with syntax and editor providers. wit_bindgen::generate!({ - world: "plugin", + inline: " + package fixture:misbehave; + world misbehave { + include openidea:plugin/plugin-syntax@1.0.0; + export openidea:plugin/providers@1.0.0; + } + ", path: "../../../../../wit", + world: "fixture:misbehave/misbehave", + generate_all, }); -use openidea::plugin::host; +use exports::openidea::plugin::providers::{self, CodeAction, CompletionItem, Document, InlineSuggestion, LineMarker}; +use exports::openidea::plugin::syntax_provider::{self, Fold, Symbol, Token}; +use exports::openidea::plugin::{commands, event_handler, lifecycle}; +use openidea::plugin::{invocation::Invocation, types}; struct Misbehave; -impl Guest for Misbehave { - fn activate(_ctx: Context) -> Result<(), String> { - for id in ["echo", "panic", "spin", "alloc", "read", "root", "insert", "language", "theme"] { - host::register_command(id, id, None); +fn failed(message: &str) -> types::Error { + types::Error::Failed(message.into()) +} + +impl lifecycle::Guest for Misbehave { + fn activate(ctx: types::Context) -> Result<(), types::Error> { + // A deliberately broken build (rollback tests): `version = "…-broken"`. + if ctx.plugin_version.ends_with("-broken") { + return Err(failed("this build is broken")); } Ok(()) } fn deactivate() {} +} - fn run_command(id: String, arg: Option) -> Result, String> { +impl commands::Guest for Misbehave { + fn run(id: String, ctx: &Invocation, arg: Option) -> Result, types::Error> { match id.as_str() { "echo" => Ok(arg), "panic" => panic!("boom"), @@ -36,18 +55,90 @@ impl Guest for Misbehave { std::hint::black_box(&chunks); } } - "read" => host::read_file(&arg.unwrap_or_default()).map(Some), - "root" => Ok(host::workspace_root()), - // Not permitted by the manifest: traps. - "insert" => { - host::insert_text("x"); - Ok(None) + "read" => { + let project = ctx.project().ok_or_else(|| failed("no project is open"))?; + project.read_file(&arg.unwrap_or_default()).map(Some) } - "language" => host::register_language(&arg.unwrap_or_default()).map(|_| None), - "theme" => host::register_theme(&arg.unwrap_or_default()).map(|_| None), - other => Err(format!("unknown command: {other}")), + "root" => ctx.project().map(|p| p.root()).transpose(), + // `editor.write` is not granted: an error, not a trap. + "insert" => { + let editor = ctx.editor().ok_or_else(|| failed("no editor"))?; + editor.apply_edits(0, &[]).map(|_| None) + } + // The user gave up: not the plugin failing. + "cancel" => Err(types::Error::Cancelled), + other => Err(types::Error::NotFound(format!("command {other}"))), } } } +impl event_handler::Guest for Misbehave { + fn handle(_events: Vec, _ctx: &Invocation) {} +} + +/// Edit-path budgets: the text says how to behave. `sleep:` busy-waits +/// that long, `spin` never returns, `panic` traps. +fn behave(text: &str) { + if let Some(ms) = text.strip_prefix("sleep:").and_then(|n| n.trim().parse::().ok()) { + let until = std::time::Instant::now() + std::time::Duration::from_millis(ms); + while std::time::Instant::now() < until { + std::hint::black_box(0); + } + } else if text == "spin" { + loop { + std::hint::black_box(0); + } + } else if text == "panic" { + panic!("boom"); + } +} + +/// One keyword token over the whole text, after [`behave`]. +impl syntax_provider::Guest for Misbehave { + fn highlights(_language: String, text: String) -> Vec { + behave(&text); + vec![Token { start: 0, end: text.len() as u32, kind: "keyword".into() }] + } + + fn outline(_language: String, _text: String) -> Vec { + Vec::new() + } + + fn folding(_language: String, _text: String) -> Vec { + Vec::new() + } +} + +/// Completion: one item, labelled with the document's path, after [`behave`]. +impl providers::Guest for Misbehave { + fn completion(doc: Document, _at: types::Position, _trigger: Option) -> Vec { + behave(&doc.text); + vec![CompletionItem { + label: doc.path.clone(), + detail: None, + kind: Some("keyword".into()), + insert_text: doc.path, + replace: None, + sort_text: None, + documentation: None, + }] + } + + fn inline_completion(_doc: Document, _at: types::Position) -> Option { + None + } + + fn code_actions(_doc: Document, _selection: types::Range) -> Vec { + Vec::new() + } + + fn definition(_doc: Document, _at: types::Position) -> Vec { + Vec::new() + } + + fn line_markers(_doc: Document) -> Vec { + Vec::new() + } +} + export!(Misbehave); diff --git a/crates/ide-plugin/tests/fixtures/p0-probe/.gitignore b/crates/ide-plugin/tests/fixtures/p0-probe/.gitignore new file mode 100644 index 00000000..a82021db --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/p0-probe/.gitignore @@ -0,0 +1,2 @@ +target/ +!dist/ diff --git a/crates/ide-plugin/tests/fixtures/p0-probe/Cargo.lock b/crates/ide-plugin/tests/fixtures/p0-probe/Cargo.lock new file mode 100644 index 00000000..1cbb372c --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/p0-probe/Cargo.lock @@ -0,0 +1,326 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-p0-probe" +version = "0.0.1" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[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 = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +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 = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/crates/ide-plugin/tests/fixtures/p0-probe/Cargo.toml b/crates/ide-plugin/tests/fixtures/p0-probe/Cargo.toml new file mode 100644 index 00000000..41c48f07 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/p0-probe/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "openidea-p0-probe" +version = "0.0.1" +edition = "2024" +publish = false + +# Standalone: not a member of the IDE workspace (different target). +[workspace] + +[lib] +crate-type = ["cdylib"] + +[features] +# Builds the `probe-full` world (with the optional exports); default is `probe-min`. +full = [] + +[dependencies] +wit-bindgen = "0.63" + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/crates/ide-plugin/tests/fixtures/p0-probe/build.sh b/crates/ide-plugin/tests/fixtures/p0-probe/build.sh new file mode 100755 index 00000000..18ed6f7b --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/p0-probe/build.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# Builds dist/min.wasm (probe-min) and dist/full.wasm (probe-full). +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +export CARGO_TARGET_DIR="$here/target" +mkdir -p "$here/dist" +cargo build --manifest-path "$here/Cargo.toml" --release --target wasm32-wasip2 +cp "$CARGO_TARGET_DIR/wasm32-wasip2/release/openidea_p0_probe.wasm" "$here/dist/min.wasm" +cargo build --manifest-path "$here/Cargo.toml" --release --target wasm32-wasip2 --features full +cp "$CARGO_TARGET_DIR/wasm32-wasip2/release/openidea_p0_probe.wasm" "$here/dist/full.wasm" +ls -l "$here/dist" diff --git a/crates/ide-plugin/tests/fixtures/p0-probe/dist/full.wasm b/crates/ide-plugin/tests/fixtures/p0-probe/dist/full.wasm new file mode 100644 index 00000000..a7b7215b Binary files /dev/null and b/crates/ide-plugin/tests/fixtures/p0-probe/dist/full.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/p0-probe/dist/min.wasm b/crates/ide-plugin/tests/fixtures/p0-probe/dist/min.wasm new file mode 100644 index 00000000..ac9499be Binary files /dev/null and b/crates/ide-plugin/tests/fixtures/p0-probe/dist/min.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/p0-probe/src/lib.rs b/crates/ide-plugin/tests/fixtures/p0-probe/src/lib.rs new file mode 100644 index 00000000..f12996fa --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/p0-probe/src/lib.rs @@ -0,0 +1,68 @@ +//! P0 probe guest. Built twice (see `build.sh`): `probe-min` and, with +//! `--features full`, `probe-full` with the optional exports. + +#[cfg(feature = "full")] +wit_bindgen::generate!({ world: "probe-full", path: "wit", generate_all }); +#[cfg(not(feature = "full"))] +wit_bindgen::generate!({ world: "probe-min", path: "wit", generate_all }); + +use exports::openidea::probe::base; +use openidea::probe::host_api; +use std::sync::atomic::{AtomicU32, Ordering}; + +static CALLS: AtomicU32 = AtomicU32::new(0); + +struct Probe; + +impl base::Guest for Probe { + fn run(cmd: String, arg: String) -> Result { + let n = CALLS.fetch_add(1, Ordering::Relaxed) + 1; + match cmd.as_str() { + "echo" => Ok(arg), + // Instance state survives between calls (and is lost with the instance). + "count" => Ok(n.to_string()), + "spin" => { + let mut x: u64 = 0; + loop { + x = std::hint::black_box(x.wrapping_add(1)); + } + } + "sleep" => { + host_api::sleep_ms(arg.parse().map_err(|_| "ms")?); + Ok("slept".into()) + } + // Streams items pushed by the host until it cancels. + "task" => { + let task = host_api::current_task(); + let mut got = Vec::new(); + loop { + task.next_ready().block(); + if task.is_cancelled() { + return Ok(format!("cancelled after {}", got.join(","))); + } + if let Some(item) = task.take() { + got.push(item); + task.report(got.len() as u32, None); + } + } + } + other => Err(format!("unknown: {other}")), + } + } +} + +#[cfg(feature = "full")] +impl exports::openidea::probe::code_actions::Guest for Probe { + fn actions(path: String) -> Vec { + vec![format!("fix:{path}")] + } +} + +#[cfg(feature = "full")] +impl exports::openidea::probe::completion::Guest for Probe { + fn complete(prefix: String) -> Vec { + vec![format!("{prefix}1"), format!("{prefix}2")] + } +} + +export!(Probe); diff --git a/crates/ide-plugin/tests/fixtures/p0-probe/wit/deps/io/poll.wit b/crates/ide-plugin/tests/fixtures/p0-probe/wit/deps/io/poll.wit new file mode 100644 index 00000000..2c81ea01 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/p0-probe/wit/deps/io/poll.wit @@ -0,0 +1,11 @@ +// Subset of wasi:io@0.2.0 (the host links its full 0.2.x implementation). +package wasi:io@0.2.0; + +interface poll { + resource pollable { + ready: func() -> bool; + block: func(); + } + + poll: func(in: list>) -> list; +} diff --git a/crates/ide-plugin/tests/fixtures/p0-probe/wit/probe.wit b/crates/ide-plugin/tests/fixtures/p0-probe/wit/probe.wit new file mode 100644 index 00000000..b1ff2c41 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/p0-probe/wit/probe.wit @@ -0,0 +1,59 @@ +/// Runtime probe: optional exports, async calls and +/// cancellation, and a WASI p2 task model built on `wasi:io/poll`. +/// Test fixture only; not part of the plugin API. +package openidea:probe@0.1.0; + +interface host-api { + use wasi:io/poll@0.2.0.{pollable}; + + /// A long-running job the host started for the guest. + resource task { + /// Progress report (`total` unknown while `none`). + report: func(done: u32, total: option); + /// Set by the host when the user cancels. + is-cancelled: func() -> bool; + /// Ready when the host pushed the next item, or on cancellation. + next-ready: func() -> pollable; + /// The pushed item, if any (non-blocking). + take: func() -> option; + } + + /// The task of the current call. + current-task: func() -> task; + + /// An async host import: sleeps without blocking the host thread. + sleep-ms: func(ms: u32); +} + +interface base { + run: func(cmd: string, arg: string) -> result; +} + +/// Optional exports: a plugin implements only the providers it needs. +interface code-actions { + actions: func(path: string) -> list; +} + +interface completion { + complete: func(prefix: string) -> list; +} + +world probe-min { + import host-api; + export base; +} + +world probe-full { + import host-api; + export base; + export code-actions; + export completion; +} + +/// The host binds this world; guests implement `probe-min` or `probe-full`. +world probe-host { + import host-api; + export base; + export code-actions; + export completion; +} diff --git a/crates/ide-plugin/tests/host.rs b/crates/ide-plugin/tests/host.rs deleted file mode 100644 index 2c2572c0..00000000 --- a/crates/ide-plugin/tests/host.rs +++ /dev/null @@ -1,603 +0,0 @@ -//! End-to-end tests against real components. -//! -//! The components are checked in (`plugins/hello/dist/plugin.wasm`, -//! `tests/fixtures/misbehave/dist/plugin.wasm`) so tests need no wasm -//! toolchain. Rebuild them with `plugins/build.sh hello` and -//! `plugins/build.sh crates/ide-plugin/tests/fixtures/misbehave` after -//! changing their source or `wit/plugin.wit`. - -use ide_plugin::*; -use parking_lot::Mutex; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::time::Duration; - -type Events = Arc, PluginEvent)>>>; - -fn repo() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../..").canonicalize().unwrap() -} - -fn sample(name: &str) -> PathBuf { - repo().join("plugins").join(name) -} - -fn theme_template() -> PathBuf { - repo().join("templates/theme-plugin") -} - -/// A theme package with a light and a dark theme, plus licence files, in `dir`. -fn write_theme_pair(dir: &Path) { - std::fs::create_dir_all(dir.join("t")).unwrap(); - std::fs::write( - dir.join("plugin.toml"), - "id = \"theme-pair\"\nname = \"Pair\"\nversion = \"1.0.0\"\nopenidea-api = \"0.1\"\n\ - [[contributes.themes]]\npath = \"t/day.json\"\n[[contributes.themes]]\npath = \"t/night.json\"\n", - ) - .unwrap(); - std::fs::write( - dir.join("t/day.json"), - r##"{"id":"day","name":"Day","kind":"light","tokens":{"--bg-frame":"#eeeeee"}}"##, - ) - .unwrap(); - std::fs::write( - dir.join("t/night.json"), - r##"{"id":"night","name":"Night","kind":"dark","tokens":{"--bg-frame":"#111111"}}"##, - ) - .unwrap(); - std::fs::write(dir.join("LICENSE"), "MIT License\n").unwrap(); - std::fs::write(dir.join("NOTICE"), "Palette notice\n").unwrap(); -} - -fn misbehave_pkg() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/misbehave") -} - -struct Fixture { - host: PluginHost, - events: Events, - _tmp: tempfile::TempDir, - plugins_dir: PathBuf, - project: PathBuf, -} - -fn fixture(limits: Limits) -> Fixture { - let tmp = tempfile::tempdir().unwrap(); - let plugins_dir = tmp.path().join("plugins"); - let project = tmp.path().join("project"); - std::fs::create_dir_all(project.join("src")).unwrap(); - std::fs::write(project.join("src/notes.txt"), "one two three\nfour five\n").unwrap(); - std::fs::write(tmp.path().join("secret.txt"), "top secret").unwrap(); - let project = project.canonicalize().unwrap(); - let events: Events = Arc::default(); - let sink = { - let events = events.clone(); - move |client: Option<&str>, e: PluginEvent| events.lock().push((client.map(str::to_owned), e)) - }; - let host = PluginHost::new(plugins_dir.clone(), Arc::new(sink), limits).unwrap(); - Fixture { host, events, _tmp: tmp, plugins_dir, project } -} - -impl Fixture { - fn inv(&self) -> Invocation { - Invocation { client: Some("main".into()), workspace_root: Some(self.project.clone()), buffer_text: None } - } - - fn run(&self, plugin: &str, cmd: &str, arg: Option<&str>) -> Result, String> { - self.host.run_command(plugin, cmd, arg, self.inv()).map_err(|e| e.message) - } - - fn status(&self, id: &str) -> PluginStatus { - self.host.info_of(id).unwrap().status - } - - fn take_events(&self) -> Vec<(Option, PluginEvent)> { - std::mem::take(&mut *self.events.lock()) - } -} - -#[test] -fn hello_plugin_commands() { - let f = fixture(Limits::default()); - let info = f.host.install_from_dir(&sample("hello")).unwrap(); - assert_eq!(info.status, PluginStatus::Active, "{:?}", info.error); - assert!(f.plugins_dir.join("hello/plugin.toml").is_file()); - assert!(f.plugins_dir.join("hello/dist/plugin.wasm").is_file()); - let titles: Vec<_> = info.commands.iter().map(|c| c.title.as_str()).collect(); - assert_eq!(titles, ["Hello: Insert Date", "Hello: Word Count of Active File"]); - f.take_events(); - - // Insert Date: returns YYYY-MM-DD and asks the invoking window to insert it. - let date = f.run("hello", "insert-date", None).unwrap().unwrap(); - assert!(date.len() == 10 && date.as_bytes()[4] == b'-' && date.starts_with("20"), "{date}"); - let events = f.take_events(); - assert!(events.iter().any(|(client, e)| client.as_deref() == Some("main") - && *e == PluginEvent::InsertText { plugin_id: "hello".into(), text: date.clone() })); - - // Word Count needs an active file. - assert!(f.run("hello", "word-count", None).unwrap_err().contains("no file is open")); - f.host.set_active_file("main", Some(f.project.join("src/notes.txt").to_string_lossy().into_owned())); - let summary = f.run("hello", "word-count", None).unwrap().unwrap(); - assert!(summary.starts_with("5 words, 2 lines"), "{summary}"); - assert!(f.take_events().iter().any(|(_, e)| matches!(e, - PluginEvent::Notification { title, level: NotificationLevel::Info, .. } if title == "Word count: notes.txt"))); - - // Unsaved buffer contents win over disk. - let mut inv = f.inv(); - inv.buffer_text = Some(Arc::new(|_: &Path| Some("just three words".to_owned()))); - let summary = f.host.run_command("hello", "word-count", None, inv).unwrap().unwrap(); - assert!(summary.starts_with("3 words"), "{summary}"); - - // Guest errors don't disable the plugin. - assert!(f.run("hello", "nope", None).unwrap_err().contains("unknown command")); - assert_eq!(f.status("hello"), PluginStatus::Active); -} - -#[test] -fn read_file_is_confined_to_the_project() { - let f = fixture(Limits::default()); - f.host.install_from_dir(&misbehave_pkg()).unwrap(); - assert_eq!(f.run("misbehave", "read", Some("src/notes.txt")).unwrap().unwrap(), "one two three\nfour five\n"); - let abs = f.project.join("src/notes.txt"); - assert!(f.run("misbehave", "read", Some(abs.to_str().unwrap())).is_ok()); - let err = f.run("misbehave", "read", Some("../secret.txt")).unwrap_err(); - assert!(err.contains("outside the project root"), "{err}"); - let err = f.run("misbehave", "read", Some("src/../../secret.txt")).unwrap_err(); - assert!(err.contains("outside the project root"), "{err}"); - assert!(f.run("misbehave", "read", Some("/etc/hosts")).is_err()); - // Without a project there is nothing to read. - let inv = Invocation { client: None, workspace_root: None, buffer_text: None }; - let err = f.host.run_command("misbehave", "read", Some("src/notes.txt"), inv).unwrap_err().message; - assert!(err.contains("no project is open"), "{err}"); - assert_eq!(f.run("misbehave", "root", None).unwrap().unwrap(), f.project.to_string_lossy()); - assert_eq!(f.status("misbehave"), PluginStatus::Active); -} - -#[test] -fn undeclared_permission_traps_and_disables() { - let f = fixture(Limits::default()); - f.host.install_from_dir(&misbehave_pkg()).unwrap(); - let err = f.run("misbehave", "insert", None).unwrap_err(); - assert!(err.contains("permission denied") && err.contains("editor-write"), "{err}"); - assert_eq!(f.status("misbehave"), PluginStatus::Failed); - assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::InsertText { .. }))); -} - -#[test] -fn panic_is_isolated_and_plugin_can_be_restarted() { - let f = fixture(Limits::default()); - f.host.install_from_dir(&sample("hello")).unwrap(); - f.host.install_from_dir(&misbehave_pkg()).unwrap(); - f.take_events(); - - let err = f.run("misbehave", "panic", None).unwrap_err(); - assert!(err.contains("crashed"), "{err}"); - assert!(err.contains("boom"), "stderr panic message is surfaced: {err}"); - let info = f.host.info_of("misbehave").unwrap(); - assert_eq!(info.status, PluginStatus::Failed); - assert!(info.enabled, "failure is per session, not persisted"); - let events = f.take_events(); - assert!(events.iter().any(|(client, e)| client.as_deref() == Some("main") - && matches!(e, PluginEvent::Notification { level: NotificationLevel::Error, title, .. } if title.contains("was disabled")))); - assert!(events.iter().any(|(_, e)| *e == PluginEvent::CommandsChanged)); - - assert!(f.run("misbehave", "echo", Some("x")).unwrap_err().contains("not running")); - // Other plugins are unaffected. - assert!(f.run("hello", "insert-date", None).is_ok()); - - // Toggling restarts it with a fresh instance. - f.host.set_enabled("misbehave", true).unwrap(); - assert_eq!(f.status("misbehave"), PluginStatus::Active); - assert_eq!(f.run("misbehave", "echo", Some("back")).unwrap().as_deref(), Some("back")); -} - -#[test] -fn fuel_exhaustion_traps() { - let f = fixture(Limits { fuel: 50_000_000, timeout: Duration::from_secs(30), ..Limits::default() }); - f.host.install_from_dir(&misbehave_pkg()).unwrap(); - let err = f.run("misbehave", "spin", None).unwrap_err(); - assert!(err.contains("CPU budget"), "{err}"); - assert_eq!(f.status("misbehave"), PluginStatus::Failed); -} - -#[test] -fn wall_clock_timeout_traps() { - let f = fixture(Limits { fuel: u64::MAX, timeout: Duration::from_millis(200), ..Limits::default() }); - f.host.install_from_dir(&misbehave_pkg()).unwrap(); - let started = std::time::Instant::now(); - let err = f.run("misbehave", "spin", None).unwrap_err(); - assert!(err.contains("timed out"), "{err}"); - assert!(started.elapsed() < Duration::from_secs(5)); -} - -#[test] -fn memory_limit_traps() { - let f = fixture(Limits { memory_bytes: 32 << 20, ..Limits::default() }); - f.host.install_from_dir(&misbehave_pkg()).unwrap(); - let err = f.run("misbehave", "alloc", None).unwrap_err(); - assert!(err.contains("memory"), "{err}"); - assert_eq!(f.status("misbehave"), PluginStatus::Failed); -} - -#[test] -fn runtime_language_and_theme_registration() { - let f = fixture(Limits::default()); - f.host.install_from_dir(&misbehave_pkg()).unwrap(); - let lang = "id = \"zz\"\nname = \"ZZ\"\nextensions = [\"zz\"]"; - f.run("misbehave", "language", Some(lang)).unwrap(); - assert!(f.run("misbehave", "language", Some("not toml [")).unwrap_err().contains("invalid language")); - assert_eq!(f.host.languages().iter().map(|l| l.id.to_string()).collect::>(), ["zz"]); - - let theme = r##"{"id":"t1","name":"T1","kind":"light","tokens":{"--bg-app":"#fff"}}"##; - f.run("misbehave", "theme", Some(theme)).unwrap(); - assert!( - f.run("misbehave", "theme", Some(r#"{"id":"t2","name":"x","kind":"dark","tokens":{"--a":"url(x)"}}"#)).is_err() - ); - let info = f.host.info_of("misbehave").unwrap(); - assert_eq!(info.languages[0].extensions, ["zz"]); - assert_eq!(info.themes[0].kind, ThemeKind::Light); - let active = f.host.set_theme(Some(("misbehave", "t1"))).unwrap().unwrap(); - assert_eq!(active.theme.tokens["--bg-app"], "#fff"); - assert!(f.host.set_theme(Some(("misbehave", "nope"))).is_err()); -} - -#[test] -fn contribution_only_plugins() { - let f = fixture(Limits::default()); - let theme = f.host.install_from_dir(&theme_template()).unwrap(); - assert_eq!(theme.status, PluginStatus::Static); - assert!(!theme.has_code); - let ids: Vec<&str> = theme.themes.iter().map(|t| t.id.as_str()).collect(); - assert_eq!(ids, ["harbor-night"]); - let lang = f.host.install_from_dir(&sample("language-toy")).unwrap(); - assert_eq!(lang.status, PluginStatus::Static); - assert_eq!(lang.languages[0].id, "toy"); - assert_eq!(f.host.languages()[0].block_comment, Some(("(*".into(), "*)".into()))); - assert!(f.run("language-toy", "x", None).unwrap_err().contains("no code")); - - f.take_events(); - let active = f.host.set_theme(Some(("theme-harbor-night", "harbor-night"))).unwrap().unwrap(); - assert_eq!(active.theme.tokens["--bg-app"], "#14171c"); - assert_eq!(active.theme.tokens["--syn-string"], "#9ccc7a"); - assert!(f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::ThemeChanged { theme: Some(_) }))); - assert_eq!(f.host.list(None).active_theme, Some(active)); - - // Disabling the plugin withdraws its theme and language. - f.host.set_enabled("theme-harbor-night", false).unwrap(); - assert!(f.host.active_theme().is_none()); - assert!(f.take_events().iter().any(|(_, e)| *e == PluginEvent::ThemeChanged { theme: None })); - f.host.set_enabled("language-toy", false).unwrap(); - assert!(f.host.languages().is_empty()); - assert_eq!(f.status("language-toy"), PluginStatus::Disabled); -} - -#[test] -fn theme_template_installs_with_its_editor_scheme() { - let f = fixture(Limits::default()); - let info = f.host.install_from_dir(&theme_template()).unwrap(); - assert_eq!(info.status, PluginStatus::Static); - assert!(!info.has_code); - assert_eq!(info.themes[0].id, "harbor-night"); - assert_eq!(info.themes[0].kind, ThemeKind::Dark); - // The scheme file is copied with the package and merged over the UI tokens. - assert!(f.plugins_dir.join("theme-harbor-night/themes/harbor-night.scheme.json").is_file()); - let active = f.host.set_theme(Some(("theme-harbor-night", "harbor-night"))).unwrap().unwrap(); - let tokens = &active.theme.tokens; - assert!( - tokens.contains_key("--bg-app") && tokens.contains_key("--syn-keyword") && tokens.contains_key("--ansi-red") - ); - assert!(tokens.len() > 150); -} - -#[test] -fn theme_packages_install_with_their_licence() { - let f = fixture(Limits::default()); - let dir = tempfile::tempdir().unwrap(); - write_theme_pair(dir.path()); - let info = f.host.install_from_dir(dir.path()).unwrap(); - assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error); - let installed = f.plugins_dir.join("theme-pair"); - assert!(std::fs::read_to_string(installed.join("LICENSE")).unwrap().contains("MIT License")); - assert!(installed.join("NOTICE").is_file()); - for (theme, kind) in [("day", ThemeKind::Light), ("night", ThemeKind::Dark)] { - let active = f.host.set_theme(Some(("theme-pair", theme))).unwrap().unwrap(); - assert_eq!(active.theme.kind, kind); - } -} - -#[test] -fn theme_frame_follows_the_selection() { - let f = fixture(Limits::default()); - let dir = tempfile::tempdir().unwrap(); - write_theme_pair(dir.path()); - f.host.install_from_dir(dir.path()).unwrap(); - // Nothing to attach it to without a selected theme. - f.host.set_theme_frame(Some("#111111")).unwrap(); - assert_eq!(f.host.startup_frame(), None); - f.host.set_theme(Some(("theme-pair", "night"))).unwrap(); - assert!(f.host.set_theme_frame(Some("hsl(220, 13%, 15%)")).is_err()); - f.host.set_theme_frame(Some("#111111")).unwrap(); - assert_eq!(f.host.startup_frame().as_deref(), Some("#111111")); - f.host.set_enabled("theme-pair", false).unwrap(); - assert_eq!(f.host.startup_frame(), None); - f.host.set_enabled("theme-pair", true).unwrap(); - assert_eq!(f.host.startup_frame().as_deref(), Some("#111111")); - // A new selection drops the old theme's colour until the UI reports the new one. - f.host.set_theme(Some(("theme-pair", "day"))).unwrap(); - assert_eq!(f.host.startup_frame(), None); - f.host.set_theme_frame(Some("#eeeeee")).unwrap(); - f.host.set_theme(None).unwrap(); - assert_eq!(f.host.startup_frame(), None); -} - -#[test] -fn theme_with_broken_editor_scheme_fails_to_load() { - let f = fixture(Limits::default()); - let dir = tempfile::tempdir().unwrap(); - std::fs::create_dir(dir.path().join("t")).unwrap(); - std::fs::write( - dir.path().join("plugin.toml"), - "id = \"bad-scheme\"\nname = \"B\"\nversion = \"1.0.0\"\nopenidea-api = \"0.1\"\n\ - [[contributes.themes]]\npath = \"t/a.json\"\neditor-scheme = \"t/a.scheme.json\"\n", - ) - .unwrap(); - std::fs::write(dir.path().join("t/a.json"), r##"{"id":"a","name":"A","kind":"light","tokens":{}}"##).unwrap(); - std::fs::write(dir.path().join("t/a.scheme.json"), "{\n \"tokens\": { \"--caret\": \"url(x)\" }\n}").unwrap(); - let info = f.host.install_from_dir(dir.path()).unwrap(); - assert_eq!(info.status, PluginStatus::Failed); - assert!(info.error.unwrap_or_default().contains("a.scheme.json")); -} - -#[test] -fn state_persists_across_restarts() { - let f = fixture(Limits::default()); - f.host.install_from_dir(&sample("hello")).unwrap(); - f.host.install_from_dir(&theme_template()).unwrap(); - f.host.set_enabled("hello", false).unwrap(); - f.host.set_theme(Some(("theme-harbor-night", "harbor-night"))).unwrap(); - f.host.set_theme_frame(Some("#1f252e")).unwrap(); - - let again = PluginHost::new(f.plugins_dir.clone(), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(); - // Known before the plugins are loaded: new windows open in the theme's frame colour. - assert_eq!(again.startup_frame().as_deref(), Some("#1f252e")); - assert!(!again.wait_initial_load(Duration::from_millis(1))); - again.load_all(); - assert!(again.wait_initial_load(Duration::ZERO)); - let list = again.list(None); - let hello = list.plugins.iter().find(|p| p.id == "hello").unwrap(); - assert!(!hello.enabled); - assert_eq!(hello.status, PluginStatus::Disabled); - assert_eq!(list.active_theme.unwrap().theme.id, "harbor-night"); - assert!( - again - .run_command("hello", "insert-date", None, Invocation::default()) - .unwrap_err() - .message - .contains("disabled") - ); -} - -#[test] -fn dev_plugins_follow_the_project() { - let f = fixture(Limits::default()); - f.host.set_project_policy(Arc::new(|_| true)); - let dev = f.project.join(DEV_PLUGINS_DIR).join("toy"); - copy_dir(&sample("language-toy"), &dev); - f.host.sync_project(&f.project); - let mine = f.host.list(Some(&f.project)); - assert_eq!(mine.plugins.len(), 1); - assert_eq!(mine.plugins[0].source, PluginSource::Dev); - assert!(f.host.list(None).plugins.is_empty(), "dev plugins only show for their project"); - assert!(f.host.uninstall("language-toy").is_err()); - assert!(f.host.install_from_dir(&sample("language-toy")).is_err(), "id clash with a dev plugin"); - - // Edit + reload picks up changes. - let manifest = dev.join("plugin.toml"); - let src = std::fs::read_to_string(&manifest).unwrap().replace("Toy Language", "Toy Language (dev)"); - std::fs::write(&manifest, src).unwrap(); - assert_eq!(f.host.reload("language-toy").unwrap().name, "Toy Language (dev)"); - - std::fs::remove_dir_all(&dev).unwrap(); - f.host.sync_project(&f.project); - assert!(f.host.list(Some(&f.project)).plugins.is_empty()); -} - -#[test] -fn install_validation_and_uninstall() { - let f = fixture(Limits::default()); - let tmp = tempfile::tempdir().unwrap(); - - // Missing component file. - let pkg = tmp.path().join("broken"); - std::fs::create_dir_all(&pkg).unwrap(); - std::fs::write( - pkg.join("plugin.toml"), - "id = \"b\"\nname = \"B\"\nversion = \"1.0.0\"\nopenidea-api = \"0.1\"\nwasm = \"x.wasm\"", - ) - .unwrap(); - assert!(f.host.install_from_dir(&pkg).unwrap_err().message.contains("missing")); - // Not a component. - std::fs::write(pkg.join("x.wasm"), b"\0asm garbage").unwrap(); - assert!(f.host.install_from_dir(&pkg).unwrap_err().message.contains("not a valid plugin component")); - // Bad manifest. - std::fs::write(pkg.join("plugin.toml"), "id = \"B!\"").unwrap(); - assert!(f.host.install_from_dir(&pkg).is_err()); - assert!(f.host.list(None).plugins.is_empty(), "failed installs leave nothing behind"); - - // A broken package already in the plugins dir shows up as failed. - std::fs::create_dir_all(f.plugins_dir.join("junk")).unwrap(); - std::fs::write(f.plugins_dir.join("junk/plugin.toml"), "garbage = ").unwrap(); - f.host.load_all(); - let junk = &f.host.list(None).plugins[0]; - assert_eq!(junk.status, PluginStatus::Failed); - assert!(junk.error.is_some()); - - // Reinstall replaces; uninstall removes the directory. - f.host.install_from_dir(&sample("hello")).unwrap(); - f.host.install_from_dir(&sample("hello")).unwrap(); - assert_eq!(f.status("hello"), PluginStatus::Active); - f.host.uninstall("hello").unwrap(); - assert!(!f.plugins_dir.join("hello").exists()); - assert!(f.host.info_of("hello").is_err()); -} - -fn copy_dir(from: &Path, to: &Path) { - std::fs::create_dir_all(to).unwrap(); - for entry in std::fs::read_dir(from).unwrap().flatten() { - let (src, dst) = (entry.path(), to.join(entry.file_name())); - if src.is_dir() { copy_dir(&src, &dst) } else { std::fs::copy(&src, &dst).map(|_| ()).unwrap() } - } -} - -#[test] -fn catalog_lists_sample_packages() { - let tmp = tempfile::tempdir().unwrap(); - let broken = tmp.path().join("broken"); - std::fs::create_dir_all(&broken).unwrap(); - std::fs::write( - broken.join("plugin.toml"), - "id = \"x\"\nname = \"X\"\nversion = \"1.0.0\"\nopenidea-api = \"0.1\"\nwasm = \"dist/plugin.wasm\"\n", - ) - .unwrap(); - std::fs::create_dir_all(tmp.path().join("junk")).unwrap(); - std::fs::write(tmp.path().join("junk/plugin.toml"), "garbage = ").unwrap(); - - let catalog = scan_catalog(&[repo().join("plugins"), repo().join("templates"), tmp.path().to_path_buf()]); - let ids: Vec<&str> = catalog.iter().map(|c| c.id.as_str()).collect(); - for id in ["hello", "theme-harbor-night", "language-toy", "x"] { - assert!(ids.contains(&id), "{id} missing from {ids:?}"); - } - let hello = catalog.iter().find(|c| c.id == "hello").unwrap(); - assert!(hello.has_code && hello.problem.is_none() && hello.change_notes.is_some()); - assert_eq!(hello.commands.len(), 2); - let theme = catalog.iter().find(|c| c.id == "theme-harbor-night").unwrap(); - assert_eq!((theme.theme_count, theme.has_code), (1, false)); - let x = catalog.iter().find(|c| c.id == "x").unwrap(); - assert!(x.problem.as_deref().unwrap().contains("plugin.wasm")); -} - -#[test] -fn restricted_dev_plugin_has_no_activation_registration() { - let f = fixture(Limits::default()); - let dev = f.project.join(DEV_PLUGINS_DIR).join("hello"); - copy_dir(&sample("hello"), &dev); - let manifest = dev.join("plugin.toml"); - let text = std::fs::read_to_string(&manifest).unwrap(); - std::fs::write(&manifest, text.split("[[contributes.commands]]").next().unwrap()).unwrap(); - assert!(PluginManifest::load(&dev).unwrap().contributes.commands.is_empty()); - let trusted = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let policy = trusted.clone(); - f.host.set_project_policy(Arc::new(move |_| policy.load(std::sync::atomic::Ordering::Acquire))); - f.host.sync_project(&f.project); - let untrusted = f.host.list(Some(&f.project)); - assert!( - !untrusted.plugins.iter().flat_map(|plugin| &plugin.commands).any(|command| command.id == "word-count"), - "untrusted development plugin registered its activation witness" - ); - assert!(untrusted.plugins.is_empty()); - assert!(f.host.info_of("hello").is_err()); - - // Positive control: activation itself registers these commands, not the manifest. - trusted.store(true, std::sync::atomic::Ordering::Release); - f.host.sync_project(&f.project); - let info = f.host.info_of("hello").unwrap(); - assert_eq!(info.status, PluginStatus::Active); - assert!(info.commands.iter().any(|c| c.id == "word-count")); - trusted.store(false, std::sync::atomic::Ordering::Release); - assert!(f.host.reload("hello").is_err()); - assert!(f.host.set_enabled("hello", true).is_err()); - assert!(f.run("hello", "word-count", None).is_err()); - f.host.sync_project(&f.project); - assert!(f.host.list(Some(&f.project)).plugins.is_empty()); -} - -/// Zips the files of `dir` under `prefix` (recursively). -fn add_dir(zip: &mut zip::ZipWriter, dir: &Path, prefix: &str) { - for entry in std::fs::read_dir(dir).unwrap().flatten() { - let name = format!("{prefix}{}", entry.file_name().to_string_lossy()); - if entry.path().is_dir() { - add_dir(zip, &entry.path(), &format!("{name}/")); - } else { - zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); - zip.write_all(&std::fs::read(entry.path()).unwrap()).unwrap(); - } - } -} - -fn zip_of(dir: &Path, prefix: &str, out: &Path) -> PathBuf { - let mut zip = zip::ZipWriter::new(std::fs::File::create(out).unwrap()); - add_dir(&mut zip, dir, prefix); - zip.finish().unwrap(); - out.to_path_buf() -} - -#[test] -fn installs_zips_with_the_package_at_the_root_or_in_one_folder() { - let f = fixture(Limits::default()); - let tmp = tempfile::tempdir().unwrap(); - for (name, prefix) in [("root.ZIP", ""), ("folder.zip", "hello-1.0/")] { - let zip = zip_of(&sample("hello"), prefix, &tmp.path().join(name)); - let info = f.host.install_from_path(&zip).unwrap(); - assert_eq!((info.id.as_str(), info.status), ("hello", PluginStatus::Active), "{:?}", info.error); - assert!(f.plugins_dir.join("hello/dist/plugin.wasm").is_file()); - } - // Still runs from the installed copy, not the unpacked archive. - assert!(f.run("hello", "insert-date", None).unwrap().is_some()); -} - -#[test] -fn installs_from_a_manifest_or_a_folder() { - let f = fixture(Limits::default()); - assert_eq!(f.host.install_from_path(&sample("hello").join("plugin.toml")).unwrap().id, "hello"); - assert_eq!(f.host.install_from_path(&sample("hello")).unwrap().id, "hello"); -} - -#[test] -fn ignores_archiver_metadata_next_to_the_package_folder() { - let f = fixture(Limits::default()); - let tmp = tempfile::tempdir().unwrap(); - let out = tmp.path().join("mac.zip"); - let mut zip = zip::ZipWriter::new(std::fs::File::create(&out).unwrap()); - add_dir(&mut zip, &sample("hello"), "hello/"); - zip.start_file("__MACOSX/hello/._plugin.toml", zip::write::SimpleFileOptions::default()).unwrap(); - zip.write_all(b"metadata").unwrap(); - zip.finish().unwrap(); - assert_eq!(f.host.install_from_path(&out).unwrap().id, "hello"); -} - -#[test] -fn refuses_zips_that_are_not_safe_plugin_packages() { - let f = fixture(Limits::default()); - let tmp = tempfile::tempdir().unwrap(); - let options = zip::write::SimpleFileOptions::default; - - let no_manifest = tmp.path().join("idea-plugin.zip"); - let mut zip = zip::ZipWriter::new(std::fs::File::create(&no_manifest).unwrap()); - zip.start_file("idea-plugin/lib/plugin.jar", options()).unwrap(); - zip.finish().unwrap(); - let error = f.host.install_from_path(&no_manifest).unwrap_err(); - assert!(error.message.contains("no plugin.toml"), "{}", error.message); - - let escape = tmp.path().join("escape.zip"); - let mut zip = zip::ZipWriter::new(std::fs::File::create(&escape).unwrap()); - zip.start_file("../../evil.txt", options()).unwrap(); - zip.write_all(b"evil").unwrap(); - zip.finish().unwrap(); - let error = f.host.install_from_path(&escape).unwrap_err(); - assert!(error.message.contains("unsafe path"), "{}", error.message); - - let link = tmp.path().join("link.zip"); - let mut zip = zip::ZipWriter::new(std::fs::File::create(&link).unwrap()); - zip.add_symlink("plugin.toml", "/etc/passwd", options()).unwrap(); - zip.finish().unwrap(); - let error = f.host.install_from_path(&link).unwrap_err(); - assert!(error.message.contains("symbolic link"), "{}", error.message); - - let garbage = tmp.path().join("garbage.zip"); - std::fs::write(&garbage, "not a zip").unwrap(); - let error = f.host.install_from_path(&garbage).unwrap_err(); - assert!(error.message.contains("not a valid plugin archive"), "{}", error.message); - - assert!(!f.plugins_dir.join("hello").exists()); -} diff --git a/crates/ide-plugin/tests/p0_probe.rs b/crates/ide-plugin/tests/p0_probe.rs new file mode 100644 index 00000000..4e9e0bdf --- /dev/null +++ b/crates/ide-plugin/tests/p0_probe.rs @@ -0,0 +1,353 @@ +//! Runtime experiments, kept as regression tests: they pin the +//! wasmtime behaviour the plugin runtime is designed around. +//! +//! Components: `tests/fixtures/p0-probe/dist/{min,full}.wasm`, rebuilt with +//! `tests/fixtures/p0-probe/build.sh`. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::{Duration, Instant}; +use wasmtime::component::{Component, HasSelf, Linker, Resource, ResourceTable}; +use wasmtime::{Config, Engine, Store}; +use wasmtime_wasi::p2::{DynPollable, Pollable, subscribe}; +use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView}; + +mod bindings { + wasmtime::component::bindgen!({ + world: "probe-host", + path: "tests/fixtures/p0-probe/wit", + imports: { + "openidea:probe/host-api.sleep-ms": async | trappable, + default: trappable, + }, + exports: { default: async }, + with: { + "wasi:io/poll": wasmtime_wasi::p2::bindings::io::poll, + "openidea:probe/host-api.task": super::Task, + }, + }); +} + +use bindings::openidea::probe::host_api; + +/// Host side of the `task` resource: a queue the host pushes into. +pub struct Task { + queue: Arc>>, + cancelled: Arc, + notify: Arc, + progress: Arc, +} + +/// The pollable of `next-ready`: ready once an item is queued or the task is cancelled. +struct NextReady { + queue: Arc>>, + cancelled: Arc, + notify: Arc, +} + +#[wasmtime_wasi::async_trait] +impl Pollable for NextReady { + async fn ready(&mut self) { + loop { + let notified = self.notify.notified(); + if self.cancelled.load(Ordering::Acquire) || !self.queue.lock().is_empty() { + return; + } + notified.await; + } + } +} + +#[derive(Clone, Default)] +struct TaskHandle { + queue: Arc>>, + cancelled: Arc, + notify: Arc, + progress: Arc, +} + +impl TaskHandle { + fn push(&self, item: &str) { + self.queue.lock().push(item.to_owned()); + self.notify.notify_waiters(); + } + fn cancel(&self) { + self.cancelled.store(true, Ordering::Release); + self.notify.notify_waiters(); + } +} + +struct Data { + wasi: WasiCtx, + table: ResourceTable, + task: TaskHandle, +} + +impl WasiView for Data { + fn ctx(&mut self) -> WasiCtxView<'_> { + WasiCtxView { ctx: &mut self.wasi, table: &mut self.table } + } +} + +impl host_api::HostTask for Data { + fn report(&mut self, task: Resource, done: u32, _total: Option) -> wasmtime::Result<()> { + self.table.get(&task)?.progress.store(u64::from(done), Ordering::Release); + Ok(()) + } + fn is_cancelled(&mut self, task: Resource) -> wasmtime::Result { + Ok(self.table.get(&task)?.cancelled.load(Ordering::Acquire)) + } + fn next_ready(&mut self, task: Resource) -> wasmtime::Result> { + let t = self.table.get(&task)?; + let ready = NextReady { queue: t.queue.clone(), cancelled: t.cancelled.clone(), notify: t.notify.clone() }; + let r = self.table.push(ready)?; + subscribe(&mut self.table, r) + } + fn take(&mut self, task: Resource) -> wasmtime::Result> { + let mut q = self.table.get(&task)?.queue.lock(); + Ok(if q.is_empty() { None } else { Some(q.remove(0)) }) + } + fn drop(&mut self, task: Resource) -> wasmtime::Result<()> { + self.table.delete(task)?; + Ok(()) + } +} + +impl host_api::Host for Data { + fn current_task(&mut self) -> wasmtime::Result> { + let h = self.task.clone(); + Ok(self.table.push(Task { queue: h.queue, cancelled: h.cancelled, notify: h.notify, progress: h.progress })?) + } + + async fn sleep_ms(&mut self, ms: u32) -> wasmtime::Result<()> { + tokio::time::sleep(Duration::from_millis(u64::from(ms))).await; + Ok(()) + } +} + +fn dist(name: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/p0-probe/dist").join(name) +} + +struct Env { + engine: Engine, + linker: Linker, + stop: Arc, +} + +impl Drop for Env { + fn drop(&mut self) { + self.stop.store(true, Ordering::Release); + } +} + +fn env() -> Env { + let mut config = Config::new(); + config.wasm_component_model(true).epoch_interruption(true).consume_fuel(true); + let engine = Engine::new(&config).unwrap(); + let mut linker = Linker::new(&engine); + wasmtime_wasi::p2::add_to_linker_async(&mut linker).unwrap(); + host_api::add_to_linker::<_, HasSelf<_>>(&mut linker, |d| d).unwrap(); + let stop = Arc::new(AtomicBool::new(false)); + let (weak, flag) = (engine.weak(), stop.clone()); + std::thread::spawn(move || { + while !flag.load(Ordering::Acquire) + && let Some(e) = weak.upgrade() + { + e.increment_epoch(); + drop(e); + std::thread::sleep(Duration::from_millis(5)); + } + }); + Env { engine, linker, stop } +} + +fn store(env: &Env, task: TaskHandle) -> Store { + let data = Data { wasi: WasiCtx::builder().build(), table: ResourceTable::new(), task }; + let mut store = Store::new(&env.engine, data); + store.set_fuel(u64::MAX).unwrap(); + // Yield to the executor every tick instead of trapping: long calls share the thread. + store.epoch_deadline_async_yield_and_update(1); + store +} + +const BASE: &str = "openidea:probe/base@0.1.0"; +const CODE_ACTIONS: &str = "openidea:probe/code-actions@0.1.0"; + +/// P0-1: a component that lacks optional exports still binds; presence is +/// detectable per interface, and present interfaces are callable. +#[tokio::test] +async fn optional_exports_bind_per_interface() { + let env = env(); + let min = Component::from_file(&env.engine, dist("min.wasm")).unwrap(); + let full = Component::from_file(&env.engine, dist("full.wasm")).unwrap(); + + // Presence is visible from the compiled component, before instantiation. + assert!(min.get_export_index(None, BASE).is_some()); + assert!(min.get_export_index(None, CODE_ACTIONS).is_none()); + assert!(full.get_export_index(None, CODE_ACTIONS).is_some()); + + // The whole-world binding requires every export ... + let pre_min = env.linker.instantiate_pre(&min).unwrap(); + assert!(bindings::ProbeHostPre::new(pre_min.clone()).is_err()); + + // ... but per-interface indices bind what is there. + use bindings::exports::openidea::probe::{base, code_actions, completion}; + let base_idx = base::GuestIndices::new(&pre_min).unwrap(); + assert!(code_actions::GuestIndices::new(&pre_min).is_err()); + let mut s = store(&env, TaskHandle::default()); + let inst = pre_min.instantiate_async(&mut s).await.unwrap(); + let b = base_idx.load(&mut s, &inst).unwrap(); + assert_eq!(b.call_run(&mut s, "echo", "hi").await.unwrap().unwrap(), "hi"); + + let pre_full = env.linker.instantiate_pre(&full).unwrap(); + let ca_idx = code_actions::GuestIndices::new(&pre_full).unwrap(); + let co_idx = completion::GuestIndices::new(&pre_full).unwrap(); + let mut s = store(&env, TaskHandle::default()); + let inst = pre_full.instantiate_async(&mut s).await.unwrap(); + let ca = ca_idx.load(&mut s, &inst).unwrap(); + assert_eq!(ca.call_actions(&mut s, "a.rs").await.unwrap(), ["fix:a.rs"]); + let co = co_idx.load(&mut s, &inst).unwrap(); + assert_eq!(co.call_complete(&mut s, "x").await.unwrap(), ["x1", "x2"]); +} + +/// P0-2a: with `epoch_deadline_async_yield_and_update`, a spinning guest yields, +/// so other tasks on the same (single) thread keep running. +#[tokio::test(flavor = "current_thread")] +async fn spinning_guest_yields_to_the_executor() { + let env = env(); + let pre = env.linker.instantiate_pre(&Component::from_file(&env.engine, dist("min.wasm")).unwrap()).unwrap(); + let idx = bindings::exports::openidea::probe::base::GuestIndices::new(&pre).unwrap(); + let mut s = store(&env, TaskHandle::default()); + let inst = pre.instantiate_async(&mut s).await.unwrap(); + let base = idx.load(&mut s, &inst).unwrap(); + + let ticks = Arc::new(AtomicU64::new(0)); + let ticker = { + let ticks = ticks.clone(); + tokio::spawn(async move { + loop { + ticks.fetch_add(1, Ordering::Relaxed); + tokio::task::yield_now().await; + } + }) + }; + let spin = base.call_run(&mut s, "spin", ""); + assert!(tokio::time::timeout(Duration::from_millis(200), spin).await.is_err(), "spin never returns"); + ticker.abort(); + // How often depends on how busy the machine is; that it ran at all shows the guest yielded. + assert!(ticks.load(Ordering::Relaxed) > 0, "the executor kept running other tasks while the guest spun"); +} + +/// P0-2b: dropping the call future cancels the call — and poisons the instance: +/// the next call fails with `CannotEnterComponent`. A fresh instance from the +/// same `InstancePre` is cheap (no compilation) and starts with fresh state. +#[tokio::test] +async fn cancelled_instance_cannot_be_reused_but_reinstantiates_fast() { + let env = env(); + let pre = env.linker.instantiate_pre(&Component::from_file(&env.engine, dist("min.wasm")).unwrap()).unwrap(); + let idx = bindings::exports::openidea::probe::base::GuestIndices::new(&pre).unwrap(); + let mut s = store(&env, TaskHandle::default()); + let inst = pre.instantiate_async(&mut s).await.unwrap(); + let base = idx.load(&mut s, &inst).unwrap(); + assert_eq!(base.call_run(&mut s, "count", "").await.unwrap().unwrap(), "1"); + + // Cancel while the guest computes. + let _ = tokio::time::timeout(Duration::from_millis(50), base.call_run(&mut s, "spin", "")).await; + let err = base.call_run(&mut s, "echo", "x").await.unwrap_err(); + assert_eq!(err.downcast_ref::(), Some(&wasmtime::Trap::CannotEnterComponent), "{err:?}"); + + // Cancel while the guest waits in an async host import: same result. + let mut s = store(&env, TaskHandle::default()); + let inst = pre.instantiate_async(&mut s).await.unwrap(); + let base = idx.load(&mut s, &inst).unwrap(); + let _ = tokio::time::timeout(Duration::from_millis(20), base.call_run(&mut s, "sleep", "5000")).await; + assert!(base.call_run(&mut s, "echo", "x").await.is_err()); + + // Re-instantiation: a new store + instance from the pre-instantiated component. + let started = Instant::now(); + let mut runs = 0; + while runs < 20 { + let mut s = store(&env, TaskHandle::default()); + let inst = pre.instantiate_async(&mut s).await.unwrap(); + let base = idx.load(&mut s, &inst).unwrap(); + assert_eq!(base.call_run(&mut s, "count", "").await.unwrap().unwrap(), "1", "state starts fresh"); + runs += 1; + } + let per = started.elapsed() / runs; + eprintln!("re-instantiate + first call: {per:?} per instance"); + assert!(per < Duration::from_millis(30), "{per:?}"); +} + +/// P0-2c: a guest that returns an error (not a trap) leaves the instance usable, +/// and an async host import does not block the thread. +#[tokio::test(flavor = "current_thread")] +async fn async_host_import_does_not_block() { + let env = env(); + let pre = env.linker.instantiate_pre(&Component::from_file(&env.engine, dist("min.wasm")).unwrap()).unwrap(); + let idx = bindings::exports::openidea::probe::base::GuestIndices::new(&pre).unwrap(); + let mut s = store(&env, TaskHandle::default()); + let inst = pre.instantiate_async(&mut s).await.unwrap(); + let base = idx.load(&mut s, &inst).unwrap(); + assert!(base.call_run(&mut s, "nope", "").await.unwrap().is_err()); + let other = tokio::spawn(async { tokio::time::sleep(Duration::from_millis(10)).await }); + let started = Instant::now(); + assert_eq!(base.call_run(&mut s, "sleep", "100").await.unwrap().unwrap(), "slept"); + assert!(other.is_finished(), "the other task ran during the host sleep"); + assert!(started.elapsed() >= Duration::from_millis(100)); + assert_eq!(base.call_run(&mut s, "echo", "still").await.unwrap().unwrap(), "still"); +} + +/// P0-3: streaming + cancellation on WASI p2 alone: the guest blocks on a host +/// `pollable` (which yields to the executor), consumes pushed items, reports +/// progress, and returns cleanly when the host flags cancellation — the instance +/// stays usable (cooperative cancellation, unlike dropping the future). +#[tokio::test] +async fn pollable_task_streams_and_cancels_cooperatively() { + let env = env(); + let pre = env.linker.instantiate_pre(&Component::from_file(&env.engine, dist("min.wasm")).unwrap()).unwrap(); + let idx = bindings::exports::openidea::probe::base::GuestIndices::new(&pre).unwrap(); + let task = TaskHandle::default(); + let mut s = store(&env, task.clone()); + let inst = pre.instantiate_async(&mut s).await.unwrap(); + let base = idx.load(&mut s, &inst).unwrap(); + + let driver = { + let task = task.clone(); + tokio::spawn(async move { + for item in ["a", "b", "c"] { + tokio::time::sleep(Duration::from_millis(10)).await; + task.push(item); + } + // Wait until the guest consumed everything, then cancel. + while task.progress.load(Ordering::Acquire) < 3 { + tokio::time::sleep(Duration::from_millis(2)).await; + } + task.cancel(); + }) + }; + let out = tokio::time::timeout(Duration::from_secs(5), base.call_run(&mut s, "task", "")).await.unwrap(); + driver.await.unwrap(); + assert_eq!(out.unwrap().unwrap(), "cancelled after a,b,c"); + assert_eq!(task.progress.load(Ordering::Acquire), 3); + assert_eq!(base.call_run(&mut s, "echo", "reusable").await.unwrap().unwrap(), "reusable"); +} + +/// Serialized compilation output loads without recompiling (P4 cache). +#[test] +fn serialized_component_round_trips() { + let env = env(); + let bytes = std::fs::read(dist("full.wasm")).unwrap(); + let t = Instant::now(); + let compiled = Component::new(&env.engine, &bytes).unwrap(); + let compile = t.elapsed(); + let blob = compiled.serialize().unwrap(); + let t = Instant::now(); + // SAFETY: the blob was produced by this engine just above. + let loaded = unsafe { Component::deserialize(&env.engine, &blob) }.unwrap(); + let load = t.elapsed(); + eprintln!("compile {compile:?}, deserialize {load:?}"); + assert!(loaded.get_export_index(None, CODE_ACTIONS).is_some()); + assert!(load < compile); +} diff --git a/crates/ide-run/src/detect.rs b/crates/ide-run/src/detect.rs index 24cf12f6..c9195b40 100644 --- a/crates/ide-run/src/detect.rs +++ b/crates/ide-run/src/detect.rs @@ -40,6 +40,7 @@ pub(crate) fn detect_with_profiles( detect_make(root, &mut out); detect_just(root, &mut out); detect_godot(root, &mut out); + crate::external::detect(root, &mut out); let mut seen = HashSet::new(); out.retain(|c| seen.insert(c.id.clone())); diff --git a/crates/ide-run/src/external.rs b/crates/ide-run/src/external.rs new file mode 100644 index 00000000..340a714c --- /dev/null +++ b/crates/ide-run/src/external.rs @@ -0,0 +1,93 @@ +//! Run configurations detected outside this crate: plugins' `runDetectors`. +//! Their ids start with [`EXTERNAL_PREFIX`]; before +//! one is started the provider names the program to run (the file approved +//! for the plugin's `process:` capability) or refuses. + +use crate::RunConfig; +use parking_lot::RwLock; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +/// Id prefix of externally detected configurations (`plugin::`). +pub const EXTERNAL_PREFIX: &str = "plugin:"; + +pub trait ExternalDetection: Send + Sync { + /// Configurations for the project at `root`; ids start with [`EXTERNAL_PREFIX`]. + fn detect(&self, root: &Path) -> Vec; + /// The program to start for `config` (one this provider detected), or why + /// it may not start. + fn launch(&self, config: &RunConfig) -> Result; +} + +static PROVIDER: RwLock>> = RwLock::new(None); + +/// Installs (or removes) the provider [`crate::detect`] and runs consult. +pub fn set_external_detection(provider: Option>) { + *PROVIDER.write() = provider; +} + +pub(crate) fn detect(root: &Path, out: &mut Vec) { + let provider = PROVIDER.read().clone(); + if let Some(p) = provider { + out.extend(p.detect(root).into_iter().filter(|c| c.id.starts_with(EXTERNAL_PREFIX))); + } +} + +/// `config` with the program its provider approved, for an externally +/// detected configuration; `None` for every other one. +pub(crate) fn approved(config: &RunConfig) -> Option> { + if !config.detected || !config.id.starts_with(EXTERNAL_PREFIX) { + return None; + } + let provider = PROVIDER.read().clone(); + Some(match provider { + Some(p) => p + .launch(config) + .map(|program| RunConfig { command: program.to_string_lossy().into_owned(), ..config.clone() }), + None => Err("the plugin that detected this configuration is not loaded".into()), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ProcessManager, StartOptions}; + + /// Answers only for projects with its own marker (tests share the provider). + struct Fake; + + const MARKER: &str = "fake-external-detection.marker"; + + impl ExternalDetection for Fake { + fn detect(&self, root: &Path) -> Vec { + if !root.join(MARKER).exists() { + return Vec::new(); + } + let mut c: RunConfig = serde_json::from_value(serde_json::json!({ + "id": "plugin:acme:x", "name": "x", "kind": "plugin", "command": "x", "args": ["a"], + "cwd": null, "env": {}, "detected": true, "isTest": false, "debugAdapter": null + })) + .unwrap(); + c.detected = true; + let other = RunConfig { id: "not-prefixed".into(), ..c.clone() }; + vec![c, other] + } + fn launch(&self, _: &RunConfig) -> Result { + Err("not allowed".into()) + } + } + + #[test] + fn external_configs_join_detection_and_launch_only_when_approved() { + set_external_detection(Some(Arc::new(Fake))); + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join(MARKER), "").unwrap(); + let configs = crate::detect(tmp.path()); + assert_eq!(configs.iter().map(|c| c.id.as_str()).collect::>(), ["plugin:acme:x"]); + let err = ProcessManager::new() + .start(tmp.path(), &configs[0], &StartOptions::default(), Arc::new(ide_core::NullSink), Box::new(|_| {})) + .unwrap_err(); + assert_eq!(err.kind, ide_core::error::ErrorKind::PermissionDenied); + assert!(err.message.contains("not allowed")); + } +} diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs index 1ca1a0a1..7e85a164 100644 --- a/crates/ide-run/src/lib.rs +++ b/crates/ide-run/src/lib.rs @@ -4,6 +4,7 @@ mod config; mod detect; pub mod dotnet; pub mod envfile; +mod external; pub mod go; pub mod gradle_jvm; pub mod import; @@ -192,6 +193,8 @@ pub struct RunInfo { pub pty: bool, } +pub use external::{EXTERNAL_PREFIX, ExternalDetection, set_external_detection}; + /// Detects configs from package.json scripts, Cargo.toml targets, build.gradle(.kts), /// pom.xml, go.mod, pyproject/pytest, Makefile. pub fn detect(root: &Path) -> Vec { diff --git a/crates/ide-run/src/process.rs b/crates/ide-run/src/process.rs index ce900eca..2899c026 100644 --- a/crates/ide-run/src/process.rs +++ b/crates/ide-run/src/process.rs @@ -329,6 +329,12 @@ impl ProcessManager { if config.command.trim().is_empty() { return Err(IdeError::invalid("run configuration has no command")); } + let approved = match crate::external::approved(config) { + Some(Ok(c)) => Some(c), + Some(Err(e)) => return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, e)), + None => None, + }; + let config = approved.as_ref().unwrap_or(config); let plan = crate::go::plan(root, config)?; let followup = plan.as_ref().and_then(|p| p.run.as_ref()).map(|run| { let cwd = resolve_cwd(root, run.cwd.as_deref()); diff --git a/crates/ide-sdk/src/apply.rs b/crates/ide-sdk/src/apply.rs index 3c1eb64f..600d8dd6 100644 --- a/crates/ide-sdk/src/apply.rs +++ b/crates/ide-sdk/src/apply.rs @@ -544,6 +544,7 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi max_java: None, launch_error: None, tsserver_project: false, + pinned: None, } } @@ -553,6 +554,8 @@ pub fn server_launch_overrides(cfg: &mut LanguageServerConfig, s: &Settings) { let Some(ls) = s.language_servers.get(&cfg.name) else { return }; if let Some(command) = non_empty(ls.command.trim()) { cfg.command = command.to_owned(); + // The user's own program, not the one approved for a plugin. + cfg.pinned = None; } if let Some(args) = &ls.args { cfg.args = args.clone(); diff --git a/crates/ide-sdk/src/tests.rs b/crates/ide-sdk/src/tests.rs index 167efed1..3117fdda 100644 --- a/crates/ide-sdk/src/tests.rs +++ b/crates/ide-sdk/src/tests.rs @@ -36,6 +36,7 @@ fn server(name: &str) -> LanguageServerConfig { max_java: None, launch_error: None, tsserver_project: false, + pinned: None, } } diff --git a/crates/ide-workspace/src/documents.rs b/crates/ide-workspace/src/documents.rs index dbcee862..7bb74199 100644 --- a/crates/ide-workspace/src/documents.rs +++ b/crates/ide-workspace/src/documents.rs @@ -563,6 +563,27 @@ impl Documents { }) } + /// [`apply_edits`](Self::apply_edits) only if the document is still at + /// `version` (checked under the document's lock). `Ok(None)` when it + /// changed since; nothing is applied then. + pub fn apply_edits_at(&self, doc: DocId, version: u32, edits: &[TextEdit]) -> IdeResult> { + self.with_doc(doc, |st| { + if st.doc.version() != version { + return Ok(None); + } + if st.read_only { + return Err(read_only_error(&st.path)); + } + if edits.is_empty() { + return Ok(Some(version)); + } + let (set, applied, bytes) = st.doc.apply_edits_detailed(edits)?; + self.patched(doc, st, version, set, &applied, &bytes); + self.set_dirty(doc, st, true); + Ok(Some(st.doc.version())) + }) + } + fn patched( &self, doc: DocId, diff --git a/docs/plugins/themes.md b/docs/plugins/themes.md index 013041bf..b11082a3 100644 --- a/docs/plugins/themes.md +++ b/docs/plugins/themes.md @@ -17,7 +17,8 @@ my-theme/ └─ my-theme.scheme.json # editor colours, optional (IntelliJ: .icls) ``` -The quickest way to start is to copy [`templates/theme-plugin`](../../templates/theme-plugin). +The quickest way to start is `openidea-plugin new --template theme`, or a copy of +[`plugins/official/harbor-night`](../../plugins/official/harbor-night). It contains *Harbor Night*, a complete example dark theme that sets every themeable token. The rest of this page covers the file format, the token reference, porting themes from IntelliJ IDEA and VS Code, and testing. @@ -106,11 +107,13 @@ built-in theme returns. There is no build step. The package *is* the folder. -1. Copy `templates/theme-plugin` and rename `id`, `name` and the theme files. +1. Run `openidea-plugin new --template theme` (or copy + `plugins/official/harbor-night`) and rename `id`, `name` and the theme files. 2. Edit the colours. Keep `kind` truthful (`light` for light backgrounds). 3. **Install:** *Settings › Plugins › ⚙ › Install Plugin from Disk…* (or the - *Install Plugin from Disk…* action) and pick the package's `plugin.toml`, or - a `.zip` of the folder. The manifest and the files it references are copied to + *Install Plugin from Disk…* action) and pick the package folder, or + *Install Plugin from Package File…* and pick its `plugin.toml` or a `.zip` of + the folder. The manifest and the files it references are copied to `/plugins//`. 4. **Apply:** in *Settings › Plugins*, select the plugin and press *Apply* next to the theme. *Use Default Theme* switches back. diff --git a/knip.ts b/knip.ts index cce08398..600d5224 100644 --- a/knip.ts +++ b/knip.ts @@ -10,6 +10,8 @@ const config: KnipConfig = { "perf/**/*.ts", "e2e/**/*.ts", ], + // Plugins' web pages are projects of their own (own package.json, checked by plugins/build.sh and CI). + ignore: ["plugins/**/web-src/**"], ignoreExportsUsedInFile: true, // lint-staged formats Rust files with the toolchain's rustfmt. ignoreBinaries: ["rustfmt"], diff --git a/perf/budgets.json b/perf/budgets.json index 25b40729..f831d10c 100644 --- a/perf/budgets.json +++ b/perf/budgets.json @@ -1,5 +1,5 @@ { - "$comment": "Upper bounds, lower is better. ui: `.` from `pnpm perf` (medians of the measured runs; enforced at CPU 1x only). Latencies are input → start of the first frame showing the result, so ~16.7 ms is 'next frame'. rust: criterion bench id → mean in microseconds, from `pnpm perf:rust`.", + "$comment": "Upper bounds, lower is better. ui: `.` from `pnpm perf` (medians of the measured runs; enforced at CPU 1x only). Latencies are input → start of the first frame showing the result, so ~16.7 ms is 'next frame'. rust: criterion bench id → mean in microseconds, from `pnpm perf:rust` (`plugins/…`: the plugin runtime budgets).", "regressionTolerance": 0.2, "regressionFloor": 1, "ui": { @@ -83,6 +83,10 @@ "search_5k/literal": 100000, "search_5k/regex": 100000, - "search_5k/dense_limit": 20000 + "search_5k/dense_limit": 20000, + + "plugins/load_50": 20000, + "plugins/cold_activation": 30000, + "plugins/syntax_highlights_2k_lines": 50000 } } diff --git a/perf/rust.ts b/perf/rust.ts index a79889f5..34538396 100644 --- a/perf/rust.ts +++ b/perf/rust.ts @@ -16,7 +16,7 @@ import { evaluate, loadBudgets, printReport, type ScenarioResult } from "./lib/r const ROOT = resolve(import.meta.dirname, ".."); const TARGET = resolve(ROOT, process.env.CARGO_TARGET_DIR ?? "target"); const OUT = join(ROOT, "target", "perf"); -const PACKAGES = ["ide-text", "ide-language", "ide-index", "ide-search"]; +const PACKAGES = ["ide-text", "ide-language", "ide-index", "ide-search", "ide-host"]; const { values: args } = parseArgs({ options: { diff --git a/plugins/README.md b/plugins/README.md index fd1a745b..4e994f5e 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -1,87 +1,210 @@ # Writing OpenIDEA plugins OpenIDEA plugins are sandboxed **WebAssembly components** (wasmtime, component -model, WASI preview 2), in the style of Zed extensions. A plugin can register -commands (they become IDE actions you can search for and bind to keys), read -project files, insert text into the editor, show notifications and contribute -themes and languages. Plugins that only contribute themes or languages need no -code at all. +model, WASI preview 2). A plugin can register commands (they become IDE actions +you can search for and bind to keys), read project files, edit the focused +editor, react to workbench events, run background tasks, show notifications +and status bar items, keep data in its own storage, read and fetch git +repositories, provide completion, quick fixes, navigation and gutter markers, +call web services and run approved programs, show tool windows and custom +editors, and contribute menus, shortcuts, settings, themes, file icon themes +and languages. Plugins that only contribute data (themes, icons, languages, +menus, settings) need no code at all. + +> **Preview.** The plugin system ships as a preview: until it is declared +> stable the API (`openidea:plugin@1.0`) may still change, and the official +> plugins are versioned `0.x`. See _Evolving the plugin API_ below. ``` plugins/ -├─ build.sh # builds Rust plugins into components -├─ hello/ # Rust plugin: two commands -└─ language-toy/ # manifest-only: a language definition +└─ official/ + ├─ harbor-night/ # data only: a colour theme (UI and editor scheme) + ├─ material-icons/ # data only: a file icon theme + ├─ solidity/ # language + syntax provider + run configurations + ├─ string-tools/ # 26 text commands, versioned multi-cursor edits + ├─ key-promoter/ # action events, storage + ├─ git-toolbox/ # on-schedule fetch, tasks, VCS, status bar item + ├─ checkstyle/ # one-shot process, diagnostics, quick fixes + ├─ ai-completion/ # inline completion over the network, secrets + ├─ mybatis/ # navigation, gutter markers, completion across files + ├─ csv-editor/ # custom editor sharing the text document + ├─ excalidraw/ # web view custom editor, file icons, a template + ├─ graphviz/ # web view with code: live preview, problems from the page, a language + ├─ regex-tester/ # html view talking to its code, settings, the editor's selection + └─ license-header/ # file-opened events, quick fix, project scan in a task +sdk/rust/openidea-plugin/ # the Rust SDK (host API, Plugin trait, mock host) +crates/ide-plugin/tests/fixtures/ # test plugins: hello, jobs, language-toy, misbehave ``` -The API is defined in [`wit/plugin.wit`](../wit/plugin.wit) (`openidea:plugin/plugin@0.1.0`). +The plugin API is defined in [`wit/`](../wit/) (`openidea:plugin@1.0.0`, world +`plugin`). -## 1. The package +## 1. Quick start + +The `openidea-plugin` tool scaffolds, builds, checks and links plugins: + +```sh +cargo install --path crates/ide-host --bin openidea-plugin # or: cargo run -p ide-host --bin openidea-plugin -- … + +openidea-plugin new my-plugin # Rust command plugin (SDK) +openidea-plugin new my-theme --template theme # also: icon-theme, language +cd my-plugin +cargo test # logic, against the SDK's mock host +openidea-plugin build # → dist/plugin.wasm, then `check` +openidea-plugin link # load this folder in the IDE +``` + +`build` runs `cargo build --release --target wasm32-wasip2` (installing the +target through rustup if needed), copies the component to the manifest's +`wasm` path and runs `check`. `check` validates the package exactly as +_Install Plugin from Disk…_ would — manifest, every contribution, the SVG +sanitiser, the component — and that the component imports nothing but the +plugin API and WASI. It prints what the user will be asked to grant. + +`link` adds the folder to `links.json` in the IDE's plugins directory +(`$OPENIDEA_PLUGINS_DIR`, default `/ai.l0ng.openidea/plugins`). Linked +plugins are read from the folder itself, so the edit loop is `build` then +Settings › Plugins › _Reload_. `unlink` and `links` undo and list. + +## 2. The package A plugin is a directory with a `plugin.toml`: ```toml -id = "hello" # [a-z0-9][a-z0-9_-]*, unique -name = "Hello" -version = "0.1.0" # semver -description = "Inserts today's date and counts words." +id = "acme.word-tools" # [a-z0-9][a-z0-9_-]*, optionally with dotted namespaces +name = "Word Tools" +version = "1.2.0" # semver +description = "Counts and transforms words." authors = ["You "] -homepage = "https://example.com" # optional -openidea-api = "0.1" # API version this plugin targets -wasm = "dist/plugin.wasm" # omit for contribution-only plugins -permissions = ["project-read", "editor-read", "editor-write"] +homepage = "https://example.com" # optional +license = "MIT" # optional +change-notes = "1.2.0 — …" # shown under What's New +engines.openidea = "^1.0" # the plugin API this package needs +wasm = "dist/plugin.wasm" # omit for data-only plugins +activation = ["on-language:markdown"] # optional, see below + +[capabilities] +required = ["project.read", "editor.write"] +optional = ["net:api.example.com"] -# Optional static contributions (active even before / without code): [[contributes.commands]] -id = "insert-date" # [a-z0-9][a-z0-9._-]* -title = "Hello: Insert Date" -category = "Hello" # group in Search Everywhere / Keymap - -[[contributes.themes]] -path = "themes/my-theme.json" - -[[contributes.languages]] -path = "languages/my-lang.toml" +id = "count" # [a-z0-9][a-z0-9._-]* +title = "Word Tools: Count Words" +category = "Word Tools" # group in Search Everywhere / Keymap +when = "editorFocus" # optional: same expressions as built-in actions ``` -All paths are relative to the package directory and may not leave it. +All paths are relative to the package directory and may not leave it. A +manifest is validated as a whole: if one contribution is invalid, nothing is +installed or loaded. Contribution types the IDE does not know (a newer API) are +skipped with a warning. -### Permissions +Manifests in the 0.1 format (`openidea-api = "0.1"`, `permissions = [...]`) +still load (their permissions become required capabilities; contributions +work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK. -| Permission | Unlocks | -| -------------- | ------------------------------------------------- | -| `project-read` | `workspace-root`, `read-file` (project root only) | -| `editor-read` | `active-file` | -| `editor-write` | `insert-text`, `replace-selection` | +### Contribution points -`log`, `register-command`, `show-notification`, `register-language` and -`register-theme` are always available. Calling a gated function without its -permission **traps**: the plugin is stopped and the user is told which -permission is missing. +| Point | Declaration | Code needed | +| --------------- | -------------------------------------------------------------------------------------------------- | ------------- | +| `commands` | `id`, `title`, `category?`, `when?` | to run them | +| `themes` | `path` (theme JSON), `editor-scheme?` | no | +| `iconThemes` | `id`, `label`, `path` (icon theme JSON, see §5) | no | +| `languages` | `path` (`languages/.toml` format, see §6) | no | +| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?` (§6.2) | no | +| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes | +| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them | +| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `tools`), `command`, `when?` | no | +| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`) | no | +| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | +| `settings` | `schema` (JSON file), `title?` — one table, see _Settings_ | no | +| `views` | `id`, `title`, `icon?`, `location` (`left`, `right`, `bottom`), `web?` (see _Web views_) | without `web` | +| `customEditors` | `id`, `title`, `patterns` (file names), `priority` (`default`, `option`), `layout?`, `web?` | without `web` | +| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no | +| `fileTemplates` | `id`, `name`, `extension`, `path` (the new file's content; template variables work) — New menu | no | -## 2. Writing code (Rust) +Declared contributions are live as soon as the plugin is enabled — commands +show in Find Action, menus and the status bar, shortcuts work, themes and icon +themes can be applied, settings pages are there — **before** any plugin code +is loaded. Menus, shortcuts and status bar items refer to the plugin's +declared commands. A plugin shortcut never takes a keystroke the IDE (or the +user) already uses; the user can rebind it in the keymap editor. -`wasm32-wasip2` produces a component directly, so all you need is rustup: +### Activation -```sh -rustup target add wasm32-wasip2 -``` +Code is instantiated lazily: when one of the plugin's commands runs, or when +an event in `activation` fires: -`Cargo.toml`: +| Event | Fires when | +| --------------------- | ------------------------------------------------------ | +| `on-command:` | the command runs (implied for every command) | +| `on-language:` | a file of that language is opened (`*`: any) | +| `on-file:` | a project file matching the glob is opened (`**`) | +| `on-view:` | one of the plugin's views is shown | +| `on-schedule:` | every `secs` seconds (at least 60): `Event::Scheduled` | +| `on-event:` | a workbench event of that kind (see _Events_) | +| `on-startup-finished` | shortly after the workbench is ready (use sparingly) | + +Until then the plugin is listed as _Inactive_ and costs nothing at start-up. +An instance unused for 5 minutes is reclaimed (its `deactivate` runs) and the +plugin is _Inactive_ again until its next event; `on-schedule` activates it +when due but does not keep it alive. Keep nothing in memory you can't rebuild +in `activate`. + +### Capabilities + +Code can only do what its capabilities allow, and the user approves them when +installing (or when a new version asks for more). Low-risk capabilities are +listed; high-risk ones are called out as equivalent to running code on the +machine. Users can revoke optional capabilities in Settings › Plugins. + +| Capability | Risk | Unlocks today | +| ------------------- | ------ | ----------------------------------------------------------------------------------- | +| `project.read` | low | `Project::root`, `read_file`, `find_files`, `host::projects`, `publish_diagnostics` | +| `editor.read` | low | `TextEditor::document`, `selections` | +| `editor.write` | medium | `TextEditor::apply_edits` | +| `vcs.read` | low | `Project::vcs_status` (branch, upstream, ahead/behind, changes) | +| `vcs.write` | medium | `Project::vcs_fetch` (trusted projects only) | +| `storage` | low | `host::storage` (1 MiB per plugin) | +| `events` | low | file opened/saved, editor focused, repository changed events | +| `events.input` | medium | `action-performed` events (which actions you run, and how) | +| `process:` | high | `Project::run_process`, language servers, debug adapters, runs | +| `net:` | medium | `host::fetch` to that host (`*.example.com`: its subdomains) | +| `secrets` | medium | `{{secret:}}` in request headers, `host::secret_is_set` | +| `clipboard` | medium | the clipboard API in the plugin's web views (keyboard copy / paste work without it) | + +`process:` capabilities are also derived from what the contributions start: a +language's `language-servers` and `debugger` commands and a run detector's +`command`. Those are optional — refusing one keeps the rest of the plugin +working. On grant the program is resolved to an absolute path and its content +hash is recorded; it is checked again right before every start, and a replaced +file is refused until the user approves it again. In a remote project the +server resolves and pins the program on its own machine (see _Remote +projects_). `fs.read:` can be declared and granted; it unlocks nothing +yet. + +Logging, notifications, status bar items, tasks and run-time contributions +are always available. Calling a gated function without its capability returns +`Error::Denied("")` — the plugin keeps running and can degrade +(Git Toolbox still shows the branch without `vcs.write`). + +## 3. Writing code (Rust SDK) + +`openidea-plugin new` writes this for you. `Cargo.toml`: ```toml [package] -name = "my-plugin" +name = "openidea-plugin-word-tools" version = "0.1.0" edition = "2024" -[workspace] # keep it out of any parent workspace +[workspace] # keep it out of any parent workspace [lib] -crate-type = ["cdylib"] +crate-type = ["cdylib", "rlib"] [dependencies] -wit-bindgen = "0.63" +openidea-plugin = { path = "…/sdk/rust/openidea-plugin" } [profile.release] opt-level = "s" @@ -93,62 +216,298 @@ panic = "abort" `src/lib.rs`: ```rust -wit_bindgen::generate!({ world: "plugin", path: "path/to/openidea/wit" }); +use openidea_plugin::{Error, Invocation, NotificationLevel, Plugin, host, register_plugin}; -use openidea::plugin::host::{self, LogLevel, NotificationLevel}; +#[derive(Default)] +struct WordTools; -struct MyPlugin; - -impl Guest for MyPlugin { - fn activate(_ctx: Context) -> Result<(), String> { - host::register_command("shout", "My Plugin: Shout Selection", Some("My Plugin")); - Ok(()) - } - - fn deactivate() {} - - fn run_command(id: String, arg: Option) -> Result, String> { - match id.as_str() { - "shout" => { - host::replace_selection(&arg.unwrap_or_default().to_uppercase()); +impl Plugin for WordTools { + fn run_command(&mut self, id: &str, ctx: &Invocation, _arg: Option<&str>) -> Result, Error> { + let editor = ctx.editor().ok_or("no file is open")?; + match id { + "count" => { + let words = editor.document()?.text.split_whitespace().count(); + host::notify(NotificationLevel::Info, "Word count", &format!("{words} words")); Ok(None) } - _ => Err(format!("unknown command {id}")), + // Every selection (a cursor: empty) in one undoable change. + "shout" => { + editor.transform_selections(|s| s.to_uppercase())?; + Ok(None) + } + _ => Err(Error::NotFound(format!("command {id}"))), } } } -export!(MyPlugin); +register_plugin!(WordTools); ``` -Build (copy `build.sh` or run it with your plugin's path): +On `wasm32-wasip2` the SDK calls the IDE; on your machine it calls the SDK's +mock host, so the logic is unit-tested with `cargo test`: -```sh -plugins/build.sh hello # → plugins/hello/dist/plugin.wasm -plugins/build.sh /path/to/my-plugin +```rust +#[test] +fn counts_and_shouts() { + let host = openidea_plugin::mock::MockHost::install(); + host.open_editor("/project/a.md", "markdown", "one two three", &[(0, 4, 0, 7)]); + WordTools.run_command("count", &host.invocation(), None).unwrap(); + assert_eq!(host.notifications()[0].body, "3 words"); + WordTools.run_command("shout", &host.invocation(), None).unwrap(); + assert_eq!(host.editor_text(), "one TWO three"); +} ``` -Any language with component-model tooling works (e.g. `componentize-py`, -`jco componentize`, TinyGo): the only contract is the `plugin` world. +The mock enforces capabilities like the IDE (`MockHost::install().with_capabilities(&[...])`), +keeps a versioned editor document (`type_in_editor` makes edits stale), and +records notifications, status items, storage, subscriptions, tasks, fetches, +commands, languages, themes and log lines. -### Host functions +Any language with component-model tooling works (`componentize-py`, +`jco componentize`, TinyGo): the only contract is the `plugin` world in +[`wit/`](../wit/) (`plugin-syntax` adds the syntax provider). Build it yourself, +then run `openidea-plugin check`. -| Function | Notes | -| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -| `log(level, msg)` | Goes to the IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. | -| `register-command(id, title, category?)` | Becomes action `plugin..`; call again to rename. Max 256 commands. | -| `show-notification(level, title, body)` | Balloon in the invoking window. | -| `workspace-root()` | Root of the project the command runs in. | -| `active-file()` | Absolute path of the focused editor's file. | -| `read-file(path)` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB. Unsaved editor contents win over disk. | -| `insert-text(text)` | Inserts at every cursor of the active editor (cursor ends after the text). | -| `replace-selection(text)` | Replaces every selection and selects the new text. | -| `register-language(toml)` | Same format as `languages/.toml`. | -| `register-theme(json)` | See _Themes_ below. | +### The API -`run-command` receives an optional string argument: `executeAction("plugin.hello.insert-date", "arg")` +| Rust SDK | WIT | Notes | +| ------------------------------------------------------------------------ | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Plugin::run_command(id, ctx, arg)` | export `commands.run` | `ctx` is the window: `ctx.project()`, `ctx.editor()`. An error shows _" failed: …"_; the plugin keeps running. `"msg".into()` is `Error::Failed`; `Cancelled` and `Denied` don't count as the plugin failing. | +| `Plugin::handle_events(events, ctx)` | export `event-handler.handle` | Batches of subscribed events, oldest first, per window. | +| `Plugin::activate` / `deactivate` | export `lifecycle` | Per instance: after a crash or idle reclaim a new one is activated. | +| `TextEditor::document()` → `{version, text}` | `editor.text-editor.document` | `selections()` are those when the command ran (0-based lines, UTF-16 columns). | +| `TextEditor::apply_edits(version, edits)` | `editor.text-editor.apply-edits` | One undoable change, only if the document is still at `version` — else `Error::Stale` and nothing changes. `transform_selections` retries once. | +| `Project::root()`, `read_file(path)` | `workspace.project` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB; unsaved editor contents win. | +| `host::projects()` | `workspace.projects` | Every open project (for scheduled work without a window). | +| `Project::vcs_status()`, `vcs_fetch()` | `vcs` | Fetch runs git, so only in trusted projects; call it inside a task. | +| `host::subscribe(kind)` | `events.subscribe` | For the session, across idle reclaim (an event activates the plugin). Or declare `on-event:<kind>`. | +| `host::begin_task(title, cancellable)` → `Task` | `tasks.begin` | Shown with the background tasks; `report`, `is_cancelled`; the call may run 60 s instead of 5 s while it is open; dropping it ends it. | +| `host::storage::{get, set, delete, keys}` | `storage` | Survives restarts; the instance's memory does not. Deleted on uninstall. | +| `host::set_status_item(id, item)`, `remove_status_item` | `ui` | `text`, `tooltip`, `command` (one of yours, run on click); at most 8; kept while the plugin is idle. | +| `host::notify(level, title, body)` | `ui.show-notification` | Balloon in the window the command or events came from (every window otherwise). | +| `host::log(level, msg)` | `log` | IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. | +| `Project::find_files(glob, limit)` | `workspace.project.find-files` | Project-relative glob (`**/*Mapper.xml`); honours `.gitignore`; at most `limit` paths. | +| `host::publish_diagnostics(path, items)` | `diagnostics.publish` | Replaces this plugin's problems for the file (editor squiggles and the Problems view); an empty list clears them. | +| `host::fetch(request)` → `{status, headers, body}` | `net.fetch` | See _Network_. | +| `Project::run_process(program, args, stdin)` → `{code, stdout, stderr}` | `process.run` | Only the pinned program of a `process:` grant; runs in the project root of a trusted project; 4 MiB of output; killed when the call is cancelled or times out. | +| `host::refresh_view(view)` | `views.refresh` | The view (or custom editors) render again; call it when the content changed. | +| `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. | +| `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:<program>` in the project root: output that keeps coming, interactive sessions. | +| `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. | + +`run-command` receives an optional string argument: `executeAction("plugin.<plugin id>.<command id>", "arg")` from another feature, or nothing when run from Search Everywhere / a shortcut. -Returning `Err(msg)` shows _"<title> failed: msg"_; the plugin keeps running. + +### Events + +| Kind | Capability | Delivered | +| ------------------ | -------------- | ------------------------------------------------------------------------- | +| `file-opened` | `events` | a file opens in an editor | +| `file-saved` | `events` | after the file is written | +| `editor-focused` | `events` | the focused editor changes (path, or none) | +| `vcs-changed` | `events` | a repository's state changed (commit, checkout, fetch…; its root) | +| `action-performed` | `events.input` | an IDE action ran: id, title, source (keyboard, menu, toolbar…), shortcut | +| `scheduled` | — | the `on-schedule` period elapsed | + +Events are batched: a running plugin gets them within a fraction of a second, +an idle one collects them for 2 s before it is woken, so frequent events +(Key Promoter's actions) don't keep it alive. + +### Providers + +Declare what the plugin provides in the editor; only plugins whose +declaration matches the file's language are called (and loaded): + +```toml +[[contributes.providers]] +kinds = ["definition", "line-markers", "completion"] # also "inline-completion", "code-actions" +languages = ["java", "xml"] # editor language ids; "*" for any +``` + +Then `register_plugin!(MyPlugin, providers)` and implement +`openidea_plugin::providers::Providers` for it: `completion`, +`inline_completion`, `code_actions`, `definition`, `line_markers`. Each gets +the document (path, language, version, text). Results join the language +servers' (completion lists, ⌥⏎ quick fixes, ⌘B, gutter icons; a code action +carries edits for any files, applied as one change). A completion item's +`kind` (`CompletionKind` in the SDK, a string in the WIT) picks its icon. +Editor providers run under the edit-path budget: 50 ms, after which the +result is dropped, and an interruption at 500 ms. Every plugin providing a +kind is asked at the same time, so each has the whole budget. + +Providers run in the plugin's one instance, with its commands, events and +views: they see the same memory (Checkstyle answers quick fixes from the +results of its last check) but also wait behind them. Keep commands and event +handlers short where you can; a provider call queued behind a long one is +dropped at 50 ms like a slow one. Inline completion is exempt from the 50 ms (it may +need the network) but is cancelled as soon as the user types on: check +`Task::is_cancelled` or just let the host interrupt the call. + +### Network and secrets + +`host::fetch` makes an HTTPS request (plain HTTP only to `localhost`) to a host +the plugin was granted with `net:<host>`; redirects to another host are +refused and responses are limited to 8 MiB. Requests are made from the +machine the project is on. + +Secrets declared under `[[contributes.secrets]]` are entered by the user in +Settings › Plugins and kept in the system keychain. The plugin never reads +them: it writes `{{secret:<name>}}` in a request header and the host fills it +in on the way out (`secrets` capability). `host::secret_is_set(name)` tells +whether the user has entered one. + +### Views and custom editors + +A view is data: a toolbar, a body — `Tree`, `List`, `Form`, `Table`, +`Message` or `Html` — and a status line. Declare it, then +`register_plugin!(MyPlugin, views)` (or `(MyPlugin, providers, views)`) and +implement `openidea_plugin::views::Views`: + +```rust +impl Views for MyPlugin { + fn render(&mut self, view: &str, viewport: Option<Viewport>, ctx: &Invocation) -> Result<View, Error> { + Ok(View::new(Body::Tree(vec![TreeItem::new("a", "A").expandable(self.open)])) + .button(Button::new("refresh", "Refresh").icon("refresh"))) + } + fn handle(&mut self, view: &str, event: ViewEvent, ctx: &Invocation) -> Result<(), Error> { + if let ViewEvent::Expand(_) = event { + self.open = true; + host::refresh_view(view); + } + Ok(()) + } +} +``` + +The IDE draws the view with its own components (theme, keyboard, speed +search) and sends what the user does: buttons, select / activate / expand / +collapse of items, form fields, table cells, inserted and deleted rows, and +`html` messages. A tree is a flat list whose items name their `parent`; an +`expandable` item gets its children when it is expanded. A table gets only +the rows it shows (`viewport`): report `total_rows` and return those. + +Showing a view activates the plugin (`on-view:<id>`). `views` become tool +windows; a `customEditors` file (`priority = "default"`) opens in the +plugin's editor, or through _Open With_ for `option`. For a custom editor +`ctx.editor()` is its document: read it with `document()` and change it with +`apply_edits(version, …)` — the text editor of the same file follows, +Undo / Redo are one history with it, and Save, the dirty mark and the close +prompts are the document's. _Open as Text_ opens the text editor. For a +tool window `ctx.editor()` is the window's active text editor, as for a +command, so a view's buttons can act on what the user is editing (a click in +the tool window doesn't change which editor that is). + +`layout` puts a custom editor beside the text editor instead of in a tab of +its own: with `"split"` or `"preview"` the file opens in the text editor, +with your editor next to it (the layout files start in) and the _Editor Only / +Editor and … / … Only_ switch in the tab strip, as for Markdown. `"tab"` +(the default) is the editor's own tab. + +`Html` is the escape hatch for content the declarative bodies can't show. It +runs in a sandboxed frame — an opaque origin under a CSP that allows only its +inline scripts and styles and `data:` images, no network, no IDE API — and +talks to the plugin only through `openidea.postMessage(text)` / +`openidea.onMessage(fn)` (`ViewEvent::Message`, `host::post_view_message`). + +The frame follows the IDE theme without reloading: its root carries +`data-theme="light|dark"` and these CSS variables, with concrete colour +values (the body already uses the text colour, UI font and size): + +| Variable | Meaning | +| ----------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | +| `--openidea-bg`, `--openidea-bg-elevated`, `--openidea-bg-hover`, `--openidea-bg-selected`, `--openidea-bg-input` | Surfaces (the frame itself is transparent) | +| `--openidea-fg`, `--openidea-fg-strong`, `--openidea-fg-muted` | Text | +| `--openidea-border`, `--openidea-focus-ring`, `--openidea-link` | Lines, focus, links | +| `--openidea-accent`, `--openidea-fg-on-accent` | Accent and text on it | +| `--openidea-danger`, `--openidea-warning`, `--openidea-success`, `--openidea-info` | Status colours | +| `--openidea-font-ui`, `--openidea-font-mono`, `--openidea-font-size` | Fonts (web fonts the IDE bundles are not available in the frame) | + +Scripts get the same as `openidea.theme` (`{ dark, vars }`) and +`openidea.onThemeChange(fn)`, for drawing on a canvas, say. Variables are only +ever added. + +#### Web views + +A view or custom editor can instead be a web page of the package, for UIs the +declarative bodies can't express (a drawing canvas, a diagram editor) — no +code needed: + +```toml +[[contributes.customEditors]] +id = "canvas" +title = "Drawing" +patterns = ["*.excalidraw"] +layout = "preview" +web = "web/index.html" # the page; its directory is what it can load +``` + +The page's directory (never the package root) is part of the declaration: +every file under it is checked (at most 4096 files and 256 MiB, no links), +installed and signed with the package. The IDE loads the page from its own +`openidea-plugin` URL scheme into an `<iframe sandbox="allow-scripts">`: an +opaque origin, no network, no cookies or storage, no IDE API, and only the +page's own files (relative URLs, ES modules, fonts, WebAssembly) — so build +it with relative paths (Vite: `base: "./"`). The same `openidea` object as +in `html` bodies is there before the page's scripts run, plus: + +| `window.openidea` | What it does | +| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `document.get()` | `{ version, text, readOnly, name }` of the custom editor's document (`name`: the file's, without its directory; none in a tool window) | +| `document.edit(version, edits)` | Applies `[{ from, to, insert }]` (UTF-16 offsets) as one change of the document's undo history; rejects with `stale` when not at `version`; resolves `{ version }` | +| `document.replace(version, text)` | The same with the whole text (sent as the smallest edit) | +| `document.onChange(fn)` | `{ version, text }` after changes made elsewhere: the text editor, Undo, another window | +| `saveFile({ name, data, filters? })` | The IDE's save dialog; `data` is a string, bytes or a Blob; the chosen path, or `null`. The page never names a path itself | +| `openFile({ filters? })` | The IDE's open dialog; `{ name, data }` (bytes), or `null` | +| `postMessage` / `onMessage` | To and from the plugin's code, when it has some | + +Save, the dirty mark and Undo are the document's, as for every custom editor. +IDE shortcuts the page doesn't handle itself (Save, Close, Find Action…) still +work while it has focus; editing keys (⌘C, ⌘V, ⌘Z…) stay with the page. With +the `clipboard` capability the page may use `navigator.clipboard`. +`plugins/official/excalidraw` is a complete example: a Vite + React page in +`web-src/`, built into `web/` by `plugins/build.sh`. `plugins/official/graphviz` +pairs a page with code: the page renders (Graphviz compiled to WebAssembly) and +sends what Graphviz reports to the plugin, which publishes it as problems. The built page is not +checked in (it is tens of MB): run `plugins/build.sh official/excalidraw` +before installing the plugin from the repository. + +### Settings + +```toml +[contributes.settings] +schema = "settings.schema.json" +``` + +```json +{ + "properties": { + "context": { "type": "string", "title": "Context", "default": "" }, + "tailLines": { "type": "integer", "title": "Log lines", "default": 200 }, + "shell": { "type": "string", "enum": ["sh", "bash"], "default": "sh" } + } +} +``` + +Types are `boolean`, `string` (optionally `enum`, `multiline`), `number` and +`integer`, each with a `default`. The IDE generates the page under +Settings › Plugins (searchable; projects can override values) and the plugin +reads values with `host::setting*`; a stored value of the wrong type falls +back to the default. + +### Remote projects + +Plugin code runs where the project is. When a window opens a remote project, +the desktop sends its enabled code plugins and their grants to +`openidea-server`, which runs them next to the files: `read_file`, +`find_files`, `run_process`, `fetch` and diagnostics all act on the remote +machine, and `process:` programs are resolved on its `PATH`. Changes on the +desktop (install, disable, grants) follow within a second. Secrets stay in the +desktop's keychain; the server asks for one when a request header needs it. +Status items, notifications, tasks, views, custom editors and terminals of +remote plugins show in that window; a custom editor edits the remote +document. +Project plugins (`.openidea/plugins`) don't run in remote projects yet, and a +plugin's storage on the server starts empty. ### Sandbox and limits @@ -157,15 +516,23 @@ environment, no network, no inherited stdio — only clocks and randomness from WASI, plus the host functions above. Every call into the plugin is bounded: - **CPU:** a fuel budget (≈ 5·10⁹ wasm instructions) per call; -- **time:** 5 s wall clock per call (epoch interruption); +- **time:** 5 s wall clock for commands, activation and deactivation; editor + providers (syntax, completion, code actions, navigation, line markers) get + 50 ms — a later result is dropped, but the instance keeps running — and are + interrupted at 500 ms; - **memory:** 256 MiB of linear memory. -A panic, trap, permission violation or exceeded limit stops the plugin and -marks it _Failed_ for the session (with the reason in Settings › Plugins); -toggling it off and on, or _Reload_, starts a fresh instance. The IDE itself is -never affected. +Each active plugin runs on its own thread; calls are queued, never run +concurrently in one instance. A panic, trap, permission violation or exceeded +limit drops the instance: the user is told once, and the plugin starts afresh +the next time it is needed, after a pause that doubles with each crash in a +row (1 s, 2 s, …). Three crashes in a row mark it _Failed_ for the session +(with the reason in Settings › Plugins); toggling it off and on, or _Reload_, +starts it again. A call that returns normally resets the count. Settings › +Plugins shows activations, call latency (p95), crashes, late editor results +and reclaims. The IDE itself is never affected. -## 3. Themes +## 4. Themes ```json { @@ -183,42 +550,227 @@ values (no `url()`, `;`, braces); `//` and `/* */` comments are allowed. A manifest theme entry may add `editor-scheme = "themes/x.scheme.json"` (editor colours, merged over the theme). Pick a theme in Settings › Plugins › _Apply_. -Start from [`templates/theme-plugin`](../templates/theme-plugin); the full guide, -token reference and IntelliJ / VS Code porting tables are in +Start with `openidea-plugin new <dir> --template theme` (or a copy of +[`official/harbor-night`](official/harbor-night)); the full guide, token +reference and IntelliJ / VS Code porting tables are in [`docs/plugins/themes.md`](../docs/plugins/themes.md). -## 4. Languages +## 5. File icon themes + +```toml +[[contributes.iconThemes]] +id = "material" +label = "Material Icons" +path = "icons/theme.json" +``` + +`theme.json` maps names to SVGs (paths relative to the package): + +```json +{ + "iconDefinitions": { "rust": "icons/rust.svg", "folder-src": "icons/folder-src.svg" }, + "file": "file", "folder": "folder", "folderExpanded": "folder-open", + "fileExtensions": { "rs": "rust", "d.ts": "typescript-def" }, + "fileNames": { "cargo.toml": "cargo" }, + "folderNames": { "src": "folder-src" } +} +``` + +Files match by exact name, then the longest extension (`a.test.ts` tries +`test.ts`, then `ts`), then `file`. Folders match by name, then +`folder`/`folderExpanded`; folders with a role (source root, excluded, module) +keep their built-in icons. Names are case-insensitive. Up to 5000 icons of at +most 64 KiB each. Every SVG is sanitised on install: allow-listed elements and +attributes only, no scripts, event handlers, external references, `url()` or +entities. Apply a theme in Settings › Plugins; see +[`official/material-icons`](official/material-icons) for a complete one. + +## 6. Languages `languages/<id>.toml` files use the IDE's own language format; see any file in -[`languages/`](../languages) (`id`, `name`, `extensions`, `filenames`, -`first-line`, `line-comment`, `block-comment`, `indent`, `ui-mode`, -`framework-ui-modes`, `language-servers`, `debugger`). `language-toy` is a -minimal example. `[[framework-ui-modes]]` entries (`ui-mode`, `root-markers`) +[`languages/`](../languages); [`official/solidity`](official/solidity) is a +complete example. + +Plugin languages join the IDE's language registry like built-in ones: file +detection (`extensions`, `filenames`, `first-line`), comments, indentation, +`ui-mode`, `framework-ui-modes`, and the `language-servers` and `debugger` +they declare (each needs its `process:` grant). A plugin cannot replace a +built-in or user definition: their ids, extensions and file names win (users +can still map files to a plugin language in Settings › File Types). In a +remote project the definitions are sent to the server, which starts the +servers there. + +`[[framework-ui-modes]]` entries (`ui-mode`, `root-markers`) replace `ui-mode` for the files of a framework's projects: the first whose root marker is in a directory above the file, up to the project folder, applies (see [`languages/html.toml`](../languages/html.toml), Angular templates). Markers are matched like a language server's `root-markers`. -## 5. Installing and developing +### 6.1 Syntax for languages without a grammar -- **Install:** Settings › Plugins › _Install Plugin from Disk…_ (or the action - _Install Plugin from Disk…_) and pick the package folder. The manifest and the - files it references are copied to `<app-data>/plugins/<id>/`. -- **Dev plugins:** put (or symlink) the package in `<project>/.openidea/plugins/<name>/`. - It loads when the project is opened, is listed with a _dev_ tag, and _Reload_ - (or the _Reload Plugins_ action) picks up a rebuilt `plugin.wasm` without - restarting the IDE. +The IDE parses its built-in languages with tree-sitter. For a plugin language +it has no grammar for, the plugin's component can export `syntax-provider` +(world `plugin-syntax`): flat highlight tokens, structure-view symbols and +folds for a whole document, in UTF-8 byte offsets. With the SDK: + +```rust +use openidea_plugin::syntax::{Fold, Highlight, Symbol, SyntaxProvider, Token}; + +impl SyntaxProvider for MyPlugin { + fn highlights(&mut self, language: &str, text: &str) -> Vec<Token> { … } + fn outline(&mut self, language: &str, text: &str) -> Vec<Symbol> { … } // optional + fn folding(&mut self, language: &str, text: &str) -> Vec<Fold> { … } // optional +} + +register_plugin!(MyPlugin, syntax); +``` + +It runs on the editing path (once per document version, cached), so keep it +fast — a hand-written lexer is typical (`syntax::bracket_folds` helps with +folding). Add `activation = ["on-language:<id>"]` so the component loads with +the first file. Results are validated (clamped to the text, overlaps dropped). + +### 6.2 Run configurations + +```toml +[[contributes.runDetectors]] +id = "forge-test" +name = "forge test" +files = ["foundry.toml"] # offered in projects with any of these at the root +command = "forge" # one program; needs process:forge +args = ["test"] +test = true # results go to the test tree +``` + +The configuration appears among the detected ones while `process:<command>` is +granted, and starts the approved program. + +## 7. Installing and developing + +- **Install:** Settings › Plugins › _Install Plugin from Disk…_ (a package + folder) or _Install Plugin from Package File…_ (a `.oiplugin`, a `.zip` with + the package at its root or in its only folder, or a folder's `plugin.toml`; + a zip without a `plugin.toml` there, such as an IntelliJ plugin, is refused). The install + page lists every capability and whether the package is signed by a publisher + the marketplace trusts; nothing is copied until you accept. +- **Versions:** installed plugins live in `<app-data>/plugins/<id>/<version>/` + with an `active` pointer that is switched only once the new version is in + place. An update whose code fails to start the first time is rolled back to + the version it replaced automatically (you're told why); _Roll Back to …_ + in the plugin's details does it by hand. Data (`storage`) is per plugin, not + per version. +- **Linked plugins:** `openidea-plugin link <dir>` (§1). Listed with a _linked_ + tag; capabilities are granted per folder. +- **Project plugins:** put (or symlink) the package in + `<project>/.openidea/plugins/<name>/`. They load only in trusted projects and + only after you approve their capabilities. - Commands appear in Search Everywhere › Actions under their category, and can be bound in Settings › Keymap like any other action. -## 6. Testing +## 8. Distribution -The host's integration tests (`crates/ide-plugin/tests/host.rs`) load the -checked-in `hello` and test-fixture components; rebuild them after changing the -WIT file: +A **package** is a zip named `<id>-<version>.oiplugin`: the manifest, the +files it references, the component, licence files and, when signed, +`SIGNATURE.json` (Ed25519 over the plugin id, version and the digest of its +files). ```sh -plugins/build.sh hello -plugins/build.sh crates/ide-plugin/tests/fixtures/misbehave -cargo test -p ide-plugin +openidea-plugin keygen acme.key # once; keep the file secret +openidea-plugin pack plugins/acme-tools --key acme.key --publisher acme +openidea-plugin index market/ --publisher acme --name "ACME" --key acme.key ``` + +A **marketplace** is static: an `index.json` and the packages next to it, on +any web server or folder. It lists publishers and their public keys (the trust +root: publisher `acme` owns plugin ids `acme.*`), the plugins with their +digests, and revocations. Settings › Plugins › Available reads it from the URL +you set; installing downloads the package, checks it against the index entry +and the publisher's key, then shows the install page. + +- A package whose signature doesn't hold (changed after signing, a key that + isn't the publisher's, another publisher's id prefix, a revoked key) is + refused. Unsigned packages install from disk with a warning. +- **Revocation:** the index can revoke plugin versions (or all versions) and + publisher keys. The IDE reads the index daily; revoked plugins are disabled + with the reason and the user is notified — also after a restart, before + their code could run. A publisher rotates keys by adding the new one; older + keys stay valid until revoked. + +## 9. Testing the host + +The host's integration tests (`crates/ide-host/tests/plugins.rs`) load the +checked-in components of the official plugins and of the test fixtures +(`crates/ide-plugin/tests/fixtures/`). +Rebuild them after changing a plugin, the SDK or the WIT files: + +```sh +plugins/build.sh # all of them +plugins/build.sh official/solidity # one +plugins/build.sh --check # what CI runs: nothing stale, everything builds +cargo test -p ide-host --test plugins +``` + +Next to each `dist/plugin.wasm`, `dist/plugin.wasm.sources` fingerprints the +sources it was built from (the plugin, the SDK and `wit/`); builds are not +byte-reproducible across machines, so `--check` compares fingerprints. + +The SDK carries a copy of `wit/` in `sdk/rust/openidea-plugin/wit`; keep them +identical (a test in `crates/ide-plugin/tests/api_compat.rs` checks). Changing +the API itself follows _Evolving the plugin API_ below. + +## 10. Evolving the plugin API + +While the plugin system is a preview the API may still change freely. Once it +is declared stable wasmtime decides what stays compatible: it resolves interface names +by semver (a component importing `openidea:plugin/x@1.0.0` links against a +host defining `@1.1.0`, and the host finds its exports the same way), but +function types must match exactly — a record with another field count, or a +variant or enum with another case count, doesn't link. So a released 1.x +only grows: + +1. **Released types and signatures never change**, whichever way the data + flows: no new record fields, variant or enum cases, renames or parameters. + Extend with new types and new functions (or interfaces). `types.error` is + used everywhere and is no exception; new situations use `failed(string)` + or `invalid(string)`. Sets that keep growing (completion, token, symbol and + fold kinds, icons) are strings for this reason. +2. **Host interfaces (imports) may gain functions and interfaces**: older + components don't import them. +3. **Plugin interfaces (exports) never gain functions** once released: the + host would not find them in older components. New capabilities get new + interfaces (e.g. a `hover-provider`) in new optional worlds. +4. **The host knows each component's API version** (the highest version of + its `openidea:plugin/*` imports and exports, `PluginEngine::check_component`). + Installing and `openidea-plugin check` refuse another major or a newer + minor with a message that says to update the IDE or rebuild with the SDK. +5. **One version number**: the `wit/` package version, `ENGINE_VERSION` and + `API_VERSION` agree, and the SDK's `wit/` copy is identical to `wit/`. + +Checked automatically: + +- SDK `tests/api_frozen.rs`: `tests/api/<version>/` holds the WIT of each + released version; every interface, type, function and world import or + export in it must still exist unchanged in `wit/` (rules 1–3). Copy `wit/` + there when releasing; there is no snapshot before the first release. +- `crates/ide-plugin/tests/api_compat.rs`: the versions agree, the SDK's copy + matches, the version check (rules 4, 5); a simulated next-minor host (every + import stubbed at the newer version, plus extra functions and an extra + interface) links every shipped component and finds its exports; another + major doesn't link; a host missing one function doesn't link. + +A new host function touches: + +| Where | Checked by | +| --------------------------------------------------------- | ---------------------------------------------- | +| `wit/*.wit`, copied to `sdk/rust/openidea-plugin/wit` | `api_compat.rs::the_sdk_carries_the_hosts_wit` | +| `crates/ide-plugin/src/wit_host.rs`: binding, capability | the compiler (bindgen's traits) | +| `crates/ide-plugin/src/runtime.rs`: `HostApi` method | the compiler | +| `crates/ide-host/src/plugins/api.rs`: implementation | the compiler (desktop and `openidea-server`) | +| SDK `src/host.rs`: the wasm and the mock `imp` | the compiler (CI builds both targets) | +| SDK public wrapper | SDK `tests/wit_coverage.rs` | +| Capability: `ide-extension/src/capability.rs`, consent UI | review; a test that a missing grant is denied | +| The API table above | review | + +Then run `plugins/build.sh`; CI's `plugins` job runs `plugins/build.sh --check` +plus fmt, clippy (host and wasm) and the tests of the SDK, the official +plugins and the fixtures. diff --git a/plugins/build.sh b/plugins/build.sh index 2b30f45c..c8aeb382 100755 --- a/plugins/build.sh +++ b/plugins/build.sh @@ -1,30 +1,139 @@ #!/usr/bin/env bash -# Builds Rust plugins into WebAssembly components (wasm32-wasip2 emits a -# component directly; no cargo-component / wasm-tools needed). +# Builds the repository's plugins: Rust code into WebAssembly components +# (wasm32-wasip2 emits a component directly; no cargo-component / wasm-tools), +# and web pages (`web-src/`, a Vite project) into `web/`. # -# plugins/build.sh # all plugins with a Cargo.toml -# plugins/build.sh hello # one plugin +# plugins/build.sh # every plugin with code or a web page +# plugins/build.sh official/csv-editor # one plugin (a path under plugins/, or any path) +# plugins/build.sh --check [...] # change nothing tracked; fail if a checked-in +# # component is stale or a plugin doesn't build (CI) # -# Output: <plugin>/dist/plugin.wasm (referenced by `wasm = ...` in plugin.toml). +# Output: <plugin>/dist/plugin.wasm (referenced by `wasm = ...` in plugin.toml) +# and <plugin>/dist/plugin.wasm.sources, a fingerprint of the sources it was +# built from: the plugin (minus target/, dist/, web/ and web-src/), the SDK +# and wit/. Components are small and checked in; builds are not +# byte-reproducible across machines, so --check compares fingerprints, not +# bytes. A web page (web-src/, a pnpm project) is built into <plugin>/web/, +# which is not checked in (it can be tens of MB): build it before installing +# the plugin from the repository. web.sources (not checked in either) skips +# rebuilding an unchanged page; --check builds it too and checks the result. +# CARGO_TARGET_DIR, when set, is shared by all plugins. set -euo pipefail here="$(cd "$(dirname "$0")" && pwd)" +repo="$(cd "$here/.." && pwd)" rustup target list --installed | grep -qx wasm32-wasip2 || rustup target add wasm32-wasip2 +check=0 +if [ "${1:-}" = "--check" ]; then + check=1 + shift +fi + +sha256() { if command -v sha256sum >/dev/null; then sha256sum; else shasum -a 256; fi; } + +# Lists "<path> <sha256>" for the files git sees (tracked, or new and not +# ignored) under the given paths of directory $1, minus build output and Finder +# metadata; so a +# checkout fingerprints the same as the working tree that committed it. +list() { + local dir="$1" + shift + (cd "$dir" && git ls-files --cached --others --exclude-standard -- "$@") | + { grep -Ev '(^|/)(dist|target|node_modules)/|(^|/)\.DS_Store$|^web(-src)?/|^web\.sources$' || true; } | LC_ALL=C sort -u | while read -r f; do + if [ -f "$dir/$f" ]; then printf '%s %s\n' "$f" "$(sha256 <"$dir/$f" | cut -d' ' -f1)"; fi + done +} + +# Prints the fingerprint of everything plugin $1's component is built from. +fingerprint() { + { list "$1" .; list "$repo" sdk/rust/openidea-plugin/Cargo.toml sdk/rust/openidea-plugin/src sdk/rust/openidea-plugin/wit wit; } | + sha256 | cut -d' ' -f1 +} + +# Prints the fingerprint of plugin $1's web page sources. +web_fingerprint() { + (cd "$1/web-src" && git ls-files --cached --others --exclude-standard -- .) | + { grep -Ev '(^|/)node_modules/|(^|/)\.DS_Store$' || true; } | LC_ALL=C sort -u | while read -r f; do + if [ -f "$1/web-src/$f" ]; then printf '%s %s\n' "$f" "$(sha256 <"$1/web-src/$f" | cut -d' ' -f1)"; fi + done | sha256 | cut -d' ' -f1 +} + +# Builds plugin $1's web page into web/ unless it was built from the current +# web-src/, then checks what the manifest's `web = "…"` entries need: each +# page is there and loads its files by relative URL (it is served from the package). +build_web() { + local dir="$1" rel="${1#"$repo"/}" want entry + want="$(web_fingerprint "$dir")" + if [ "$want" != "$(cat "$dir/web.sources" 2>/dev/null || true)" ] || [ ! -d "$dir/web" ]; then + echo "building the web page of $rel" + if ! { pnpm --dir "$dir/web-src" install --frozen-lockfile --ignore-workspace --silent && + pnpm --dir "$dir/web-src" run build; }; then + echo "FAIL $rel: the web page does not build" + failed=1 + return + fi + echo "$want" >"$dir/web.sources" + fi + for entry in $(sed -n 's/^web *= *"\(.*\)".*/\1/p' "$dir/plugin.toml" | sort -u); do + if [ ! -f "$dir/$entry" ]; then + echo "FAIL $rel: $entry was not built" + failed=1 + elif grep -Eq '(src|href)="/' "$dir/$entry"; then + echo "FAIL $rel: $entry loads files by absolute URL; build it with relative paths (Vite: base: \"./\")" + failed=1 + fi + done + echo "ok $rel (web, $(du -sh "$dir/web" | cut -f1))" +} + +failed=0 build() { local dir="$1" - local name + if [ -f "$dir/web-src/package.json" ]; then build_web "$dir"; fi + [ -f "$dir/Cargo.toml" ] || return 0 + local name target out name="$(sed -n 's/^name *= *"\(.*\)"/\1/p' "$dir/Cargo.toml" | head -1)" - echo "building $name ($dir)" - CARGO_TARGET_DIR="$dir/target" cargo build --manifest-path "$dir/Cargo.toml" --release --target wasm32-wasip2 + target="${CARGO_TARGET_DIR:-$dir/target}" + out="$target/wasm32-wasip2/release/${name//-/_}.wasm" + local rel="${dir#"$repo"/}" + if [ "$check" = 1 ]; then + if ! CARGO_TARGET_DIR="$target" cargo build -q --locked --manifest-path "$dir/Cargo.toml" --release --target wasm32-wasip2; then + echo "FAIL $rel: does not build" + failed=1 + return + fi + local want have + want="$(fingerprint "$dir")" + have="$(cat "$dir/dist/plugin.wasm.sources" 2>/dev/null || true)" + if [ "$want" != "$have" ]; then + echo "STALE $rel: dist/plugin.wasm was not built from the current sources; run plugins/build.sh $rel" + failed=1 + else + echo "ok $rel" + fi + return + fi + echo "building $name ($rel)" + CARGO_TARGET_DIR="$target" cargo build --manifest-path "$dir/Cargo.toml" --release --target wasm32-wasip2 mkdir -p "$dir/dist" - cp "$dir/target/wasm32-wasip2/release/${name//-/_}.wasm" "$dir/dist/plugin.wasm" - echo " -> $dir/dist/plugin.wasm ($(wc -c < "$dir/dist/plugin.wasm" | tr -d " ") bytes)" + cp "$out" "$dir/dist/plugin.wasm" + fingerprint "$dir" >"$dir/dist/plugin.wasm.sources" + echo " -> $rel/dist/plugin.wasm ($(wc -c <"$dir/dist/plugin.wasm" | tr -d " ") bytes)" } if [ $# -gt 0 ]; then for p in "$@"; do - case "$p" in /*) build "$p" ;; *) build "$here/$p" ;; esac + if [ -d "$here/$p" ]; then build "$here/$p" + elif [ -d "$repo/$p" ]; then build "$(cd "$repo/$p" && pwd)" + elif [ -d "$p" ]; then build "$(cd "$p" && pwd)" + else echo "no plugin at $p" >&2; exit 2 + fi done else - for manifest in "$here"/*/Cargo.toml; do build "$(dirname "$manifest")"; done + # Every component (plugin.toml + Cargo.toml) and web page (plugin.toml + web-src/). + for manifest in "$here"/official/*/plugin.toml "$repo"/crates/ide-plugin/tests/fixtures/*/plugin.toml; do + dir="$(dirname "$manifest")" + if [ -f "$dir/Cargo.toml" ] || [ -f "$dir/web-src/package.json" ]; then build "$dir"; fi + done fi +exit "$failed" diff --git a/plugins/hello/dist/plugin.wasm b/plugins/hello/dist/plugin.wasm deleted file mode 100644 index 3cc43a85..00000000 Binary files a/plugins/hello/dist/plugin.wasm and /dev/null differ diff --git a/plugins/hello/plugin.toml b/plugins/hello/plugin.toml deleted file mode 100644 index 458abb4b..00000000 --- a/plugins/hello/plugin.toml +++ /dev/null @@ -1,23 +0,0 @@ -id = "hello" -name = "Hello" -version = "0.1.0" -description = "Sample plugin: inserts today's date and counts words in the active file." -authors = ["OpenIDEA contributors"] -change-notes = """ -0.1.0 — first release: Insert Date and Word Count of Active File commands. -""" -openidea-api = "0.1" -wasm = "dist/plugin.wasm" -permissions = ["project-read", "editor-read", "editor-write"] - -# Static declarations make the commands visible before the plugin activates; -# the plugin may also register more at runtime via `register-command`. -[[contributes.commands]] -id = "insert-date" -title = "Hello: Insert Date" -category = "Hello" - -[[contributes.commands]] -id = "word-count" -title = "Hello: Word Count of Active File" -category = "Hello" diff --git a/plugins/hello/src/lib.rs b/plugins/hello/src/lib.rs deleted file mode 100644 index e1009fd7..00000000 --- a/plugins/hello/src/lib.rs +++ /dev/null @@ -1,70 +0,0 @@ -//! Sample OpenIDEA plugin. Build with `../build.sh hello` (see plugins/README.md). - -wit_bindgen::generate!({ - world: "plugin", - path: "../../wit", -}); - -use openidea::plugin::host::{self, LogLevel, NotificationLevel}; - -struct Hello; - -impl Guest for Hello { - fn activate(ctx: Context) -> Result<(), String> { - host::log(LogLevel::Info, &format!("hello {} activated", ctx.plugin_version)); - host::register_command("insert-date", "Hello: Insert Date", Some("Hello")); - host::register_command("word-count", "Hello: Word Count of Active File", Some("Hello")); - Ok(()) - } - - fn deactivate() { - host::log(LogLevel::Info, "hello deactivated"); - } - - fn run_command(id: String, _arg: Option<String>) -> Result<Option<String>, String> { - match id.as_str() { - "insert-date" => { - let date = today(); - host::insert_text(&date); - Ok(Some(date)) - } - "word-count" => { - let path = host::active_file().ok_or("no file is open in the editor")?; - let text = host::read_file(&path)?; - let words = text.split_whitespace().count(); - let lines = text.lines().count(); - let name = path.rsplit(['/', '\\']).next().unwrap_or(&path); - let body = format!("{words} words, {lines} lines, {} characters", text.chars().count()); - host::show_notification(NotificationLevel::Info, &format!("Word count: {name}"), &body); - Ok(Some(body)) - } - other => Err(format!("unknown command: {other}")), - } - } -} - -/// Today's UTC date as `YYYY-MM-DD` (WASI wall clock). -fn today() -> String { - let secs = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs() as i64) - .unwrap_or(0); - let (y, m, d) = civil_from_days(secs.div_euclid(86_400)); - format!("{y:04}-{m:02}-{d:02}") -} - -/// Howard Hinnant's days-to-civil algorithm. -fn civil_from_days(z: i64) -> (i64, u32, u32) { - let z = z + 719_468; - let era = z.div_euclid(146_097); - let doe = z.rem_euclid(146_097); - let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = (doy - (153 * mp + 2) / 5 + 1) as u32; - let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; - let y = yoe + era * 400 + i64::from(m <= 2); - (y, m, d) -} - -export!(Hello); diff --git a/plugins/official/ai-completion/.gitignore b/plugins/official/ai-completion/.gitignore new file mode 100644 index 00000000..ea8c4bf7 --- /dev/null +++ b/plugins/official/ai-completion/.gitignore @@ -0,0 +1 @@ +/target diff --git a/plugins/official/ai-completion/Cargo.lock b/plugins/official/ai-completion/Cargo.lock new file mode 100644 index 00000000..e7bc7ab9 --- /dev/null +++ b/plugins/official/ai-completion/Cargo.lock @@ -0,0 +1,334 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "openidea-plugin-openidea-ai-completion" +version = "0.1.0" +dependencies = [ + "openidea-plugin", + "serde_json", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[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 = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +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 = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/plugins/official/ai-completion/Cargo.toml b/plugins/official/ai-completion/Cargo.toml new file mode 100644 index 00000000..255622aa --- /dev/null +++ b/plugins/official/ai-completion/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "openidea-plugin-openidea-ai-completion" +version = "0.1.0" +edition = "2024" +publish = false + +# A plugin builds on its own (target wasm32-wasip2), outside any IDE workspace. +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../sdk/rust/openidea-plugin" } +serde_json = "1" + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/plugins/official/ai-completion/dist/plugin.wasm b/plugins/official/ai-completion/dist/plugin.wasm new file mode 100644 index 00000000..ee11a42e Binary files /dev/null and b/plugins/official/ai-completion/dist/plugin.wasm differ diff --git a/plugins/official/ai-completion/dist/plugin.wasm.sources b/plugins/official/ai-completion/dist/plugin.wasm.sources new file mode 100644 index 00000000..43ce4cdf --- /dev/null +++ b/plugins/official/ai-completion/dist/plugin.wasm.sources @@ -0,0 +1 @@ +bf264a97dc918f24ac00f0e9e0d0373b68391a96921b44345b466c2a087c5283 diff --git a/plugins/official/ai-completion/plugin.toml b/plugins/official/ai-completion/plugin.toml new file mode 100644 index 00000000..8cf1c563 --- /dev/null +++ b/plugins/official/ai-completion/plugin.toml @@ -0,0 +1,44 @@ +id = "openidea.ai-completion" +name = "AI Completion" +version = "0.1.0" +description = "Inline code suggestions (ghost text) from a local model (Ollama) or OpenAI, as you type." +authors = ["OpenIDEA contributors"] +license = "Apache-2.0" +change-notes = "0.1.0 — first release: local (Ollama) and OpenAI backends; the key stays in the system keychain." +engines.openidea = "^1.0" +wasm = "dist/plugin.wasm" +activation = ["on-command:*"] + +[capabilities] +required = ["storage"] +# Grant the backends you use; the key is only ever sent to api.openai.com. +optional = ["net:localhost", "net:api.openai.com", "secrets"] + +[[contributes.providers]] +kinds = ["inline-completion"] +languages = ["*"] + +[[contributes.secrets]] +name = "api-key" +label = "OpenAI API key" +description = "Used only with the OpenAI backend." + +[[contributes.commands]] +id = "use-local" +title = "AI Completion: Use Local Model (Ollama)" +category = "AI Completion" + +[[contributes.commands]] +id = "use-openai" +title = "AI Completion: Use OpenAI" +category = "AI Completion" + +[[contributes.commands]] +id = "toggle" +title = "AI Completion: Enable / Disable" +category = "AI Completion" + +[[contributes.commands]] +id = "set-endpoint" +title = "AI Completion: Set Endpoint URL" +category = "AI Completion" diff --git a/plugins/official/ai-completion/src/lib.rs b/plugins/official/ai-completion/src/lib.rs new file mode 100644 index 00000000..c07d60f6 --- /dev/null +++ b/plugins/official/ai-completion/src/lib.rs @@ -0,0 +1,214 @@ +//! AI Completion for OpenIDEA: inline suggestions from an OpenAI-compatible +//! `/v1/completions` endpoint (fill-in-the-middle with `prompt` + `suffix`). +//! The IDE cancels a request as soon as the user types on (the fetch returns +//! `Cancelled`); the API key is filled in by the IDE (`{{secret:api-key}}`) +//! and never seen here. + +use openidea_plugin::host::{self, storage}; +use openidea_plugin::providers::{Document, InlineSuggestion, Providers}; +use openidea_plugin::text::offset; +use openidea_plugin::{Error, HttpRequest, Invocation, LogLevel, NotificationLevel, Plugin, Position, register_plugin}; +use serde_json::{Value, json}; + +const LOCAL: &str = "http://localhost:11434"; +const OPENAI: &str = "https://api.openai.com"; +const LOCAL_MODEL: &str = "qwen2.5-coder:1.5b"; +const OPENAI_MODEL: &str = "gpt-3.5-turbo-instruct"; +/// Context sent around the caret. +const PREFIX_CHARS: usize = 3000; +const SUFFIX_CHARS: usize = 1000; + +#[derive(Default)] +pub struct AiCompletion { + /// Why the last request failed, so it is logged once rather than per keystroke. + last_error: Option<String>, +} + +struct Config { + endpoint: String, + model: String, + openai: bool, + enabled: bool, +} + +fn config() -> Config { + let get = |k: &str| storage::get(k).ok().flatten(); + let endpoint = get("endpoint").unwrap_or_else(|| LOCAL.into()); + let openai = endpoint.starts_with(OPENAI); + let model = get("model").unwrap_or_else(|| (if openai { OPENAI_MODEL } else { LOCAL_MODEL }).into()); + Config { endpoint, model, openai, enabled: get("enabled").as_deref() != Some("false") } +} + +/// The last `max` characters of `s` (on a char boundary). +fn tail(s: &str, max: usize) -> &str { + match s.char_indices().rev().nth(max.saturating_sub(1)) { + Some((i, _)) if s.chars().count() > max => &s[i..], + _ => s, + } +} + +fn head(s: &str, max: usize) -> &str { + s.char_indices().nth(max).map_or(s, |(i, _)| &s[..i]) +} + +/// The request body for the text around `at`, or `None` when there is +/// nothing to complete (in the middle of a word). +pub fn request_body(doc: &Document, at: Position, model: &str) -> Option<String> { + let at = offset(&doc.text, at)?; + let (before, after) = doc.text.split_at(at); + // Only at the end of a line or before closing punctuation. + let rest_of_line = after.split('\n').next().unwrap_or(""); + if !rest_of_line.trim().chars().all(|c| ")]}>;,'\"`".contains(c)) { + return None; + } + let body = json!({ + "model": model, + "prompt": tail(before, PREFIX_CHARS), + "suffix": head(after, SUFFIX_CHARS), + "max_tokens": 64, + "temperature": 0, + "stop": ["\n\n"], + }); + Some(body.to_string()) +} + +/// The suggestion in a `/v1/completions` response. +pub fn suggestion(response: &str) -> Option<String> { + let v: Value = serde_json::from_str(response).ok()?; + let text = v["choices"][0]["text"].as_str()?.trim_end().to_owned(); + (!text.trim().is_empty()).then_some(text) +} + +impl Providers for AiCompletion { + fn inline_completion(&mut self, doc: &Document, at: Position) -> Option<InlineSuggestion> { + let c = config(); + if !c.enabled { + return None; + } + let body = request_body(doc, at, &c.model)?; + let mut req = HttpRequest::post(&format!("{}/v1/completions", c.endpoint.trim_end_matches('/')), body) + .header("Content-Type", "application/json"); + if c.openai { + if !host::secret_is_set("api-key") { + return None; + } + req = req.header("Authorization", "Bearer {{secret:api-key}}"); + } + req.timeout_ms = Some(10_000); + match host::fetch(&req) { + Ok(r) if r.status == 200 => { + self.last_error = None; + suggestion(&r.text()).map(|insert_text| InlineSuggestion { insert_text, replace: None }) + } + // Superseded by the next keystroke: nothing to report. + Err(Error::Cancelled) => None, + other => { + let msg = match other { + Ok(r) => format!("HTTP {}: {}", r.status, head(&r.text(), 200)), + Err(e) => e.to_string(), + }; + if self.last_error.as_ref() != Some(&msg) { + host::log(LogLevel::Warn, &format!("{}: {msg}", c.endpoint)); + self.last_error = Some(msg); + } + None + } + } + } +} + +impl Plugin for AiCompletion { + fn run_command(&mut self, id: &str, _ctx: &Invocation, arg: Option<&str>) -> Result<Option<String>, Error> { + let msg = match id { + "use-local" => { + storage::set("endpoint", LOCAL)?; + storage::delete("model")?; + format!("Using the local model {LOCAL_MODEL} (Ollama at {LOCAL}).") + } + "use-openai" => { + storage::set("endpoint", OPENAI)?; + storage::delete("model")?; + if host::secret_is_set("api-key") { + format!("Using OpenAI ({OPENAI_MODEL}).") + } else { + "Using OpenAI: store your API key in Settings › Plugins › AI Completion.".into() + } + } + "set-endpoint" => { + let url = arg.map(str::trim).filter(|u| u.starts_with("http://") || u.starts_with("https://")); + let url = url.ok_or("give the endpoint URL, e.g. http://localhost:11434")?; + storage::set("endpoint", url)?; + format!("Using {url}.") + } + "toggle" => { + let enabled = !config().enabled; + storage::set("enabled", if enabled { "true" } else { "false" })?; + (if enabled { "AI Completion is on." } else { "AI Completion is off." }).into() + } + _ => return Err(Error::NotFound(format!("command {id}"))), + }; + host::notify(NotificationLevel::Info, "AI Completion", &msg); + Ok(Some(msg)) + } +} + +register_plugin!(AiCompletion, providers); + +#[cfg(test)] +mod tests { + use super::*; + use openidea_plugin::HttpResponse; + use openidea_plugin::mock::MockHost; + + fn doc(text: &str) -> Document { + Document { path: "/p/a.rs".into(), language: "rust".into(), version: 1, text: text.into() } + } + + #[test] + fn asks_with_prefix_and_suffix_and_returns_the_text() { + let host = MockHost::install().with_capabilities(&["storage", "net:localhost"]); + host.on_fetch(|r| { + let body: Value = serde_json::from_slice(r.body.as_ref().unwrap()).unwrap(); + assert_eq!(body["prompt"], "fn add(a: i32, b: i32) -> i32 {\n "); + assert_eq!(body["suffix"], "\n}\n"); + Ok(HttpResponse { status: 200, headers: vec![], body: br#"{"choices":[{"text":"a + b\n"}]}"#.to_vec() }) + }); + let s = AiCompletion::default() + .inline_completion(&doc("fn add(a: i32, b: i32) -> i32 {\n \n}\n"), Position::new(1, 4)) + .unwrap(); + assert_eq!(s.insert_text, "a + b"); + assert_eq!(host.requests()[0].url, "http://localhost:11434/v1/completions"); + } + + #[test] + fn openai_uses_the_secret_and_only_when_set() { + let host = MockHost::install().with_capabilities(&["storage", "net:api.openai.com", "secrets"]); + host.on_fetch(|_| { + Ok(HttpResponse { status: 200, headers: vec![], body: br#"{"choices":[{"text":"x"}]}"#.to_vec() }) + }); + let mut p = AiCompletion::default(); + p.run_command("use-openai", &host.invocation(), None).unwrap(); + assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none(), "no key yet"); + host.set_secret("api-key", "sk-test"); + assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_some()); + let sent = &host.requests()[0]; + assert!(sent.headers.contains(&("Authorization".into(), "Bearer sk-test".into()))); + } + + #[test] + fn quiet_when_cancelled_denied_or_mid_word() { + let host = MockHost::install().with_capabilities(&["storage"]); + let mut p = AiCompletion::default(); + assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none(), "net denied"); + assert!(request_body(&doc("let abc = d;"), Position::new(0, 5), "m").is_none(), "mid-word"); + assert!(request_body(&doc("call(x)"), Position::new(0, 6), "m").is_some(), "before `)`"); + let host2 = MockHost::install().with_capabilities(&["storage", "net:localhost"]); + host2.on_fetch(|_| Err(Error::Cancelled)); + assert!(p.inline_completion(&doc("x"), Position::new(0, 1)).is_none()); + assert!(host2.logs().is_empty(), "a cancelled request is not an error"); + drop(host); + p.run_command("toggle", &host2.invocation(), None).unwrap(); + assert!(p.inline_completion(&doc("x"), Position::new(0, 1)).is_none()); + assert_eq!(host2.requests().len(), 1, "disabled: no request"); + } +} diff --git a/plugins/official/checkstyle/.gitignore b/plugins/official/checkstyle/.gitignore new file mode 100644 index 00000000..ea8c4bf7 --- /dev/null +++ b/plugins/official/checkstyle/.gitignore @@ -0,0 +1 @@ +/target diff --git a/plugins/official/checkstyle/Cargo.lock b/plugins/official/checkstyle/Cargo.lock new file mode 100644 index 00000000..5c3d4f38 --- /dev/null +++ b/plugins/official/checkstyle/Cargo.lock @@ -0,0 +1,333 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "openidea-plugin-openidea-checkstyle" +version = "0.1.0" +dependencies = [ + "openidea-plugin", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[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 = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +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 = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/plugins/official/checkstyle/Cargo.toml b/plugins/official/checkstyle/Cargo.toml new file mode 100644 index 00000000..2a04ad51 --- /dev/null +++ b/plugins/official/checkstyle/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "openidea-plugin-openidea-checkstyle" +version = "0.1.0" +edition = "2024" +publish = false + +# A plugin builds on its own (target wasm32-wasip2), outside any IDE workspace. +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../sdk/rust/openidea-plugin" } + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/plugins/official/checkstyle/dist/plugin.wasm b/plugins/official/checkstyle/dist/plugin.wasm new file mode 100644 index 00000000..b7508504 Binary files /dev/null and b/plugins/official/checkstyle/dist/plugin.wasm differ diff --git a/plugins/official/checkstyle/dist/plugin.wasm.sources b/plugins/official/checkstyle/dist/plugin.wasm.sources new file mode 100644 index 00000000..6192fb92 --- /dev/null +++ b/plugins/official/checkstyle/dist/plugin.wasm.sources @@ -0,0 +1 @@ +6095c7e30658b93d79270e6355d42941a4cfe13eeb8bada07acc7ae462194853 diff --git a/plugins/official/checkstyle/plugin.toml b/plugins/official/checkstyle/plugin.toml new file mode 100644 index 00000000..444157b6 --- /dev/null +++ b/plugins/official/checkstyle/plugin.toml @@ -0,0 +1,33 @@ +id = "openidea.checkstyle" +name = "Checkstyle" +version = "0.1.0" +description = "Checks Java files with Checkstyle when you save them: problems in the editor and the Problems view, quick fixes for tabs, trailing spaces and missing final newlines." +authors = ["OpenIDEA contributors"] +license = "Apache-2.0" +change-notes = "0.1.0 — first release: check on save (a newer save cancels the running check), Google style by default, quick fixes." +engines.openidea = "^1.0" +wasm = "dist/plugin.wasm" +activation = ["on-event:file-saved", "on-command:*"] + +[capabilities] +# `process:checkstyle`: the `checkstyle` command line (e.g. `brew install checkstyle`). +required = ["project.read", "events", "storage", "process:checkstyle"] + +[[contributes.providers]] +kinds = ["code-actions"] +languages = ["java"] + +[[contributes.commands]] +id = "check" +title = "Checkstyle: Check Current File" +category = "Checkstyle" + +[[contributes.commands]] +id = "use-sun" +title = "Checkstyle: Use Sun Checks" +category = "Checkstyle" + +[[contributes.commands]] +id = "use-google" +title = "Checkstyle: Use Google Checks" +category = "Checkstyle" diff --git a/plugins/official/checkstyle/src/lib.rs b/plugins/official/checkstyle/src/lib.rs new file mode 100644 index 00000000..74f17cc4 --- /dev/null +++ b/plugins/official/checkstyle/src/lib.rs @@ -0,0 +1,317 @@ +//! Checkstyle for OpenIDEA: runs the `checkstyle` command line on a Java file +//! when it is saved (as a cancellable task; a newer save cancels the running +//! check), publishes the problems as diagnostics, and offers quick fixes for +//! the ones it can fix textually. +//! +//! The configuration is the project's own when it has one (`checkstyle.xml`, +//! `config/checkstyle/checkstyle.xml` as Gradle and Maven projects keep it, +//! or `.checkstyle.xml`), else the Google or Sun checks chosen with the +//! commands. + +use openidea_plugin::host::{self, storage}; +use openidea_plugin::providers::{CodeAction, Document, Providers}; +use openidea_plugin::{ + Diagnostic, Error, Event, Invocation, NotificationLevel, Plugin, Position, Project, Range, Severity, TextEdit, + register_plugin, +}; +use std::collections::BTreeMap; + +/// Built into the Checkstyle jar. +const GOOGLE: &str = "/google_checks.xml"; +const SUN: &str = "/sun_checks.xml"; +/// Project configurations, by preference (project-relative; the check runs in the project root). +const PROJECT_CONFIGS: [&str; 3] = ["checkstyle.xml", "config/checkstyle/checkstyle.xml", ".checkstyle.xml"]; + +/// One reported problem. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Problem { + /// 0-based. + pub line: u32, + /// 0-based; `None` for the whole line. + pub column: Option<u32>, + pub severity: Severity, + pub message: String, + /// The check's simple name (`FileTabCharacter`). + pub check: String, +} + +#[derive(Default)] +pub struct Checkstyle { + /// Last results per file (for quick fixes; rebuilt by the next save). + problems: BTreeMap<String, Vec<Problem>>, +} + +fn unescape(s: &str) -> String { + s.replace(""", "\"") + .replace("'", "'") + .replace("<", "<") + .replace(">", ">") + .replace(" ", "\n") + .replace("&", "&") +} + +fn attr(tag: &str, name: &str) -> Option<String> { + let start = tag.find(&format!(" {name}=\""))? + name.len() + 3; + let end = tag[start..].find('"')? + start; + Some(unescape(&tag[start..end])) +} + +/// Problems per file from Checkstyle's `-f xml` report. +pub fn parse_report(xml: &str) -> BTreeMap<String, Vec<Problem>> { + let mut out: BTreeMap<String, Vec<Problem>> = BTreeMap::new(); + let mut file = None; + for tag in xml.split('<').skip(1) { + let tag = format!(" {}", tag.split('>').next().unwrap_or("")); + if tag.starts_with(" file ") { + file = attr(&tag, "name"); + if let Some(f) = &file { + out.entry(f.clone()).or_default(); + } + } else if tag.starts_with(" error ") { + let (Some(f), Some(line)) = (&file, attr(&tag, "line").and_then(|l| l.parse::<u32>().ok())) else { + continue; + }; + let severity = match attr(&tag, "severity").as_deref() { + Some("error") => Severity::Error, + Some("info") => Severity::Info, + Some("ignore") => continue, + _ => Severity::Warning, + }; + let check = attr(&tag, "source").unwrap_or_default(); + // Checks configured with an `id` report it after a `#` (Google checks: `RegexpSinglelineCheck#noTrailingWhitespace`). + let check = check.split('#').next().unwrap_or_default(); + let check = check.rsplit('.').next().unwrap_or(check).trim_end_matches("Check").to_owned(); + out.entry(f.clone()).or_default().push(Problem { + line: line.saturating_sub(1), + column: attr(&tag, "column").and_then(|c| c.parse::<u32>().ok()).map(|c| c.saturating_sub(1)), + severity, + message: attr(&tag, "message").unwrap_or_default(), + check, + }); + } + } + out +} + +fn diagnostic(p: &Problem, text: &str) -> Diagnostic { + let line_len = text.split('\n').nth(p.line as usize).map_or(0, |l| l.encode_utf16().count() as u32); + let start = p.column.unwrap_or(0).min(line_len); + let end = if p.column.is_some() && start < line_len { start + 1 } else { line_len }; + Diagnostic { + range: Range::new(Position::new(p.line, start), Position::new(p.line, end.max(start))), + severity: p.severity, + message: p.message.clone(), + code: Some(p.check.clone()), + } +} + +/// The project containing `path`. +fn project_of(path: &str) -> Option<Project> { + host::projects() + .ok()? + .into_iter() + .filter(|p| p.root().is_ok_and(|r| path.starts_with(&r))) + .max_by_key(|p| p.root().map(|r| r.len()).unwrap_or(0)) +} + +/// The configuration for files of `project`. +fn config_for(project: &Project) -> String { + PROJECT_CONFIGS + .iter() + .find(|c| project.read_file(c).is_ok()) + .map(|c| (*c).to_owned()) + .or_else(|| storage::get("config").ok().flatten()) + .unwrap_or_else(|| GOOGLE.into()) +} + +impl Checkstyle { + /// Checks `path` and publishes the result. `Err(Cancelled)` when a newer + /// save (or the user) cancelled it. + fn check(&mut self, path: &str) -> Result<usize, Error> { + let project = project_of(path).ok_or_else(|| Error::NotFound(format!("{path} is not in an open project")))?; + let name = path.rsplit(['/', '\\']).next().unwrap_or(path); + let task = host::begin_task(&format!("Checkstyle: {name}"), true); + let config = config_for(&project); + let args = vec!["-f".to_owned(), "xml".into(), "-c".into(), config, path.to_owned()]; + let out = project.run_process("checkstyle", &args, None)?; + if task.is_cancelled() { + return Err(Error::Cancelled); + } + // Exit status is the number of errors; only missing output is a failure. + if !out.stdout.contains("<checkstyle") { + return Err(Error::Failed(format!("checkstyle: {}", out.stderr.lines().next().unwrap_or("no report")))); + } + let report = parse_report(&out.stdout); + let problems = report + .into_iter() + .find(|(f, _)| f == path || path.ends_with(f.as_str())) + .map(|(_, p)| p) + .unwrap_or_default(); + let text = project.read_file(path).unwrap_or_default(); + let diagnostics: Vec<Diagnostic> = problems.iter().map(|p| diagnostic(p, &text)).collect(); + host::publish_diagnostics(path, &diagnostics)?; + let n = problems.len(); + self.problems.insert(path.to_owned(), problems); + Ok(n) + } +} + +impl Providers for Checkstyle { + fn code_actions(&mut self, doc: &Document, selection: Range) -> Vec<CodeAction> { + let Some(problems) = self.problems.get(&doc.path) else { return Vec::new() }; + let lines: Vec<&str> = doc.text.split('\n').collect(); + let mut out = Vec::new(); + let mut seen = std::collections::BTreeSet::new(); + for p in problems.iter().filter(|p| p.line >= selection.start.line && p.line <= selection.end.line) { + let Some(line) = lines.get(p.line as usize) else { continue }; + let whole = Range::new(Position::new(p.line, 0), Position::new(p.line, line.encode_utf16().count() as u32)); + let (title, edit) = match p.check.as_str() { + "FileTabCharacter" => { + ("Replace tabs with spaces", TextEdit { range: whole, text: line.replace('\t', " ") }) + } + "RegexpSingleline" if p.message.to_lowercase().contains("trailing") => { + ("Remove trailing whitespace", TextEdit { range: whole, text: line.trim_end().to_owned() }) + } + "NewlineAtEndOfFile" => { + let last = lines.len() as u32 - 1; + let end = Position::new(last, lines[last as usize].encode_utf16().count() as u32); + ( + "Add a newline at the end of the file", + TextEdit { range: Range::new(end, end), text: "\n".into() }, + ) + } + _ => continue, + }; + if seen.insert((title, p.line)) { + out.push(CodeAction { + title: format!("Checkstyle: {title}"), + kind: Some("quickfix".into()), + preferred: true, + edits: vec![(doc.path.clone(), vec![edit])], + }); + } + } + out + } +} + +impl Plugin for Checkstyle { + fn run_command(&mut self, id: &str, ctx: &Invocation, _arg: Option<&str>) -> Result<Option<String>, Error> { + match id { + "check" => { + let editor = ctx.editor().ok_or("no file is open")?; + let n = self.check(&editor.path())?; + Ok(Some(format!("{n} problems"))) + } + "use-google" | "use-sun" => { + storage::set("config", if id == "use-sun" { SUN } else { GOOGLE })?; + Ok(None) + } + _ => Err(Error::NotFound(format!("command {id}"))), + } + } + + fn handle_events(&mut self, events: &[Event], _ctx: &Invocation) { + let mut saved: Vec<&str> = events + .iter() + .filter_map(|e| match e { + Event::FileSaved(p) if p.ends_with(".java") => Some(p.as_str()), + _ => None, + }) + .collect(); + saved.sort_unstable(); + saved.dedup(); + for path in saved { + match self.check(path) { + Ok(_) => {} + Err(Error::Cancelled) => return, // a newer save takes over + Err(e) => { + host::notify(NotificationLevel::Warning, "Checkstyle", &e.to_string()); + return; + } + } + } + } +} + +register_plugin!(Checkstyle, providers); + +#[cfg(test)] +mod tests { + use super::*; + use openidea_plugin::ProcessOutput; + use openidea_plugin::mock::MockHost; + + const REPORT: &str = r#"<?xml version="1.0" encoding="UTF-8"?> +<checkstyle version="10.17.0"> +<file name="/project/src/A.java"> +<error line="2" column="1" severity="warning" message="Line contains a tab character." source="com.puppycrawl.tools.checkstyle.checks.whitespace.FileTabCharacterCheck"/> +<error line="3" severity="error" message="Trailing whitespace is not allowed" source="com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineCheck#noTrailingWhitespace"/> +</file> +</checkstyle>"#; + + #[test] + fn parses_reports() { + let r = parse_report(REPORT); + let p = &r["/project/src/A.java"]; + assert_eq!(p.len(), 2); + assert_eq!((p[0].line, p[0].column, p[0].check.as_str()), (1, Some(0), "FileTabCharacter")); + assert_eq!( + (p[1].severity, p[1].message.as_str(), p[1].check.as_str()), + (Severity::Error, "Trailing whitespace is not allowed", "RegexpSingleline") + ); + } + + #[test] + fn checks_saved_java_files_and_fixes() { + let host = MockHost::install().with_capabilities(&["project.read", "events", "storage", "process:checkstyle"]); + let text = "class A {\n\tint x;\n void f() {} \n}"; + host.add_file("src/A.java", text); + host.on_process("checkstyle", |args, _| { + assert_eq!(&args[..4], ["-f", "xml", "-c", GOOGLE]); + Ok(ProcessOutput { status: Some(1), stdout: REPORT.into(), stderr: String::new() }) + }); + let mut p = Checkstyle::default(); + p.handle_events( + &[Event::FileSaved("/project/src/A.java".into()), Event::FileSaved("/project/notes.txt".into())], + &host.invocation(), + ); + assert_eq!(host.process_runs().len(), 1, "only Java files"); + assert_eq!(host.process_runs()[0].cwd.as_deref(), Some("/project")); + let d = &host.diagnostics()["/project/src/A.java"]; + assert_eq!(d.len(), 2); + assert_eq!(d[1].range, Range::new(Position::new(2, 0), Position::new(2, 16)), "whole line without a column"); + assert!(host.tasks()[0].ended); + + let doc = + Document { path: "/project/src/A.java".into(), language: "java".into(), version: 1, text: text.into() }; + let actions = p.code_actions(&doc, Range::new(Position::new(1, 0), Position::new(2, 0))); + let titles: Vec<_> = actions.iter().map(|a| a.title.as_str()).collect(); + assert_eq!(titles, ["Checkstyle: Replace tabs with spaces", "Checkstyle: Remove trailing whitespace"]); + assert_eq!(actions[1].edits[0].1[0].text, " void f() {}"); + } + + #[test] + fn the_projects_configuration_wins() { + let host = MockHost::install().with_capabilities(&["project.read", "events", "storage", "process:checkstyle"]); + host.add_file("src/A.java", "class A {}"); + host.on_process("checkstyle", |_, _| { + Ok(ProcessOutput { status: Some(0), stdout: "<checkstyle/>".into(), stderr: String::new() }) + }); + let mut p = Checkstyle::default(); + p.run_command("use-sun", &host.invocation(), None).unwrap(); + p.handle_events(&[Event::FileSaved("/project/src/A.java".into())], &host.invocation()); + host.add_file("config/checkstyle/checkstyle.xml", "<module name=\"Checker\"/>"); + p.handle_events(&[Event::FileSaved("/project/src/A.java".into())], &host.invocation()); + let configs: Vec<String> = host.process_runs().iter().map(|r| r.args[3].clone()).collect(); + assert_eq!(configs, [SUN, "config/checkstyle/checkstyle.xml"]); + } + + #[test] + fn a_missing_checkstyle_is_reported_once() { + let host = MockHost::install().with_capabilities(&["project.read", "events", "storage"]); + host.add_file("src/A.java", "class A {}"); + Checkstyle::default().handle_events(&[Event::FileSaved("/project/src/A.java".into())], &host.invocation()); + assert!(host.notifications()[0].body.contains("process:checkstyle")); + } +} diff --git a/plugins/official/csv-editor/Cargo.lock b/plugins/official/csv-editor/Cargo.lock new file mode 100644 index 00000000..e0f64ffb --- /dev/null +++ b/plugins/official/csv-editor/Cargo.lock @@ -0,0 +1,333 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "openidea-plugin-openidea-csv-editor" +version = "0.1.0" +dependencies = [ + "openidea-plugin", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[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 = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +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 = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/plugins/official/csv-editor/Cargo.toml b/plugins/official/csv-editor/Cargo.toml new file mode 100644 index 00000000..9e381e43 --- /dev/null +++ b/plugins/official/csv-editor/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "openidea-plugin-openidea-csv-editor" +version = "0.1.0" +edition = "2024" +publish = false + +# A plugin builds on its own (target wasm32-wasip2), outside any IDE workspace. +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../sdk/rust/openidea-plugin" } + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/plugins/official/csv-editor/dist/plugin.wasm b/plugins/official/csv-editor/dist/plugin.wasm new file mode 100644 index 00000000..539a1dce Binary files /dev/null and b/plugins/official/csv-editor/dist/plugin.wasm differ diff --git a/plugins/official/csv-editor/dist/plugin.wasm.sources b/plugins/official/csv-editor/dist/plugin.wasm.sources new file mode 100644 index 00000000..d1b11a17 --- /dev/null +++ b/plugins/official/csv-editor/dist/plugin.wasm.sources @@ -0,0 +1 @@ +b96941af697ce7a6c1c8ef1539d34aa7c23d2d41dd1b2ccffdfda5648f90cf56 diff --git a/plugins/official/csv-editor/plugin.toml b/plugins/official/csv-editor/plugin.toml new file mode 100644 index 00000000..06d920a5 --- /dev/null +++ b/plugins/official/csv-editor/plugin.toml @@ -0,0 +1,23 @@ +id = "openidea.csv-editor" +name = "CSV Editor" +version = "0.1.0" +description = "Edit CSV and TSV files as a table. Edits go to the file's text, so the text view follows and undo is shared." +authors = ["OpenIDEA contributors"] +license = "Apache-2.0" +change-notes = "0.1.0 — first release: table editor for .csv and .tsv with cell editing, inserting and deleting rows; large files load the visible rows only." +engines.openidea = "^1.0" +wasm = "dist/plugin.wasm" +activation = ["on-view:table"] + +[capabilities] +required = ["editor.read", "editor.write"] + +[[contributes.customEditors]] +id = "table" +title = "Table" +patterns = ["*.csv", "*.tsv"] +priority = "default" + +[contributes.settings] +title = "CSV Editor" +schema = "settings.schema.json" diff --git a/plugins/official/csv-editor/settings.schema.json b/plugins/official/csv-editor/settings.schema.json new file mode 100644 index 00000000..9df4a56a --- /dev/null +++ b/plugins/official/csv-editor/settings.schema.json @@ -0,0 +1,17 @@ +{ + "properties": { + "firstRowIsHeader": { + "type": "boolean", + "title": "First row is the header", + "description": "Show the first record as column names instead of a row.", + "default": true + }, + "delimiter": { + "type": "string", + "title": "Delimiter", + "description": "auto: tab for .tsv files, else the most frequent of , ; | in the first line.", + "enum": ["auto", ",", ";", "|", "tab"], + "default": "auto" + } + } +} diff --git a/plugins/official/csv-editor/src/lib.rs b/plugins/official/csv-editor/src/lib.rs new file mode 100644 index 00000000..38cad0ee --- /dev/null +++ b/plugins/official/csv-editor/src/lib.rs @@ -0,0 +1,319 @@ +//! CSV Editor for OpenIDEA: a custom editor showing `.csv` / `.tsv` files as +//! a table. It never keeps its own copy of the data: every render parses the +//! document, and every edit is a versioned text edit of the document, so the +//! text view of the same file follows at once and Undo is one history. +//! +//! Large files: the IDE asks only for the rows it shows; the parse of the +//! last document version is kept, so scrolling doesn't parse again. + +use openidea_plugin::host; +use openidea_plugin::text::position; +use openidea_plugin::views::{Body, Button, Table, View, ViewEvent, Viewport, Views}; +use openidea_plugin::{Error, Invocation, Plugin, Range, TextEdit, register_plugin}; +use std::ops::Range as Span; + +/// One record: the byte spans of its fields and of the whole record (without +/// the line break). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Record { + pub fields: Vec<Span<usize>>, + pub span: Span<usize>, + /// Where the next record starts (after the line break), or the text's end. + pub next: usize, +} + +/// A parsed document. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Csv { + pub delimiter: char, + pub records: Vec<Record>, +} + +/// The field's text: quotes removed, `""` unescaped. +pub fn field_text(text: &str, span: &Span<usize>) -> String { + let raw = &text[span.clone()]; + match raw.strip_prefix('"').and_then(|r| r.strip_suffix('"')) { + Some(inner) if raw.len() >= 2 => inner.replace("\"\"", "\""), + _ => raw.to_owned(), + } +} + +/// `value` as a field: quoted when it contains the delimiter, a quote or a line break. +pub fn quote(value: &str, delimiter: char) -> String { + if value.contains([delimiter, '"', '\n', '\r']) || value.starts_with(' ') || value.ends_with(' ') { + format!("\"{}\"", value.replace('"', "\"\"")) + } else { + value.to_owned() + } +} + +/// The delimiter: `tab` for .tsv, else the most frequent of `,;|\t` in the first line. +pub fn detect_delimiter(path: &str, text: &str, setting: &str) -> char { + match setting { + "," | ";" | "|" => return setting.chars().next().expect("non-empty"), + "tab" => return '\t', + _ => {} + } + if path.to_ascii_lowercase().ends_with(".tsv") { + return '\t'; + } + let first = text.lines().next().unwrap_or(""); + [',', ';', '\t', '|'] + .into_iter() + .max_by_key(|d| first.matches(*d).count()) + .filter(|d| first.contains(*d)) + .unwrap_or(',') +} + +/// RFC 4180 records (quoted fields may span lines); a trailing line break +/// doesn't start an empty record. +pub fn parse(text: &str, delimiter: char) -> Csv { + let bytes = text.as_bytes(); + let d = delimiter as u8; + let mut records = Vec::new(); + let mut i = 0; + while i < bytes.len() { + let start = i; + let mut fields = Vec::new(); + loop { + let field_start = i; + if bytes.get(i) == Some(&b'"') { + i += 1; + while i < bytes.len() { + if bytes[i] == b'"' { + if bytes.get(i + 1) == Some(&b'"') { + i += 2; + continue; + } + i += 1; + break; + } + i += 1; + } + } + while i < bytes.len() && bytes[i] != d && bytes[i] != b'\n' && bytes[i] != b'\r' { + i += 1; + } + fields.push(field_start..i); + if i < bytes.len() && bytes[i] == d { + i += 1; + continue; + } + break; + } + let end = i; + if bytes.get(i) == Some(&b'\r') { + i += 1; + } + if bytes.get(i) == Some(&b'\n') { + i += 1; + } + records.push(Record { fields, span: start..end, next: i }); + } + Csv { delimiter, records } +} + +#[derive(Default)] +pub struct CsvEditor { + /// (path, version) of the last parse, and the parse. + cache: Option<((String, u64), Csv)>, +} + +/// Rows the IDE gets when it asks for no viewport. +const DEFAULT_ROWS: u32 = 200; + +fn edit(text: &str, span: Span<usize>, new_text: String) -> TextEdit { + TextEdit { range: Range::new(position(text, span.start), position(text, span.end)), text: new_text } +} + +impl CsvEditor { + fn parsed(&mut self, path: &str, version: u64, text: &str) -> &Csv { + let key = (path.to_owned(), version); + if self.cache.as_ref().is_none_or(|(k, _)| *k != key) { + let setting = host::setting_string("delimiter").unwrap_or_else(|| "auto".into()); + let csv = parse(text, detect_delimiter(path, text, &setting)); + self.cache = Some((key, csv)); + } + &self.cache.as_ref().expect("just set").1 + } + + /// The edits for `event` on `text` (`header`: the first record is not a row). + pub fn edits_for(csv: &Csv, text: &str, header: bool, event: &ViewEvent) -> Result<Vec<TextEdit>, Error> { + let skip = usize::from(header && !csv.records.is_empty()); + let d = csv.delimiter; + let width = csv.records.iter().map(|r| r.fields.len()).max().unwrap_or(1).max(1); + let empty_record = d.to_string().repeat(width - 1); + let record = |row: u32| csv.records.get(row as usize + skip); + let insert = |before: u32| match record(before) { + Some(r) => vec![edit(text, r.span.start..r.span.start, format!("{empty_record}\n"))], + None => { + // Append; the last record may lack its line break. + let end = text.len(); + let sep = if text.is_empty() || text.ends_with('\n') { "" } else { "\n" }; + vec![edit(text, end..end, format!("{sep}{empty_record}\n"))] + } + }; + Ok(match event { + ViewEvent::Cell { row, column, value } => { + let r = record(*row).ok_or_else(|| Error::Invalid(format!("no row {row}")))?; + let column = *column as usize; + match r.fields.get(column) { + Some(span) => vec![edit(text, span.clone(), quote(value, d))], + // A short record: pad it with empty fields. + None => { + let pad = d.to_string().repeat(column + 1 - r.fields.len()); + vec![edit(text, r.span.end..r.span.end, format!("{pad}{}", quote(value, d)))] + } + } + } + ViewEvent::InsertRow(before) => insert(*before), + ViewEvent::Button(b) if b == "add-row" => insert(u32::MAX), + ViewEvent::DeleteRows(rows) => { + let mut rows: Vec<u32> = rows.clone(); + rows.sort_unstable(); + rows.dedup(); + rows.iter() + .filter_map(|row| record(*row)) + .map(|r| edit(text, r.span.start..r.next, String::new())) + .collect() + } + _ => Vec::new(), + }) + } +} + +impl Plugin for CsvEditor { + fn run_command(&mut self, id: &str, _ctx: &Invocation, _arg: Option<&str>) -> Result<Option<String>, Error> { + Err(Error::NotFound(format!("command {id}"))) + } +} + +impl Views for CsvEditor { + fn render(&mut self, view: &str, viewport: Option<Viewport>, ctx: &Invocation) -> Result<View, Error> { + if view != "table" { + return Err(Error::NotFound(view.into())); + } + let editor = ctx.editor().ok_or_else(|| Error::Invalid("the table editor needs a document".into()))?; + let doc = editor.document()?; + let path = editor.path(); + let header = host::setting_bool("firstRowIsHeader").unwrap_or(true); + let csv = self.parsed(&path, doc.version, &doc.text).clone(); + let skip = usize::from(header && !csv.records.is_empty()); + let width = csv.records.iter().map(|r| r.fields.len()).max().unwrap_or(0); + let columns: Vec<String> = (0..width) + .map(|c| match (header, csv.records.first().and_then(|r| r.fields.get(c))) { + (true, Some(span)) => field_text(&doc.text, span), + _ => format!("Column {}", c + 1), + }) + .collect(); + let total = (csv.records.len() - skip) as u32; + let range = Viewport::range(viewport, total, DEFAULT_ROWS); + let rows = range + .clone() + .map(|row| { + let r = &csv.records[row as usize + skip]; + (0..width).map(|c| r.fields.get(c).map(|s| field_text(&doc.text, s)).unwrap_or_default()).collect() + }) + .collect(); + let delimiter = match csv.delimiter { + '\t' => "tab".to_owned(), + d => format!("'{d}'"), + }; + Ok(View::new(Body::Table(Table { columns, total_rows: total, first_row: range.start, rows, editable: true })) + .button(Button::new("add-row", "Add Row").icon("plus")) + .status(&format!("{total} rows × {width} columns, delimiter {delimiter}"))) + } + + fn handle(&mut self, view: &str, event: ViewEvent, ctx: &Invocation) -> Result<(), Error> { + if view != "table" { + return Err(Error::NotFound(view.into())); + } + let editor = ctx.editor().ok_or_else(|| Error::Invalid("the table editor needs a document".into()))?; + let doc = editor.document()?; + let path = editor.path(); + let header = host::setting_bool("firstRowIsHeader").unwrap_or(true); + let csv = self.parsed(&path, doc.version, &doc.text).clone(); + let edits = Self::edits_for(&csv, &doc.text, header, &event)?; + if !edits.is_empty() { + // Stale: the user typed in the text view meanwhile; the table renders again. + editor.apply_edits(doc.version, &edits)?; + } + Ok(()) + } +} + +register_plugin!(CsvEditor, views); + +#[cfg(test)] +mod tests { + use super::*; + use openidea_plugin::mock::MockHost; + + const DATA: &str = "name,age,city\nAda,36,London\n\"Lovelace, A.\",\"say \"\"hi\"\"\",\"multi\nline\"\nBob,40\n"; + + #[test] + fn parses_quotes_line_breaks_and_short_records() { + let csv = parse(DATA, ','); + assert_eq!(csv.records.len(), 4); + let texts: Vec<String> = csv.records[2].fields.iter().map(|s| field_text(DATA, s)).collect(); + assert_eq!(texts, ["Lovelace, A.", "say \"hi\"", "multi\nline"]); + assert_eq!(csv.records[3].fields.len(), 2); + assert_eq!(parse("a,b\r\nc,d", ',').records.len(), 2); + assert_eq!(detect_delimiter("x.csv", "a;b;c\n", "auto"), ';'); + assert_eq!(detect_delimiter("x.tsv", "a,b\n", "auto"), '\t'); + assert_eq!(quote("a,b", ','), "\"a,b\""); + assert_eq!(quote("plain", ','), "plain"); + } + + #[test] + fn renders_the_visible_rows_with_the_header() { + let host = MockHost::install(); + host.open_editor("/project/people.csv", "csv", DATA, &[]); + let mut p = CsvEditor::default(); + let view = p.render("table", Some(Viewport { first_row: 1, rows: 1 }), &host.invocation()).unwrap(); + let Body::Table(t) = view.body else { panic!("a table") }; + assert_eq!(t.columns, ["name", "age", "city"]); + assert_eq!((t.total_rows, t.first_row), (3, 1)); + assert_eq!(t.rows, [vec!["Lovelace, A.", "say \"hi\"", "multi\nline"]]); + + host.set_setting("firstRowIsHeader", "false"); + let view = p.render("table", None, &host.invocation()).unwrap(); + let Body::Table(t) = view.body else { panic!("a table") }; + assert_eq!((t.columns[0].as_str(), t.total_rows), ("Column 1", 4)); + } + + #[test] + fn edits_cells_and_rows_through_the_document() { + let host = MockHost::install(); + host.open_editor("/project/people.csv", "csv", DATA, &[]); + let mut p = CsvEditor::default(); + let cell = |row, column, value: &str| ViewEvent::Cell { row, column, value: value.into() }; + p.handle("table", cell(0, 2, "Paris, FR"), &host.invocation()).unwrap(); + assert_eq!(host.editor_text().lines().nth(1), Some("Ada,36,\"Paris, FR\"")); + // A short record is padded. + p.handle("table", cell(2, 2, "Oslo"), &host.invocation()).unwrap(); + assert!(host.editor_text().ends_with("Bob,40,Oslo\n"), "{}", host.editor_text()); + p.handle("table", ViewEvent::InsertRow(0), &host.invocation()).unwrap(); + assert_eq!(host.editor_text().lines().nth(1), Some(",,")); + p.handle("table", ViewEvent::DeleteRows(vec![0, 1]), &host.invocation()).unwrap(); + assert!(host.editor_text().starts_with("name,age,city\n\"Lovelace"), "{}", host.editor_text()); + p.handle("table", ViewEvent::Button("add-row".into()), &host.invocation()).unwrap(); + assert!(host.editor_text().ends_with("Bob,40,Oslo\n,,\n"), "{}", host.editor_text()); + } + + #[test] + fn a_changed_document_is_not_overwritten() { + let host = MockHost::install(); + host.open_editor("/project/a.csv", "csv", "a,b\n1,2\n", &[]); + let mut p = CsvEditor::default(); + let csv = parse("a,b\n1,2\n", ','); + let edits = + CsvEditor::edits_for(&csv, "a,b\n1,2\n", true, &ViewEvent::Cell { row: 0, column: 0, value: "9".into() }); + let editor = host.invocation().editor().unwrap(); + host.type_in_editor("x"); + assert_eq!(editor.apply_edits(0, &edits.unwrap()), Err(Error::Stale)); + // The next event works on the current version. + p.handle("table", ViewEvent::Cell { row: 0, column: 1, value: "8".into() }, &host.invocation()).unwrap(); + assert!(host.editor_text().contains(",8"), "{}", host.editor_text()); + } +} diff --git a/plugins/official/excalidraw/.gitignore b/plugins/official/excalidraw/.gitignore new file mode 100644 index 00000000..2aa0170a --- /dev/null +++ b/plugins/official/excalidraw/.gitignore @@ -0,0 +1,4 @@ +web-src/node_modules/ +# Built by plugins/build.sh, not checked in. +web/ +web.sources diff --git a/plugins/official/excalidraw/NOTICE.md b/plugins/official/excalidraw/NOTICE.md new file mode 100644 index 00000000..1df5d881 --- /dev/null +++ b/plugins/official/excalidraw/NOTICE.md @@ -0,0 +1,28 @@ +# Third-party software + +The page in `web/` is built from `web-src/` and bundles: + +- **Excalidraw** (`@excalidraw/excalidraw` 0.18.1), MIT License, Copyright (c) 2020 Excalidraw — + https://github.com/excalidraw/excalidraw — with the libraries it loads on demand (among them + Mermaid, KaTeX and Cytoscape.js, MIT License). +- **React** and **React DOM**, MIT License, Copyright (c) Meta Platforms, Inc. and affiliates. +- The fonts Excalidraw ships in `web/fonts/` (Excalifont, Virgil, Xiaolai, Nunito, Lilita One, + Comic Shanns, Cascadia Code, Liberation Sans, Assistant), each under its own licence (SIL Open + Font License 1.1, or MIT for Comic Shanns); see the Excalidraw repository for their texts. + +The MIT License: + +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software +> and associated documentation files (the "Software"), to deal in the Software without +> restriction, including without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +> Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or +> substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +> BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +> DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/plugins/official/excalidraw/icons/excalidraw.svg b/plugins/official/excalidraw/icons/excalidraw.svg new file mode 100644 index 00000000..71d1b0eb --- /dev/null +++ b/plugins/official/excalidraw/icons/excalidraw.svg @@ -0,0 +1,5 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none"> + <rect x="1.5" y="2.5" width="13" height="11" rx="2" fill="#F1EFFF" stroke="#6E5BD8"/> + <path d="M4 10.5c1.2-2.6 2.4-3.9 3.6-3.9 1.5 0 1.1 2.4 2.6 2.4.9 0 1.5-.8 1.8-1.6" stroke="#6E5BD8" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/> + <circle cx="4" cy="10.5" r="1" fill="#6E5BD8"/> +</svg> diff --git a/plugins/official/excalidraw/icons/excalidraw_dark.svg b/plugins/official/excalidraw/icons/excalidraw_dark.svg new file mode 100644 index 00000000..2e71d97b --- /dev/null +++ b/plugins/official/excalidraw/icons/excalidraw_dark.svg @@ -0,0 +1,5 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none"> + <rect x="1.5" y="2.5" width="13" height="11" rx="2" fill="#2B2747" stroke="#A99CFF"/> + <path d="M4 10.5c1.2-2.6 2.4-3.9 3.6-3.9 1.5 0 1.1 2.4 2.6 2.4.9 0 1.5-.8 1.8-1.6" stroke="#A99CFF" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/> + <circle cx="4" cy="10.5" r="1" fill="#A99CFF"/> +</svg> diff --git a/plugins/official/excalidraw/languages/excalidraw.toml b/plugins/official/excalidraw/languages/excalidraw.toml new file mode 100644 index 00000000..cc7fb623 --- /dev/null +++ b/plugins/official/excalidraw/languages/excalidraw.toml @@ -0,0 +1,6 @@ +id = "excalidraw" +name = "Excalidraw" +extensions = ["excalidraw"] +indent = { tab-size = 2, insert-spaces = true } +ui-mode = "JSON" +tree-sitter = "json" diff --git a/plugins/official/excalidraw/plugin.toml b/plugins/official/excalidraw/plugin.toml new file mode 100644 index 00000000..70bf7ad0 --- /dev/null +++ b/plugins/official/excalidraw/plugin.toml @@ -0,0 +1,35 @@ +id = "openidea.excalidraw" +name = "Excalidraw" +version = "0.1.0" +description = "Draw and edit Excalidraw diagrams (.excalidraw). The drawing is the file's text, so the text editor follows, Undo and Save are shared, and the IDE theme applies." +authors = ["OpenIDEA contributors"] +license = "Apache-2.0" +change-notes = "0.1.0 — first release: the Excalidraw canvas next to (or instead of) the file's text, kept in step both ways; export to PNG and SVG through the save dialog; a file icon and a New › Excalidraw Drawing template. Based on the Excalidraw editor proposed by Deng Liu (#738)." +engines.openidea = "^1.0" + +[capabilities] +# Copy and paste through Excalidraw's menus (the keyboard works without it). +optional = ["clipboard"] + +[[contributes.customEditors]] +id = "canvas" +title = "Drawing" +patterns = ["*.excalidraw", "*.excalidraw.json"] +priority = "default" +layout = "preview" +web = "web/index.html" + +[[contributes.languages]] +path = "languages/excalidraw.toml" + +[[contributes.fileIcons]] +id = "excalidraw" +patterns = ["*.excalidraw", "*.excalidraw.json"] +icon = "icons/excalidraw.svg" +iconDark = "icons/excalidraw_dark.svg" + +[[contributes.fileTemplates]] +id = "drawing" +name = "Excalidraw Drawing" +extension = "excalidraw" +path = "templates/drawing.excalidraw" diff --git a/plugins/official/excalidraw/templates/drawing.excalidraw b/plugins/official/excalidraw/templates/drawing.excalidraw new file mode 100644 index 00000000..1d9b5f0a --- /dev/null +++ b/plugins/official/excalidraw/templates/drawing.excalidraw @@ -0,0 +1,13 @@ +{ + "type": "excalidraw", + "version": 2, + "source": "https://openidea.dev", + "elements": [], + "appState": { + "gridSize": 20, + "gridStep": 5, + "gridModeEnabled": false, + "viewBackgroundColor": "#ffffff" + }, + "files": {} +} diff --git a/plugins/official/excalidraw/web-src/index.html b/plugins/official/excalidraw/web-src/index.html new file mode 100644 index 00000000..9101cf84 --- /dev/null +++ b/plugins/official/excalidraw/web-src/index.html @@ -0,0 +1,32 @@ +<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <title>Excalidraw + + + +
+ + + diff --git a/plugins/official/excalidraw/web-src/package.json b/plugins/official/excalidraw/web-src/package.json new file mode 100644 index 00000000..fab85689 --- /dev/null +++ b/plugins/official/excalidraw/web-src/package.json @@ -0,0 +1,26 @@ +{ + "name": "openidea-plugin-excalidraw-web", + "private": true, + "version": "0.1.0", + "type": "module", + "description": "The Excalidraw plugin's web page; `pnpm build` writes it to ../web.", + "scripts": { + "build": "tsc --noEmit && vite build", + "test": "vitest run" + }, + "dependencies": { + "@excalidraw/excalidraw": "0.18.1", + "react": "^19.1.0", + "react-dom": "^19.1.0" + }, + "devDependencies": { + "@types/node": "^26.6.6", + "@types/react": "^19.1.0", + "@types/react-dom": "^19.1.0", + "@vitejs/plugin-react": "^6.0.2", + "jsdom": "^30.1.3", + "typescript": "~6.0.3", + "vite": "^8.0.16", + "vitest": "^5.0.5" + } +} diff --git a/plugins/official/excalidraw/web-src/pnpm-lock.yaml b/plugins/official/excalidraw/web-src/pnpm-lock.yaml new file mode 100644 index 00000000..0fe21cc4 --- /dev/null +++ b/plugins/official/excalidraw/web-src/pnpm-lock.yaml @@ -0,0 +1,3208 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + '@excalidraw/excalidraw': + specifier: 0.18.1 + version: 0.18.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + react: + specifier: ^19.1.0 + version: 19.3.1 + react-dom: + specifier: ^19.1.0 + version: 19.3.1(react@19.3.1) + devDependencies: + '@types/node': + specifier: ^26.6.6 + version: 26.6.6 + '@types/react': + specifier: ^19.1.0 + version: 19.3.0 + '@types/react-dom': + specifier: ^19.1.0 + version: 19.3.0(@types/react@19.3.0) + '@vitejs/plugin-react': + specifier: ^6.0.2 + version: 6.1.2(vite@8.3.5(@types/node@26.6.6)) + jsdom: + specifier: ^30.1.3 + version: 30.1.3 + typescript: + specifier: ~6.0.3 + version: 6.0.3 + vite: + specifier: ^8.0.16 + version: 8.3.5(@types/node@26.6.6) + vitest: + specifier: ^5.0.5 + version: 5.0.5(@types/node@26.6.6)(jsdom@30.1.3)(vite@8.3.5(@types/node@26.6.6)) + +packages: + + '@antfu/install-pkg@2.1.0': + resolution: {integrity: sha512-sdg9NxU3zR4Mnawfbc/x6GB5Wf17WYud5qOuEuxXjaKpYpMkISSJEjItGebXJ2bQ4DIcly4NYH23mtkGJjvKUw==} + + '@asamuzakjp/css-color@7.1.9': + resolution: {integrity: sha512-vZ6JQVq8Ivgz6b/IBlAf90wZviXdluY13cQOPO+nJHbmXwGrPl2GcpqUY7a55/8ZVdfONXpCFMpRijOBCHNlcQ==} + engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0} + + '@asamuzakjp/dom-selector@10.0.5': + resolution: {integrity: sha512-EgmJ7oEaGQECTn3H3wmnQpEy4hKY66VvM7VQndwPIQob3p877BgbyOUE3EX0LgXQCciF2H8KMdR+RznqjMNOLw==} + engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0} + + '@babel/runtime@7.29.10': + resolution: {integrity: sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==} + engines: {node: '>=6.9.0'} + + '@braintree/sanitize-url@6.0.2': + resolution: {integrity: sha512-Tbsj02wXCbqGmzdnXNk0SOF19ChhRU70BsroIi4Pm6Ehp56in6vch94mfbdQ17DozxkL3BAVjbZ4Qc1a0HFRAg==} + + '@braintree/sanitize-url@7.1.2': + resolution: {integrity: sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA==} + + '@bramus/specificity@2.4.3': + resolution: {integrity: sha512-0GEz8qJWokkUVYQYRukmkSHIFNoBH8QTreeHrAFbvz1XFYc3Y+puhMs8PQ5x8GNugiC2l5jvDBXKLbBIByeSBw==} + hasBin: true + + '@chevrotain/cst-dts-gen@11.0.3': + resolution: {integrity: sha512-BvIKpRLeS/8UbfxXxgC33xOumsacaeCKAjAeLyOn7Pcp95HiRbrpl14S+9vaZLolnbssPIUuiUd8IvgkRyt6NQ==} + + '@chevrotain/gast@11.0.3': + resolution: {integrity: sha512-+qNfcoNk70PyS/uxmj3li5NiECO+2YKZZQMbmjTqRI3Qchu8Hig/Q9vgkHpI3alNjr7M+a2St5pw5w5F6NL5/Q==} + + '@chevrotain/regexp-to-ast@11.0.3': + resolution: {integrity: sha512-1fMHaBZxLFvWI067AVbGJav1eRY7N8DDvYCTwGBiE/ytKBgP8azTdgyrKyWZ9Mfh09eHWb5PgTSO8wi7U824RA==} + + '@chevrotain/types@11.0.3': + resolution: {integrity: sha512-gsiM3G8b58kZC2HaWR50gu6Y1440cHiJ+i3JUvcp/35JchYejb2+5MVeJK0iKThYpAa/P2PYFV4hoi44HD+aHQ==} + + '@chevrotain/types@11.1.2': + resolution: {integrity: sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==} + + '@chevrotain/utils@11.0.3': + resolution: {integrity: sha512-YslZMgtJUyuMbZ+aKvfF3x1f5liK4mWNxghFRv7jqRR9C3R3fAOGTTKvxXDa2Y1s9zSbcpuO0cAxDYsc9SrXoQ==} + + '@csstools/color-helpers@6.1.2': + resolution: {integrity: sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==} + engines: {node: '>=20.19.0'} + + '@csstools/css-calc@3.4.3': + resolution: {integrity: sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@csstools/css-parser-algorithms': ^4.0.2 + '@csstools/css-tokenizer': ^4.0.2 + + '@csstools/css-color-parser@4.2.7': + resolution: {integrity: sha512-zgm9yjQz5iJB4VL8RyVwd71TWB8Q89FSxt/NzXoWqPSkEBOVtn9L6vAPtSc9hpKfB0Awo/AL2VKFHjYetBLFHQ==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@csstools/css-parser-algorithms': ^4.0.2 + '@csstools/css-tokenizer': ^4.0.2 + + '@csstools/css-parser-algorithms@4.0.2': + resolution: {integrity: sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@csstools/css-tokenizer': ^4.0.2 + + '@csstools/css-syntax-patches-for-csstree@1.1.16': + resolution: {integrity: sha512-LsDbJPP/B8cPasUJyTA5S99F7C4G93ngW8hUluXz8CFeOaaRnBPtBiIlvgcPYU0HmHNz8CXg+1vwFrIB4F6Dgw==} + peerDependencies: + css-tree: ^3.2.1 + peerDependenciesMeta: + css-tree: + optional: true + + '@csstools/css-tokenizer@4.0.2': + resolution: {integrity: sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==} + engines: {node: '>=20.19.0'} + + '@excalidraw/excalidraw@0.18.1': + resolution: {integrity: sha512-6i5Gt7IDTOH//qa0Z315Ly5iVRhjWpu2whrlQFqkuwrkKUWgRsMk0P5qdE7bpyDpai7jeLeWYkyj1eVAfni1lw==} + peerDependencies: + react: ^17.0.2 || ^18.2.0 || ^19.0.0 + react-dom: ^17.0.2 || ^18.2.0 || ^19.0.0 + + '@excalidraw/laser-pointer@1.3.1': + resolution: {integrity: sha512-psA1z1N2qeAfsORdXc9JmD2y4CmDwmuMRxnNdJHZexIcPwaNEyIpNcelw+QkL9rz9tosaN9krXuKaRqYpRAR6g==} + + '@excalidraw/markdown-to-text@0.1.2': + resolution: {integrity: sha512-1nDXBNAojfi3oSFwJswKREkFm5wrSjqay81QlyRv2pkITG/XYB5v+oChENVBQLcxQwX4IUATWvXM5BcaNhPiIg==} + + '@excalidraw/mermaid-to-excalidraw@2.2.2': + resolution: {integrity: sha512-5VKQq5CdRocC82vOIUpQ5ufJOVV9FpBTdHGA+ULqazeIVV+cr299877omQCibsdS3Bpitz2fsnTwnIXEmLVDSg==} + + '@excalidraw/random-username@1.1.0': + resolution: {integrity: sha512-nULYsQxkWHnbmHvcs+efMkJ4/9TtvNyFeLyHdeGxW0zHs6P+jYVqcRff9A6Vq9w9JXeDRnRh2VKvTtS19GW2qA==} + engines: {node: '>=10'} + + '@exodus/bytes@1.16.0': + resolution: {integrity: sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + peerDependencies: + '@noble/hashes': ^1.8.0 || ^2.0.0 + peerDependenciesMeta: + '@noble/hashes': + optional: true + + '@floating-ui/core@1.8.0': + resolution: {integrity: sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==} + + '@floating-ui/dom@1.8.0': + resolution: {integrity: sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==} + + '@floating-ui/react-dom@2.1.9': + resolution: {integrity: sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==} + peerDependencies: + react: '>=16.8.0' + react-dom: '>=16.8.0' + + '@floating-ui/utils@0.2.12': + resolution: {integrity: sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==} + + '@iconify/types@2.0.0': + resolution: {integrity: sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==} + + '@iconify/utils@3.1.7': + resolution: {integrity: sha512-JZHlwdID+dy+lTgbYC8NEC4zeugqeYsc6jewvzb4c58kHauJn+X7rNwQjxz5p2qSjqaEeQoLkCIQ9v/H4PK0/w==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@mermaid-js/parser@0.6.3': + resolution: {integrity: sha512-lnjOhe7zyHjc+If7yT4zoedx2vo4sHaTmtkl1+or8BRTnCtDmcTpAjpzDSfCZrshM5bCoz0GyidzadJAH1xobA==} + + '@mermaid-js/parser@1.2.1': + resolution: {integrity: sha512-n12NohV3mrUyUL2o93IgG/ifeW9FTyeJn3zDxkhwa8MJ9Fxg3HQMlA3RiGmD/3UnJvheztkjjQAjA2T4LmUcpw==} + + '@oxc-project/types@0.156.0': + resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} + + '@radix-ui/primitive@1.0.0': + resolution: {integrity: sha512-3e7rn8FDMin4CgeL7Z/49smCA3rFYY3Ha2rUQ7HRWFadS5iCRw08ZgVT1LaNTCNqgvrUiyczLflrVrF0SRQtNA==} + + '@radix-ui/primitive@1.1.1': + resolution: {integrity: sha512-SJ31y+Q/zAyShtXJc8x83i9TYdbAfHZ++tUZnvjJJqFjzsdUnKsxPL6IEtBlxKkU7yzer//GQtZSV4GbldL3YA==} + + '@radix-ui/react-arrow@1.1.2': + resolution: {integrity: sha512-G+KcpzXHq24iH0uGG/pF8LyzpFJYGD4RfLjCIBfGdSLXvjLHST31RUiRVrupIBMvIppMgSzQ6l66iAxl03tdlg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-collection@1.0.1': + resolution: {integrity: sha512-uuiFbs+YCKjn3X1DTSx9G7BHApu4GHbi3kgiwsnFUbOKCrwejAJv4eE4Vc8C0Oaxt9T0aV4ox0WCOdx+39Xo+g==} + peerDependencies: + react: ^16.8 || ^17.0 || ^18.0 + react-dom: ^16.8 || ^17.0 || ^18.0 + + '@radix-ui/react-compose-refs@1.0.0': + resolution: {integrity: sha512-0KaSv6sx787/hK3eF53iOkiSLwAGlFMx5lotrqD2pTjB18KbybKoEIgkNZTKC60YECDQTKGTRcDBILwZVqVKvA==} + peerDependencies: + react: ^16.8 || ^17.0 || ^18.0 + + '@radix-ui/react-compose-refs@1.1.1': + resolution: {integrity: sha512-Y9VzoRDSJtgFMUCoiZBDVo084VQ5hfpXxVE+NgkdNsjiDBByiImMZKKhxMwCbdHvhlENG6a833CbFkOQvTricw==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-context@1.0.0': + resolution: {integrity: sha512-1pVM9RfOQ+n/N5PJK33kRSKsr1glNxomxONs5c49MliinBY6Yw2Q995qfBUUo0/Mbg05B/sGA0gkgPI7kmSHBg==} + peerDependencies: + react: ^16.8 || ^17.0 || ^18.0 + + '@radix-ui/react-context@1.1.1': + resolution: {integrity: sha512-UASk9zi+crv9WteK/NU4PLvOoL3OuE6BWVKNF6hPRBtYBDXQ2u5iu3O59zUlJiTVvkyuycnqrztsHVJwcK9K+Q==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-direction@1.0.0': + resolution: {integrity: sha512-2HV05lGUgYcA6xgLQ4BKPDmtL+QbIZYH5fCOTAOOcJ5O0QbWS3i9lKaurLzliYUDhORI2Qr3pyjhJh44lKA3rQ==} + peerDependencies: + react: ^16.8 || ^17.0 || ^18.0 + + '@radix-ui/react-dismissable-layer@1.1.5': + resolution: {integrity: sha512-E4TywXY6UsXNRhFrECa5HAvE5/4BFcGyfTyK36gP+pAW1ed7UTK4vKwdr53gAJYwqbfCWC6ATvJa3J3R/9+Qrg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-focus-guards@1.1.1': + resolution: {integrity: sha512-pSIwfrT1a6sIoDASCSpFwOasEwKTZWDw/iBdtnqKO7v6FeOzYJ7U53cPzYFVR3geGGXgVHaH+CdngrrAzqUGxg==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-focus-scope@1.1.2': + resolution: {integrity: sha512-zxwE80FCU7lcXUGWkdt6XpTTCKPitG1XKOwViTxHVKIJhZl9MvIl2dVHeZENCWD9+EdWv05wlaEkRXUykU27RA==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-id@1.0.0': + resolution: {integrity: sha512-Q6iAB/U7Tq3NTolBBQbHTgclPmGWE3OlktGGqrClPozSw4vkQ1DfQAOtzgRPecKsMdJINE05iaoDUG8tRzCBjw==} + peerDependencies: + react: ^16.8 || ^17.0 || ^18.0 + + '@radix-ui/react-id@1.1.0': + resolution: {integrity: sha512-EJUrI8yYh7WOjNOqpoJaf1jlFIH2LvtgAl+YcFqNCa+4hj64ZXmPkAKOFs/ukjz3byN6bdb/AVUqHkI8/uWWMA==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-popover@1.1.6': + resolution: {integrity: sha512-NQouW0x4/GnkFJ/pRqsIS3rM/k97VzKnVb2jB7Gq7VEGPy5g7uNV1ykySFt7eWSp3i2uSGFwaJcvIRJBAHmmFg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-popper@1.2.2': + resolution: {integrity: sha512-Rvqc3nOpwseCyj/rgjlJDYAgyfw7OC1tTkKn2ivhaMGcYt8FSBlahHOZak2i3QwkRXUXgGgzeEe2RuqeEHuHgA==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-portal@1.1.4': + resolution: {integrity: sha512-sn2O9k1rPFYVyKd5LAJfo96JlSGVFpa1fS6UuBJfrZadudiw5tAmru+n1x7aMRQ84qDM71Zh1+SzK5QwU0tJfA==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-presence@1.0.0': + resolution: {integrity: sha512-A+6XEvN01NfVWiKu38ybawfHsBjWum42MRPnEuqPsBZ4eV7e/7K321B5VgYMPv3Xx5An6o1/l9ZuDBgmcmWK3w==} + peerDependencies: + react: ^16.8 || ^17.0 || ^18.0 + react-dom: ^16.8 || ^17.0 || ^18.0 + + '@radix-ui/react-presence@1.1.2': + resolution: {integrity: sha512-18TFr80t5EVgL9x1SwF/YGtfG+l0BS0PRAlCWBDoBEiDQjeKgnNZRVJp/oVBl24sr3Gbfwc/Qpj4OcWTQMsAEg==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-primitive@1.0.1': + resolution: {integrity: sha512-fHbmislWVkZaIdeF6GZxF0A/NH/3BjrGIYj+Ae6eTmTCr7EB0RQAAVEiqsXK6p3/JcRqVSBQoceZroj30Jj3XA==} + peerDependencies: + react: ^16.8 || ^17.0 || ^18.0 + react-dom: ^16.8 || ^17.0 || ^18.0 + + '@radix-ui/react-primitive@2.0.2': + resolution: {integrity: sha512-Ec/0d38EIuvDF+GZjcMU/Ze6MxntVJYO/fRlCPhCaVUyPY9WTalHJw54tp9sXeJo3tlShWpy41vQRgLRGOuz+w==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-roving-focus@1.0.2': + resolution: {integrity: sha512-HLK+CqD/8pN6GfJm3U+cqpqhSKYAWiOJDe+A+8MfxBnOue39QEeMa43csUn2CXCHQT0/mewh1LrrG4tfkM9DMA==} + peerDependencies: + react: ^16.8 || ^17.0 || ^18.0 + react-dom: ^16.8 || ^17.0 || ^18.0 + + '@radix-ui/react-slot@1.0.1': + resolution: {integrity: sha512-avutXAFL1ehGvAXtPquu0YK5oz6ctS474iM3vNGQIkswrVhdrS52e3uoMQBzZhNRAIE0jBnUyXWNmSjGHhCFcw==} + peerDependencies: + react: ^16.8 || ^17.0 || ^18.0 + + '@radix-ui/react-slot@1.1.2': + resolution: {integrity: sha512-YAKxaiGsSQJ38VzKH86/BPRC4rh+b1Jpa+JneA5LRE7skmLPNAyeG8kPJj/oo4STLvlrs8vkf/iYyc3A5stYCQ==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-tabs@1.0.2': + resolution: {integrity: sha512-gOUwh+HbjCuL0UCo8kZ+kdUEG8QtpdO4sMQduJ34ZEz0r4922g9REOBM+vIsfwtGxSug4Yb1msJMJYN2Bk8TpQ==} + peerDependencies: + react: ^16.8 || ^17.0 || ^18.0 + react-dom: ^16.8 || ^17.0 || ^18.0 + + '@radix-ui/react-use-callback-ref@1.0.0': + resolution: {integrity: sha512-GZtyzoHz95Rhs6S63D2t/eqvdFCm7I+yHMLVQheKM7nBD8mbZIt+ct1jz4536MDnaOGKIxynJ8eHTkVGVVkoTg==} + peerDependencies: + react: ^16.8 || ^17.0 || ^18.0 + + '@radix-ui/react-use-callback-ref@1.1.0': + resolution: {integrity: sha512-CasTfvsy+frcFkbXtSJ2Zu9JHpN8TYKxkgJGWbjiZhFivxaeW7rMeZt7QELGVLaYVfFMsKHjb7Ak0nMEe+2Vfw==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-controllable-state@1.0.0': + resolution: {integrity: sha512-FohDoZvk3mEXh9AWAVyRTYR4Sq7/gavuofglmiXB2g1aKyboUD4YtgWxKj8O5n+Uak52gXQ4wKz5IFST4vtJHg==} + peerDependencies: + react: ^16.8 || ^17.0 || ^18.0 + + '@radix-ui/react-use-controllable-state@1.1.0': + resolution: {integrity: sha512-MtfMVJiSr2NjzS0Aa90NPTnvTSg6C/JLCV7ma0W6+OMV78vd8OyRpID+Ng9LxzsPbLeuBnWBA1Nq30AtBIDChw==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-escape-keydown@1.1.0': + resolution: {integrity: sha512-L7vwWlR1kTTQ3oh7g1O0CBF3YCyyTj8NmhLR+phShpyA50HCfBFKVJTpshm9PzLiKmehsrQzTYTpX9HvmC9rhw==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-layout-effect@1.0.0': + resolution: {integrity: sha512-6Tpkq+R6LOlmQb1R5NNETLG0B4YP0wc+klfXafpUCj6JGyaUc8il7/kUZ7m59rGbXGczE9Bs+iz2qloqsZBduQ==} + peerDependencies: + react: ^16.8 || ^17.0 || ^18.0 + + '@radix-ui/react-use-layout-effect@1.1.0': + resolution: {integrity: sha512-+FPE0rOdziWSrH9athwI1R0HDVbWlEhd+FR+aSDk4uWGmSJ9Z54sdZVDQPZAinJhJXwfT+qnj969mCsT2gfm5w==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-rect@1.1.0': + resolution: {integrity: sha512-0Fmkebhr6PiseyZlYAOtLS+nb7jLmpqTrJyv61Pe68MKYW6OWdRE2kI70TaYY27u7H0lajqM3hSMMLFq18Z7nQ==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/react-use-size@1.1.0': + resolution: {integrity: sha512-XW3/vWuIXHa+2Uwcc2ABSfcCledmXhhQPlGbfcRXbiUQI5Icjcg19BGCZVKKInYbvUCut/ufbbLLPFC5cbb1hw==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + '@radix-ui/rect@1.1.0': + resolution: {integrity: sha512-A9+lCBZoaMJlVKcRBz2YByCG+Cp2t6nAnMnNba+XiWxnj6r4JUFqfsgwocMBZU9LPtdxC6wB56ySYpc7LQIoJg==} + + '@rolldown/binding-android-arm-eabi@1.2.16': + resolution: {integrity: sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.16': + resolution: {integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.16': + resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.16': + resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.16': + resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.16': + resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.16': + resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.16': + resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.16': + resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.16': + resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.16': + resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.16': + resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.16': + resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/d3-array@3.2.2': + resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==} + + '@types/d3-axis@3.0.6': + resolution: {integrity: sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==} + + '@types/d3-brush@3.0.6': + resolution: {integrity: sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==} + + '@types/d3-chord@3.0.6': + resolution: {integrity: sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==} + + '@types/d3-color@3.1.3': + resolution: {integrity: sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==} + + '@types/d3-contour@3.0.6': + resolution: {integrity: sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==} + + '@types/d3-delaunay@6.0.4': + resolution: {integrity: sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==} + + '@types/d3-dispatch@3.0.7': + resolution: {integrity: sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA==} + + '@types/d3-drag@3.0.7': + resolution: {integrity: sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==} + + '@types/d3-dsv@3.0.7': + resolution: {integrity: sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==} + + '@types/d3-ease@3.0.2': + resolution: {integrity: sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==} + + '@types/d3-fetch@3.0.7': + resolution: {integrity: sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==} + + '@types/d3-force@3.0.10': + resolution: {integrity: sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==} + + '@types/d3-format@3.0.4': + resolution: {integrity: sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==} + + '@types/d3-geo@3.1.1': + resolution: {integrity: sha512-65Emv9fQiQQqphLlRkuQ5ypPsOmWPhtBGCMv61JDPEPMvsx+gzhGf74yw1a78xFKPj6zw4AgQICJoQv0vK9M2w==} + + '@types/d3-hierarchy@3.1.7': + resolution: {integrity: sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==} + + '@types/d3-interpolate@3.0.4': + resolution: {integrity: sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==} + + '@types/d3-path@3.1.1': + resolution: {integrity: sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==} + + '@types/d3-polygon@3.0.2': + resolution: {integrity: sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==} + + '@types/d3-quadtree@3.0.6': + resolution: {integrity: sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==} + + '@types/d3-random@3.0.4': + resolution: {integrity: sha512-UHYId5WTCx4L4YNel7NU00XUXXgvgpgZOvp10PuvsQENjMDXhh2RyFc0KBjO7B45ne4Ha1yVH7ii0vnzKkuzWA==} + + '@types/d3-scale-chromatic@3.1.0': + resolution: {integrity: sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==} + + '@types/d3-scale@4.0.9': + resolution: {integrity: sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==} + + '@types/d3-selection@3.0.12': + resolution: {integrity: sha512-Qe/KWYhEiIIxGs7HrAAjMfShxKldx19SJtr5zu53f3afPsdZNz7HHtdTLXo/kqeiWNXVycI24kSnfzBYkTzpgw==} + + '@types/d3-shape@3.2.0': + resolution: {integrity: sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==} + + '@types/d3-time-format@4.0.3': + resolution: {integrity: sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==} + + '@types/d3-time@3.0.4': + resolution: {integrity: sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==} + + '@types/d3-timer@3.0.2': + resolution: {integrity: sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==} + + '@types/d3-transition@3.0.9': + resolution: {integrity: sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==} + + '@types/d3-zoom@3.0.9': + resolution: {integrity: sha512-0sE1406XBYJGiqD3AusTl9ZqC//2mIXix51tbom25gDCA8ri4xnSZg28CaSE8Srl6FClqABUKfsn0qghgdepMA==} + + '@types/d3@7.4.3': + resolution: {integrity: sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.10': + resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==} + + '@types/geojson@7946.0.16': + resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==} + + '@types/node@26.6.6': + resolution: {integrity: sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==} + + '@types/react-dom@19.3.0': + resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==} + peerDependencies: + '@types/react': ^19.3.0 + + '@types/react@19.3.0': + resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==} + + '@types/trusted-types@2.0.7': + resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} + + '@upsetjs/venn.js@2.0.0': + resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==} + + '@vitejs/plugin-react@6.1.2': + resolution: {integrity: sha512-fhJNGUdscQa4HkI0xFxwonWyhnVReCPDbXI7FH7jmzpnVCrFQI7PRrhWecO263610vOrs9tr2Y4xcf8uAdFxbw==} + engines: {node: ^20.19.0 || >=22.12.0} + peerDependencies: + '@rolldown/plugin-babel': ^0.1.7 || ^0.2.0 + babel-plugin-react-compiler: ^1.0.0 + oxc-transform-react: ^0.152.0 + vite: ^8.0.0 + peerDependenciesMeta: + '@rolldown/plugin-babel': + optional: true + babel-plugin-react-compiler: + optional: true + oxc-transform-react: + optional: true + + '@vitest/mocker@5.0.5': + resolution: {integrity: sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==} + peerDependencies: + msw: ^2.4.9 || ^3.0.0 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/spy@5.0.5': + resolution: {integrity: sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==} + + anymatch@3.1.3: + resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} + engines: {node: '>= 8'} + + aria-hidden@1.2.6: + resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==} + engines: {node: '>=10'} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + bidi-js@1.1.0: + resolution: {integrity: sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==} + + binary-extensions@2.3.0: + resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==} + engines: {node: '>=8'} + + braces@3.0.3: + resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} + engines: {node: '>=8'} + + browser-fs-access@0.29.1: + resolution: {integrity: sha512-LSvVX5e21LRrXqVMhqtAwj5xPgDb+fXAIH80NsnCQ9xuZPs2xWsOREi24RKgZa1XOiQRbcmVrv87+ulOKsgjxw==} + + canvas-roundrect-polyfill@0.0.1: + resolution: {integrity: sha512-yWq+R3U3jE+coOeEb3a3GgE2j/0MMiDKM/QpLb6h9ihf5fGY9UXtvK9o4vNqjWXoZz7/3EaSVU3IX53TvFFUOw==} + + chai@6.3.0: + resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} + engines: {node: '>=18'} + + chevrotain-allstar@0.3.1: + resolution: {integrity: sha512-b7g+y9A0v4mxCW1qUhf3BSVPg+/NvGErk/dOkrDaHA0nQIQGAtrOjlX//9OQtRlSCy+x9rfB5N8yC71lH1nvMw==} + peerDependencies: + chevrotain: ^11.0.0 + + chevrotain@11.0.3: + resolution: {integrity: sha512-ci2iJH6LeIkvP9eJW6gpueU8cnZhv85ELY8w8WiFtNjMHA5ad6pQLaJo9mEly/9qUyCpvqX8/POVUTf18/HFdw==} + + chokidar@3.6.0: + resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==} + engines: {node: '>= 8.10.0'} + + clsx@1.1.1: + resolution: {integrity: sha512-6/bPho624p3S2pMyvP5kKBPXnI3ufHLObBFCfgx+LkeR5lg2XYy2hqZqUf45ypD8COn2bhgGJSUE+l5dhNBieA==} + engines: {node: '>=6'} + + commander@7.2.0: + resolution: {integrity: sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==} + engines: {node: '>= 10'} + + commander@8.3.0: + resolution: {integrity: sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==} + engines: {node: '>= 12'} + + cose-base@1.0.3: + resolution: {integrity: sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==} + + cose-base@2.2.0: + resolution: {integrity: sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==} + + crc-32@0.3.0: + resolution: {integrity: sha512-kucVIjOmMc1f0tv53BJ/5WIX+MGLcKuoBhnGqQrgKJNqLByb/sVMWfW/Aw6hw0jgcqjJ2pi9E5y32zOIpaUlsA==} + engines: {node: '>=0.8'} + + cross-env@7.0.3: + resolution: {integrity: sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==} + engines: {node: '>=10.14', npm: '>=6', yarn: '>=1'} + hasBin: true + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + + css-tree@3.2.1: + resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==} + engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + cytoscape-cose-bilkent@4.1.0: + resolution: {integrity: sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ==} + peerDependencies: + cytoscape: ^3.2.0 + + cytoscape-fcose@2.2.0: + resolution: {integrity: sha512-ki1/VuRIHFCzxWNrsshHYPs6L7TvLu3DL+TyIGEsRcvVERmxokbf5Gdk7mFxZnTdiGtnA4cfSmjZJMviqSuZrQ==} + peerDependencies: + cytoscape: ^3.2.0 + + cytoscape@3.34.4: + resolution: {integrity: sha512-msY99tMY8iWTg+sIPGfSqDcPNOt4xcj+v/K/7qUFaCUxxlqnMkUYLBjRUzn9W5CU/R2hrmtJa5+UtovrEM2ctg==} + engines: {node: '>=0.10'} + + d3-array@2.12.1: + resolution: {integrity: sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==} + + d3-array@3.2.4: + resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==} + engines: {node: '>=12'} + + d3-axis@3.0.0: + resolution: {integrity: sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==} + engines: {node: '>=12'} + + d3-brush@3.0.0: + resolution: {integrity: sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==} + engines: {node: '>=12'} + + d3-chord@3.0.1: + resolution: {integrity: sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==} + engines: {node: '>=12'} + + d3-color@3.1.0: + resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==} + engines: {node: '>=12'} + + d3-contour@4.0.2: + resolution: {integrity: sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==} + engines: {node: '>=12'} + + d3-delaunay@6.0.4: + resolution: {integrity: sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==} + engines: {node: '>=12'} + + d3-dispatch@3.0.1: + resolution: {integrity: sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==} + engines: {node: '>=12'} + + d3-drag@3.0.0: + resolution: {integrity: sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==} + engines: {node: '>=12'} + + d3-dsv@3.0.1: + resolution: {integrity: sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==} + engines: {node: '>=12'} + hasBin: true + + d3-ease@3.0.1: + resolution: {integrity: sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==} + engines: {node: '>=12'} + + d3-fetch@3.0.1: + resolution: {integrity: sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==} + engines: {node: '>=12'} + + d3-force@3.0.0: + resolution: {integrity: sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==} + engines: {node: '>=12'} + + d3-format@3.1.2: + resolution: {integrity: sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==} + engines: {node: '>=12'} + + d3-geo@3.1.1: + resolution: {integrity: sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==} + engines: {node: '>=12'} + + d3-hierarchy@3.1.2: + resolution: {integrity: sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==} + engines: {node: '>=12'} + + d3-interpolate@3.0.1: + resolution: {integrity: sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==} + engines: {node: '>=12'} + + d3-path@1.0.9: + resolution: {integrity: sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==} + + d3-path@3.1.0: + resolution: {integrity: sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==} + engines: {node: '>=12'} + + d3-polygon@3.0.1: + resolution: {integrity: sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==} + engines: {node: '>=12'} + + d3-quadtree@3.0.1: + resolution: {integrity: sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==} + engines: {node: '>=12'} + + d3-random@3.0.1: + resolution: {integrity: sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==} + engines: {node: '>=12'} + + d3-sankey@0.12.3: + resolution: {integrity: sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==} + + d3-scale-chromatic@3.1.0: + resolution: {integrity: sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==} + engines: {node: '>=12'} + + d3-scale@4.0.2: + resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==} + engines: {node: '>=12'} + + d3-selection@3.0.0: + resolution: {integrity: sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==} + engines: {node: '>=12'} + + d3-shape@1.3.7: + resolution: {integrity: sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==} + + d3-shape@3.2.0: + resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==} + engines: {node: '>=12'} + + d3-time-format@4.1.0: + resolution: {integrity: sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==} + engines: {node: '>=12'} + + d3-time@3.1.0: + resolution: {integrity: sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==} + engines: {node: '>=12'} + + d3-timer@3.0.1: + resolution: {integrity: sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==} + engines: {node: '>=12'} + + d3-transition@3.0.1: + resolution: {integrity: sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==} + engines: {node: '>=12'} + peerDependencies: + d3-selection: 2 - 3 + + d3-zoom@3.0.0: + resolution: {integrity: sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==} + engines: {node: '>=12'} + + d3@7.9.0: + resolution: {integrity: sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==} + engines: {node: '>=12'} + + dagre-d3-es@7.0.14: + resolution: {integrity: sha512-P4rFMVq9ESWqmOgK+dlXvOtLwYg0i7u0HBGJER0LZDJT2VHIPAMZ/riPxqJceWMStH5+E61QxFra9kIS3AqdMg==} + + data-urls@8.0.0: + resolution: {integrity: sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==} + engines: {node: ^22.14.0 || >=24.0.0} + + dayjs@1.11.23: + resolution: {integrity: sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==} + + decimal.js@10.6.0: + resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==} + + delaunator@5.1.0: + resolution: {integrity: sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + detect-node-es@1.1.0: + resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==} + + dompurify@3.4.17: + resolution: {integrity: sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==} + + entities@9.0.0: + resolution: {integrity: sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==} + engines: {node: '>=20.19.0'} + + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + + es-toolkit@1.53.1: + resolution: {integrity: sha512-VhMc6IXmexu8iYFfL2aaAww6IvJTdHlqBLruLoEUs33YD4IcP5DdZcLOybMsMmmLsiy1c8PsiLsrM0DdIuuRUA==} + + es6-promise-pool@2.5.0: + resolution: {integrity: sha512-VHErXfzR/6r/+yyzPKeBvO0lgjfC5cbDCQWjWwMZWSb6YU39TGIl51OUmCfWCq4ylMdJSB8zkz2vIuIeIxXApA==} + engines: {node: '>=0.10.0'} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fastdom@1.0.12: + resolution: {integrity: sha512-LB+xjSTEbjHE1cWsxu+tN2Xqr1kpi+V9aADI7sVM5ZMaXyYGPHULQMzpJMYqOTULK/73pUkWVzzObFRBkPr+hg==} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fill-range@7.1.1: + resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} + engines: {node: '>=8'} + + fractional-indexing@3.2.0: + resolution: {integrity: sha512-PcOxmqwYCW7O2ovKRU8OoQQj2yqTfEB/yeTYk4gPid6dN5ODRfU1hXd9tTVZzax/0NkO7AxpHykvZnT1aYp/BQ==} + engines: {node: ^14.13.1 || >=16.0.0} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + fuzzy@0.1.3: + resolution: {integrity: sha512-/gZffu4ykarLrCiP3Ygsa86UAo1E5vEVlvTrpkKywXSbP9Xhln3oSp9QSV57gEq3JFFpGJ4GZ+5zdEp3FcUh4w==} + engines: {node: '>= 0.6.0'} + + get-nonce@1.0.1: + resolution: {integrity: sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==} + engines: {node: '>=6'} + + glob-parent@5.1.2: + resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} + engines: {node: '>= 6'} + + glur@1.1.2: + resolution: {integrity: sha512-l+8esYHTKOx2G/Aao4lEQ0bnHWg4fWtJbVoZZT9Knxi01pB8C80BR85nONLFwkkQoFRCmXY+BUcGZN3yZ2QsRA==} + + hachure-fill@0.5.2: + resolution: {integrity: sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==} + + html-encoding-sniffer@7.0.0: + resolution: {integrity: sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==} + engines: {node: ^22.13.0 || >=24.0.0} + + iconv-lite@0.6.3: + resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} + engines: {node: '>=0.10.0'} + + image-blob-reduce@3.0.1: + resolution: {integrity: sha512-/VmmWgIryG/wcn4TVrV7cC4mlfUC/oyiKIfSg5eVM3Ten/c1c34RJhMYKCWTnoSMHSqXLt3tsrBR4Q2HInvN+Q==} + + immutable@4.3.9: + resolution: {integrity: sha512-ObHy4YN7ycwZOUCLI1/6svfyAFu7vL8RhAvVu/bh/RZW9EPlOyDaQ9jDQWCtdqzaXUjgXZCW1migtHE7YI7UGQ==} + + import-meta-resolve@4.2.0: + resolution: {integrity: sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==} + + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + + internmap@1.0.1: + resolution: {integrity: sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==} + + internmap@2.0.3: + resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==} + engines: {node: '>=12'} + + is-binary-path@2.1.0: + resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==} + engines: {node: '>=8'} + + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + + is-number@7.0.0: + resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} + engines: {node: '>=0.12.0'} + + is-potential-custom-element-name@1.0.1: + resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + jotai-scope@0.7.2: + resolution: {integrity: sha512-Gwed97f3dDObrO43++2lRcgOqw4O2sdr4JCjP/7eHK1oPACDJ7xKHGScpJX9XaflU+KBHXF+VhwECnzcaQiShg==} + peerDependencies: + jotai: '>=2.9.2' + react: '>=17.0.0' + + jotai@2.11.0: + resolution: {integrity: sha512-zKfoBBD1uDw3rljwHkt0fWuja1B76R7CjznuBO+mSX6jpsO1EBeWNRKpeaQho9yPI/pvCv4recGfgOXGxwPZvQ==} + engines: {node: '>=12.20.0'} + peerDependencies: + '@types/react': '>=17.0.0' + react: '>=17.0.0' + peerDependenciesMeta: + '@types/react': + optional: true + react: + optional: true + + jsdom@30.1.3: + resolution: {integrity: sha512-hQMUPvRgN7KxsfIytDQji7bimuJeRQa6Qo5+iuiZQk5CafeRxLIA10/cG5YCBFNpD9RO3oqIiN4CO1Y44kxqXg==} + engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0} + peerDependencies: + canvas: ^3.2.3 + peerDependenciesMeta: + canvas: + optional: true + + katex@0.16.47: + resolution: {integrity: sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg==} + hasBin: true + + khroma@2.1.0: + resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==} + + langium@3.3.1: + resolution: {integrity: sha512-QJv/h939gDpvT+9SiLVlY7tZC3xB2qK57v0J04Sh9wpMb6MP1q8gB21L3WIo8T5P1MSMg3Ep14L7KkDCFG3y4w==} + engines: {node: '>=16.0.0'} + + layout-base@1.0.2: + resolution: {integrity: sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==} + + layout-base@2.0.1: + resolution: {integrity: sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==} + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + lodash-es@4.17.21: + resolution: {integrity: sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==} + + lodash-es@4.18.1: + resolution: {integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==} + + lodash.debounce@4.0.8: + resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==} + + lodash.throttle@4.1.1: + resolution: {integrity: sha512-wIkUCfVKpVsWo3JSZlc+8MB5it+2AN5W8J7YVMST30UrvcQNZ1Okbj+rbVniijTWE6FGYy4XJq/rHkas8qJMLQ==} + + lru-cache@11.5.3: + resolution: {integrity: sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==} + engines: {node: 20 || >=22} + + magic-string@1.4.5: + resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} + + marked@16.4.2: + resolution: {integrity: sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA==} + engines: {node: '>= 20'} + hasBin: true + + mdn-data@2.27.1: + resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==} + + mermaid@11.17.2: + resolution: {integrity: sha512-V6K3C8EBdEsPFZXSKMJe6ppQOENxuHARr9GvHX4hh47lAbhMRD9qf4oEK7LoaRQxULMa80/qt5gHO73aCleBBg==} + + multimath@2.0.0: + resolution: {integrity: sha512-toRx66cAMJ+Ccz7pMIg38xSIrtnbozk0dchXezwQDMgQmbGpfxjtv68H+L00iFL8hxDaVjrmwAFSb3I6bg8Q2g==} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + nanoid@3.3.3: + resolution: {integrity: sha512-p1sjXuopFs0xg+fPASzQ28agW1oHD7xDsd9Xkf3T15H3c/cifrFHVwrh74PdoklAPi+i7MdRsE47vm2r6JoB+w==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + nanoid@4.0.2: + resolution: {integrity: sha512-7ZtY5KTCNheRGfEFxnedV5zFiORN1+Y1N6zvPTnHQd8ENUvfaDBeuJDZb2bN/oXwXxu3qkTXDzy57W5vAmDTBw==} + engines: {node: ^14 || ^16 || >=18} + hasBin: true + + normalize-path@3.0.0: + resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} + engines: {node: '>=0.10.0'} + + object-assign@4.1.1: + resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} + engines: {node: '>=0.10.0'} + + obug@3.0.0: + resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} + engines: {node: '>=12.20.0'} + + open-color@1.9.1: + resolution: {integrity: sha512-vCseG/EQ6/RcvxhUcGJiHViOgrtz4x0XbZepXvKik66TMGkvbmjeJrKFyBEx6daG5rNyyd14zYXhz0hZVwQFOw==} + + package-manager-detector@1.9.0: + resolution: {integrity: sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA==} + + pako@2.0.3: + resolution: {integrity: sha512-WjR1hOeg+kki3ZIOjaf4b5WVcay1jaliKSYiEaB1XzwhMQZJxRdQRv0V31EKBYlxb4T7SK3hjfc/jxyU64BoSw==} + + parse5@8.1.0: + resolution: {integrity: sha512-sq3qBFpee5jeocbFbO48VHlGr8sT7mbXS0vxlKN6sottBtJzrOG3998sr0llSZcQAGgfpdmEYAIZE0P9z0dE8w==} + + path-data-parser@0.1.0: + resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + perfect-freehand@1.2.0: + resolution: {integrity: sha512-h/0ikF1M3phW7CwpZ5MMvKnfpHficWoOEyr//KVNTxV4F6deRK1eYMtHyBKEAKFK0aXIEUK9oBvlF6PNXMDsAw==} + + pica@7.1.1: + resolution: {integrity: sha512-WY73tMvNzXWEld2LicT9Y260L43isrZ85tPuqRyvtkljSDLmnNFQmZICt4xUJMVulmcc6L9O7jbBrtx3DOz/YQ==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@2.3.2: + resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} + engines: {node: '>=8.6'} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + png-chunk-text@1.0.0: + resolution: {integrity: sha512-DEROKU3SkkLGWNMzru3xPVgxyd48UGuMSZvioErCure6yhOc/pRH2ZV+SEn7nmaf7WNf3NdIpH+UTrRdKyq9Lw==} + + png-chunks-encode@1.0.0: + resolution: {integrity: sha512-J1jcHgbQRsIIgx5wxW9UmCymV3wwn4qCCJl6KYgEU/yHCh/L2Mwq/nMOkRPtmV79TLxRZj5w3tH69pvygFkDqA==} + + png-chunks-extract@1.0.0: + resolution: {integrity: sha512-ZiVwF5EJ0DNZyzAqld8BP1qyJBaGOFaq9zl579qfbkcmOwWLLO4I9L8i2O4j3HkI6/35i0nKG2n+dZplxiT89Q==} + + points-on-curve@0.2.0: + resolution: {integrity: sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==} + + points-on-curve@1.0.1: + resolution: {integrity: sha512-3nmX4/LIiyuwGLwuUrfhTlDeQFlAhi7lyK/zcRNGhalwapDWgAGR82bUpmn2mA03vII3fvNCG8jAONzKXwpxAg==} + + points-on-path@0.2.1: + resolution: {integrity: sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==} + + postcss@8.5.32: + resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} + engines: {node: ^10 || ^12 || >=14} + + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + + pwacompat@2.0.17: + resolution: {integrity: sha512-6Du7IZdIy7cHiv7AhtDy4X2QRM8IAD5DII69mt5qWibC2d15ZU8DmBG1WdZKekG11cChSu4zkSUGPF9sweOl6w==} + + react-dom@19.3.1: + resolution: {integrity: sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==} + peerDependencies: + react: ^19.3.1 + + react-remove-scroll-bar@2.3.8: + resolution: {integrity: sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==} + engines: {node: '>=10'} + peerDependencies: + '@types/react': '*' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + + react-remove-scroll@2.7.2: + resolution: {integrity: sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==} + engines: {node: '>=10'} + peerDependencies: + '@types/react': '*' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + react-style-singleton@2.2.3: + resolution: {integrity: sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==} + engines: {node: '>=10'} + peerDependencies: + '@types/react': '*' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + react@19.3.1: + resolution: {integrity: sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==} + engines: {node: '>=0.10.0'} + + readdirp@3.6.0: + resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} + engines: {node: '>=8.10.0'} + + require-from-string@2.0.2: + resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} + engines: {node: '>=0.10.0'} + + robust-predicates@3.0.3: + resolution: {integrity: sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==} + + rolldown@1.2.16: + resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + roughjs@4.6.4: + resolution: {integrity: sha512-s6EZ0BntezkFYMf/9mGn7M8XGIoaav9QQBCnJROWB3brUWQ683Q2LbRD/hq0Z3bAJ/9NVpU/5LpiTWvQMyLDhw==} + + roughjs@4.6.6: + resolution: {integrity: sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==} + + rw@1.3.3: + resolution: {integrity: sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==} + + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + + sass@1.51.0: + resolution: {integrity: sha512-haGdpTgywJTvHC2b91GSq+clTKGbtkkZmVAb82jZQN/wTy6qs8DdFm2lhEQbEwrY0QDRgSQ3xDurqM977C3noA==} + engines: {node: '>=12.0.0'} + hasBin: true + + saxes@6.0.0: + resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} + engines: {node: '>=v12.22.7'} + + scheduler@0.28.0: + resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==} + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + sliced@1.0.1: + resolution: {integrity: sha512-VZBmZP8WU3sMOZm1bdgTadsQbcscK0UM8oKxKVBs4XAhUo2Xxzm/OFMGBkPusxw9xL3Uy8LrzEqGqJhclsr0yA==} + deprecated: Unsupported + + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} + engines: {node: '>=0.10.0'} + + std-env@4.3.0: + resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + + strictdom@1.0.1: + resolution: {integrity: sha512-cEmp9QeXXRmjj/rVp9oyiqcvyocWab/HaoN4+bwFeZ7QzykJD6L3yD4v12K1x0tHpqRqVpJevN3gW7kyM39Bqg==} + + stylis@4.4.0: + resolution: {integrity: sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA==} + + tinybench@6.2.3: + resolution: {integrity: sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==} + engines: {node: '>=20.0.0'} + + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tldts-core@7.4.20: + resolution: {integrity: sha512-C630TWXZCZmLq0F2bW4QqwnaaxCQ/svpAqvJwnC4JvgEM5ohhBnGsEzTLSOXcN+xjz+kEaHS5uoWIw2klnqd0A==} + + tldts@7.4.19: + resolution: {integrity: sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q==} + hasBin: true + + to-regex-range@5.0.1: + resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} + engines: {node: '>=8.0'} + + tough-cookie@6.0.2: + resolution: {integrity: sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==} + engines: {node: '>=16'} + + tr46@7.0.0: + resolution: {integrity: sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==} + engines: {node: ^22.14.0 || >=24.0.0} + + ts-dedent@2.3.0: + resolution: {integrity: sha512-JfJeIHke7y2egdGGgRAvpCwYFUsHlM2gPcrVOxFkznt/4uzQ7HFmvE63iFHVLBJNDuyDOQgijDK/tXH/f6Msjg==} + engines: {node: '>=6.10'} + + tslib@2.9.1: + resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==} + + tunnel-rat@0.1.2: + resolution: {integrity: sha512-lR5VHmkPhzdhrM092lI2nACsLO4QubF0/yoOhzX7c+wIpbN1GjHNzCc91QlpxBi+cnx8vVJ+Ur6vL5cEoQPFpQ==} + + typescript@6.0.3: + resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@8.9.0: + resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} + + undici@8.12.3: + resolution: {integrity: sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==} + engines: {node: '>=22.19.0'} + + use-callback-ref@1.3.3: + resolution: {integrity: sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==} + engines: {node: '>=10'} + peerDependencies: + '@types/react': '*' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + use-sidecar@1.1.3: + resolution: {integrity: sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==} + engines: {node: '>=10'} + peerDependencies: + '@types/react': '*' + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + + use-sync-external-store@1.7.0: + resolution: {integrity: sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==} + peerDependencies: + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + + uuid@14.0.3: + resolution: {integrity: sha512-Sc5u1VVln93y1Xnz4R+CunOZc7R9LUcTmhj7Rc7Eg3HVcf7rVn2FOoa812fe0W8p3jD7xeoGSYbfqCGGH2B6xw==} + hasBin: true + + vite@8.3.5: + resolution: {integrity: sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.7.1 || ^0.8.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@5.0.5: + resolution: {integrity: sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==} + engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 5.0.5 + '@vitest/browser-preview': 5.0.5 + '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 + '@vitest/coverage-istanbul': 5.0.5 + '@vitest/coverage-v8': 5.0.5 + '@vitest/ui': 5.0.5 + happy-dom: '*' + jsdom: '*' + vite: ^6.4.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + vscode-jsonrpc@8.2.0: + resolution: {integrity: sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==} + engines: {node: '>=14.0.0'} + + vscode-languageserver-protocol@3.17.5: + resolution: {integrity: sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==} + + vscode-languageserver-textdocument@1.0.16: + resolution: {integrity: sha512-qeNEuOi9a3qkqRf7Gfez2WL2VwlBTLCNekHBGO9kxPVUp9XuY15yfTJ9jwvOwKI0I2MhUUfZq95NSp+LK1CLQg==} + + vscode-languageserver-types@3.17.5: + resolution: {integrity: sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==} + + vscode-languageserver@9.0.1: + resolution: {integrity: sha512-woByF3PDpkHFUreUa7Hos7+pUWdeWMXRd26+ZX2A8cFx6v/JPTtd4/uN0/jB6XQHYaOlHbio03NTHCqrgG5n7g==} + hasBin: true + + vscode-uri@3.0.8: + resolution: {integrity: sha512-AyFQ0EVmsOZOlAnxoFOGOq1SQDWAB7C6aqMGS23svWAllfOaxbuFvcT8D1i8z3Gyn8fraVeZNNmN6e9bxxXkKw==} + + w3c-xmlserializer@6.0.0: + resolution: {integrity: sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==} + engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0} + + webidl-conversions@8.0.1: + resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==} + engines: {node: '>=20'} + + webworkify@1.5.0: + resolution: {integrity: sha512-AMcUeyXAhbACL8S2hqqdqOLqvJ8ylmIbNwUIqQujRSouf4+eUFaXbG6F1Rbu+srlJMmxQWsiU7mOJi0nMBfM1g==} + + whatwg-mimetype@5.0.0: + resolution: {integrity: sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==} + engines: {node: '>=20'} + + whatwg-url@17.3.0: + resolution: {integrity: sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==} + engines: {node: ^22.14.0 || >=24.0.0} + + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + + why-is-node-running@3.2.1: + resolution: {integrity: sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==} + engines: {node: '>=20.11'} + hasBin: true + + xml-name-validator@5.0.0: + resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==} + engines: {node: '>=18'} + + xmlchars@2.2.0: + resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + + zustand@4.5.7: + resolution: {integrity: sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==} + engines: {node: '>=12.7.0'} + peerDependencies: + '@types/react': '>=16.8' + immer: '>=9.0.6' + react: '>=16.8' + peerDependenciesMeta: + '@types/react': + optional: true + immer: + optional: true + react: + optional: true + +snapshots: + + '@antfu/install-pkg@2.1.0': + dependencies: + package-manager-detector: 1.9.0 + tinyexec: 1.3.1 + + '@asamuzakjp/css-color@7.1.9': + dependencies: + '@csstools/css-calc': 3.4.3(@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2))(@csstools/css-tokenizer@4.0.2) + '@csstools/css-color-parser': 4.2.7(@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2))(@csstools/css-tokenizer@4.0.2) + '@csstools/css-parser-algorithms': 4.0.2(@csstools/css-tokenizer@4.0.2) + '@csstools/css-tokenizer': 4.0.2 + lru-cache: 11.5.3 + + '@asamuzakjp/dom-selector@10.0.5': + dependencies: + bidi-js: 1.1.0 + css-tree: 3.2.1 + is-potential-custom-element-name: 1.0.1 + lru-cache: 11.5.3 + + '@babel/runtime@7.29.10': {} + + '@braintree/sanitize-url@6.0.2': {} + + '@braintree/sanitize-url@7.1.2': {} + + '@bramus/specificity@2.4.3': + dependencies: + css-tree: 3.2.1 + + '@chevrotain/cst-dts-gen@11.0.3': + dependencies: + '@chevrotain/gast': 11.0.3 + '@chevrotain/types': 11.0.3 + lodash-es: 4.17.21 + + '@chevrotain/gast@11.0.3': + dependencies: + '@chevrotain/types': 11.0.3 + lodash-es: 4.17.21 + + '@chevrotain/regexp-to-ast@11.0.3': {} + + '@chevrotain/types@11.0.3': {} + + '@chevrotain/types@11.1.2': {} + + '@chevrotain/utils@11.0.3': {} + + '@csstools/color-helpers@6.1.2': {} + + '@csstools/css-calc@3.4.3(@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2))(@csstools/css-tokenizer@4.0.2)': + dependencies: + '@csstools/css-parser-algorithms': 4.0.2(@csstools/css-tokenizer@4.0.2) + '@csstools/css-tokenizer': 4.0.2 + + '@csstools/css-color-parser@4.2.7(@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2))(@csstools/css-tokenizer@4.0.2)': + dependencies: + '@csstools/color-helpers': 6.1.2 + '@csstools/css-calc': 3.4.3(@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2))(@csstools/css-tokenizer@4.0.2) + '@csstools/css-parser-algorithms': 4.0.2(@csstools/css-tokenizer@4.0.2) + '@csstools/css-tokenizer': 4.0.2 + + '@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2)': + dependencies: + '@csstools/css-tokenizer': 4.0.2 + + '@csstools/css-syntax-patches-for-csstree@1.1.16(css-tree@3.2.1)': + optionalDependencies: + css-tree: 3.2.1 + + '@csstools/css-tokenizer@4.0.2': {} + + '@excalidraw/excalidraw@0.18.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@braintree/sanitize-url': 6.0.2 + '@excalidraw/laser-pointer': 1.3.1 + '@excalidraw/mermaid-to-excalidraw': 2.2.2 + '@excalidraw/random-username': 1.1.0 + '@radix-ui/react-popover': 1.1.6(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-tabs': 1.0.2(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + browser-fs-access: 0.29.1 + canvas-roundrect-polyfill: 0.0.1 + clsx: 1.1.1 + cross-env: 7.0.3 + es6-promise-pool: 2.5.0 + fractional-indexing: 3.2.0 + fuzzy: 0.1.3 + image-blob-reduce: 3.0.1 + jotai: 2.11.0(@types/react@19.3.0)(react@19.3.1) + jotai-scope: 0.7.2(jotai@2.11.0(@types/react@19.3.0)(react@19.3.1))(react@19.3.1) + lodash.debounce: 4.0.8 + lodash.throttle: 4.1.1 + nanoid: 3.3.3 + open-color: 1.9.1 + pako: 2.0.3 + perfect-freehand: 1.2.0 + pica: 7.1.1 + png-chunk-text: 1.0.0 + png-chunks-encode: 1.0.0 + png-chunks-extract: 1.0.0 + points-on-curve: 1.0.1 + pwacompat: 2.0.17 + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + roughjs: 4.6.4 + sass: 1.51.0 + tunnel-rat: 0.1.2(@types/react@19.3.0)(react@19.3.1) + transitivePeerDependencies: + - '@types/react' + - '@types/react-dom' + - immer + + '@excalidraw/laser-pointer@1.3.1': {} + + '@excalidraw/markdown-to-text@0.1.2': {} + + '@excalidraw/mermaid-to-excalidraw@2.2.2': + dependencies: + '@excalidraw/markdown-to-text': 0.1.2 + '@mermaid-js/parser': 0.6.3 + mermaid: 11.17.2 + nanoid: 4.0.2 + + '@excalidraw/random-username@1.1.0': {} + + '@exodus/bytes@1.16.0': {} + + '@floating-ui/core@1.8.0': + dependencies: + '@floating-ui/utils': 0.2.12 + + '@floating-ui/dom@1.8.0': + dependencies: + '@floating-ui/core': 1.8.0 + '@floating-ui/utils': 0.2.12 + + '@floating-ui/react-dom@2.1.9(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@floating-ui/dom': 1.8.0 + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + + '@floating-ui/utils@0.2.12': {} + + '@iconify/types@2.0.0': {} + + '@iconify/utils@3.1.7': + dependencies: + '@antfu/install-pkg': 2.1.0 + '@iconify/types': 2.0.0 + import-meta-resolve: 4.2.0 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@mermaid-js/parser@0.6.3': + dependencies: + langium: 3.3.1 + + '@mermaid-js/parser@1.2.1': + dependencies: + '@chevrotain/types': 11.1.2 + + '@oxc-project/types@0.156.0': {} + + '@radix-ui/primitive@1.0.0': + dependencies: + '@babel/runtime': 7.29.10 + + '@radix-ui/primitive@1.1.1': {} + + '@radix-ui/react-arrow@1.1.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@radix-ui/react-primitive': 2.0.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + optionalDependencies: + '@types/react': 19.3.0 + '@types/react-dom': 19.3.0(@types/react@19.3.0) + + '@radix-ui/react-collection@1.0.1(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@babel/runtime': 7.29.10 + '@radix-ui/react-compose-refs': 1.0.0(react@19.3.1) + '@radix-ui/react-context': 1.0.0(react@19.3.1) + '@radix-ui/react-primitive': 1.0.1(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-slot': 1.0.1(react@19.3.1) + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + + '@radix-ui/react-compose-refs@1.0.0(react@19.3.1)': + dependencies: + '@babel/runtime': 7.29.10 + react: 19.3.1 + + '@radix-ui/react-compose-refs@1.1.1(@types/react@19.3.0)(react@19.3.1)': + dependencies: + react: 19.3.1 + optionalDependencies: + '@types/react': 19.3.0 + + '@radix-ui/react-context@1.0.0(react@19.3.1)': + dependencies: + '@babel/runtime': 7.29.10 + react: 19.3.1 + + '@radix-ui/react-context@1.1.1(@types/react@19.3.0)(react@19.3.1)': + dependencies: + react: 19.3.1 + optionalDependencies: + '@types/react': 19.3.0 + + '@radix-ui/react-direction@1.0.0(react@19.3.1)': + dependencies: + '@babel/runtime': 7.29.10 + react: 19.3.1 + + '@radix-ui/react-dismissable-layer@1.1.5(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@radix-ui/primitive': 1.1.1 + '@radix-ui/react-compose-refs': 1.1.1(@types/react@19.3.0)(react@19.3.1) + '@radix-ui/react-primitive': 2.0.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-use-callback-ref': 1.1.0(@types/react@19.3.0)(react@19.3.1) + '@radix-ui/react-use-escape-keydown': 1.1.0(@types/react@19.3.0)(react@19.3.1) + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + optionalDependencies: + '@types/react': 19.3.0 + '@types/react-dom': 19.3.0(@types/react@19.3.0) + + '@radix-ui/react-focus-guards@1.1.1(@types/react@19.3.0)(react@19.3.1)': + dependencies: + react: 19.3.1 + optionalDependencies: + '@types/react': 19.3.0 + + '@radix-ui/react-focus-scope@1.1.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@radix-ui/react-compose-refs': 1.1.1(@types/react@19.3.0)(react@19.3.1) + '@radix-ui/react-primitive': 2.0.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-use-callback-ref': 1.1.0(@types/react@19.3.0)(react@19.3.1) + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + optionalDependencies: + '@types/react': 19.3.0 + '@types/react-dom': 19.3.0(@types/react@19.3.0) + + '@radix-ui/react-id@1.0.0(react@19.3.1)': + dependencies: + '@babel/runtime': 7.29.10 + '@radix-ui/react-use-layout-effect': 1.0.0(react@19.3.1) + react: 19.3.1 + + '@radix-ui/react-id@1.1.0(@types/react@19.3.0)(react@19.3.1)': + dependencies: + '@radix-ui/react-use-layout-effect': 1.1.0(@types/react@19.3.0)(react@19.3.1) + react: 19.3.1 + optionalDependencies: + '@types/react': 19.3.0 + + '@radix-ui/react-popover@1.1.6(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@radix-ui/primitive': 1.1.1 + '@radix-ui/react-compose-refs': 1.1.1(@types/react@19.3.0)(react@19.3.1) + '@radix-ui/react-context': 1.1.1(@types/react@19.3.0)(react@19.3.1) + '@radix-ui/react-dismissable-layer': 1.1.5(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-focus-guards': 1.1.1(@types/react@19.3.0)(react@19.3.1) + '@radix-ui/react-focus-scope': 1.1.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-id': 1.1.0(@types/react@19.3.0)(react@19.3.1) + '@radix-ui/react-popper': 1.2.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-portal': 1.1.4(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-presence': 1.1.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-primitive': 2.0.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-slot': 1.1.2(@types/react@19.3.0)(react@19.3.1) + '@radix-ui/react-use-controllable-state': 1.1.0(@types/react@19.3.0)(react@19.3.1) + aria-hidden: 1.2.6 + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + react-remove-scroll: 2.7.2(@types/react@19.3.0)(react@19.3.1) + optionalDependencies: + '@types/react': 19.3.0 + '@types/react-dom': 19.3.0(@types/react@19.3.0) + + '@radix-ui/react-popper@1.2.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@floating-ui/react-dom': 2.1.9(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-arrow': 1.1.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-compose-refs': 1.1.1(@types/react@19.3.0)(react@19.3.1) + '@radix-ui/react-context': 1.1.1(@types/react@19.3.0)(react@19.3.1) + '@radix-ui/react-primitive': 2.0.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-use-callback-ref': 1.1.0(@types/react@19.3.0)(react@19.3.1) + '@radix-ui/react-use-layout-effect': 1.1.0(@types/react@19.3.0)(react@19.3.1) + '@radix-ui/react-use-rect': 1.1.0(@types/react@19.3.0)(react@19.3.1) + '@radix-ui/react-use-size': 1.1.0(@types/react@19.3.0)(react@19.3.1) + '@radix-ui/rect': 1.1.0 + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + optionalDependencies: + '@types/react': 19.3.0 + '@types/react-dom': 19.3.0(@types/react@19.3.0) + + '@radix-ui/react-portal@1.1.4(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@radix-ui/react-primitive': 2.0.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-use-layout-effect': 1.1.0(@types/react@19.3.0)(react@19.3.1) + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + optionalDependencies: + '@types/react': 19.3.0 + '@types/react-dom': 19.3.0(@types/react@19.3.0) + + '@radix-ui/react-presence@1.0.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@babel/runtime': 7.29.10 + '@radix-ui/react-compose-refs': 1.0.0(react@19.3.1) + '@radix-ui/react-use-layout-effect': 1.0.0(react@19.3.1) + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + + '@radix-ui/react-presence@1.1.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@radix-ui/react-compose-refs': 1.1.1(@types/react@19.3.0)(react@19.3.1) + '@radix-ui/react-use-layout-effect': 1.1.0(@types/react@19.3.0)(react@19.3.1) + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + optionalDependencies: + '@types/react': 19.3.0 + '@types/react-dom': 19.3.0(@types/react@19.3.0) + + '@radix-ui/react-primitive@1.0.1(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@babel/runtime': 7.29.10 + '@radix-ui/react-slot': 1.0.1(react@19.3.1) + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + + '@radix-ui/react-primitive@2.0.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@radix-ui/react-slot': 1.1.2(@types/react@19.3.0)(react@19.3.1) + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + optionalDependencies: + '@types/react': 19.3.0 + '@types/react-dom': 19.3.0(@types/react@19.3.0) + + '@radix-ui/react-roving-focus@1.0.2(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@babel/runtime': 7.29.10 + '@radix-ui/primitive': 1.0.0 + '@radix-ui/react-collection': 1.0.1(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-compose-refs': 1.0.0(react@19.3.1) + '@radix-ui/react-context': 1.0.0(react@19.3.1) + '@radix-ui/react-direction': 1.0.0(react@19.3.1) + '@radix-ui/react-id': 1.0.0(react@19.3.1) + '@radix-ui/react-primitive': 1.0.1(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-use-callback-ref': 1.0.0(react@19.3.1) + '@radix-ui/react-use-controllable-state': 1.0.0(react@19.3.1) + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + + '@radix-ui/react-slot@1.0.1(react@19.3.1)': + dependencies: + '@babel/runtime': 7.29.10 + '@radix-ui/react-compose-refs': 1.0.0(react@19.3.1) + react: 19.3.1 + + '@radix-ui/react-slot@1.1.2(@types/react@19.3.0)(react@19.3.1)': + dependencies: + '@radix-ui/react-compose-refs': 1.1.1(@types/react@19.3.0)(react@19.3.1) + react: 19.3.1 + optionalDependencies: + '@types/react': 19.3.0 + + '@radix-ui/react-tabs@1.0.2(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@babel/runtime': 7.29.10 + '@radix-ui/primitive': 1.0.0 + '@radix-ui/react-context': 1.0.0(react@19.3.1) + '@radix-ui/react-direction': 1.0.0(react@19.3.1) + '@radix-ui/react-id': 1.0.0(react@19.3.1) + '@radix-ui/react-presence': 1.0.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-primitive': 1.0.1(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-roving-focus': 1.0.2(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@radix-ui/react-use-controllable-state': 1.0.0(react@19.3.1) + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + + '@radix-ui/react-use-callback-ref@1.0.0(react@19.3.1)': + dependencies: + '@babel/runtime': 7.29.10 + react: 19.3.1 + + '@radix-ui/react-use-callback-ref@1.1.0(@types/react@19.3.0)(react@19.3.1)': + dependencies: + react: 19.3.1 + optionalDependencies: + '@types/react': 19.3.0 + + '@radix-ui/react-use-controllable-state@1.0.0(react@19.3.1)': + dependencies: + '@babel/runtime': 7.29.10 + '@radix-ui/react-use-callback-ref': 1.0.0(react@19.3.1) + react: 19.3.1 + + '@radix-ui/react-use-controllable-state@1.1.0(@types/react@19.3.0)(react@19.3.1)': + dependencies: + '@radix-ui/react-use-callback-ref': 1.1.0(@types/react@19.3.0)(react@19.3.1) + react: 19.3.1 + optionalDependencies: + '@types/react': 19.3.0 + + '@radix-ui/react-use-escape-keydown@1.1.0(@types/react@19.3.0)(react@19.3.1)': + dependencies: + '@radix-ui/react-use-callback-ref': 1.1.0(@types/react@19.3.0)(react@19.3.1) + react: 19.3.1 + optionalDependencies: + '@types/react': 19.3.0 + + '@radix-ui/react-use-layout-effect@1.0.0(react@19.3.1)': + dependencies: + '@babel/runtime': 7.29.10 + react: 19.3.1 + + '@radix-ui/react-use-layout-effect@1.1.0(@types/react@19.3.0)(react@19.3.1)': + dependencies: + react: 19.3.1 + optionalDependencies: + '@types/react': 19.3.0 + + '@radix-ui/react-use-rect@1.1.0(@types/react@19.3.0)(react@19.3.1)': + dependencies: + '@radix-ui/rect': 1.1.0 + react: 19.3.1 + optionalDependencies: + '@types/react': 19.3.0 + + '@radix-ui/react-use-size@1.1.0(@types/react@19.3.0)(react@19.3.1)': + dependencies: + '@radix-ui/react-use-layout-effect': 1.1.0(@types/react@19.3.0)(react@19.3.1) + react: 19.3.1 + optionalDependencies: + '@types/react': 19.3.0 + + '@radix-ui/rect@1.1.0': {} + + '@rolldown/binding-android-arm-eabi@1.2.16': + optional: true + + '@rolldown/binding-android-arm64@1.2.16': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.16': + optional: true + + '@rolldown/binding-darwin-x64@1.2.16': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.16': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.16': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.16': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.16': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.16': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.16': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/d3-array@3.2.2': {} + + '@types/d3-axis@3.0.6': + dependencies: + '@types/d3-selection': 3.0.12 + + '@types/d3-brush@3.0.6': + dependencies: + '@types/d3-selection': 3.0.12 + + '@types/d3-chord@3.0.6': {} + + '@types/d3-color@3.1.3': {} + + '@types/d3-contour@3.0.6': + dependencies: + '@types/d3-array': 3.2.2 + '@types/geojson': 7946.0.16 + + '@types/d3-delaunay@6.0.4': {} + + '@types/d3-dispatch@3.0.7': {} + + '@types/d3-drag@3.0.7': + dependencies: + '@types/d3-selection': 3.0.12 + + '@types/d3-dsv@3.0.7': {} + + '@types/d3-ease@3.0.2': {} + + '@types/d3-fetch@3.0.7': + dependencies: + '@types/d3-dsv': 3.0.7 + + '@types/d3-force@3.0.10': {} + + '@types/d3-format@3.0.4': {} + + '@types/d3-geo@3.1.1': + dependencies: + '@types/geojson': 7946.0.16 + + '@types/d3-hierarchy@3.1.7': {} + + '@types/d3-interpolate@3.0.4': + dependencies: + '@types/d3-color': 3.1.3 + + '@types/d3-path@3.1.1': {} + + '@types/d3-polygon@3.0.2': {} + + '@types/d3-quadtree@3.0.6': {} + + '@types/d3-random@3.0.4': {} + + '@types/d3-scale-chromatic@3.1.0': {} + + '@types/d3-scale@4.0.9': + dependencies: + '@types/d3-time': 3.0.4 + + '@types/d3-selection@3.0.12': {} + + '@types/d3-shape@3.2.0': + dependencies: + '@types/d3-path': 3.1.1 + + '@types/d3-time-format@4.0.3': {} + + '@types/d3-time@3.0.4': {} + + '@types/d3-timer@3.0.2': {} + + '@types/d3-transition@3.0.9': + dependencies: + '@types/d3-selection': 3.0.12 + + '@types/d3-zoom@3.0.9': + dependencies: + '@types/d3-interpolate': 3.0.4 + '@types/d3-selection': 3.0.12 + + '@types/d3@7.4.3': + dependencies: + '@types/d3-array': 3.2.2 + '@types/d3-axis': 3.0.6 + '@types/d3-brush': 3.0.6 + '@types/d3-chord': 3.0.6 + '@types/d3-color': 3.1.3 + '@types/d3-contour': 3.0.6 + '@types/d3-delaunay': 6.0.4 + '@types/d3-dispatch': 3.0.7 + '@types/d3-drag': 3.0.7 + '@types/d3-dsv': 3.0.7 + '@types/d3-ease': 3.0.2 + '@types/d3-fetch': 3.0.7 + '@types/d3-force': 3.0.10 + '@types/d3-format': 3.0.4 + '@types/d3-geo': 3.1.1 + '@types/d3-hierarchy': 3.1.7 + '@types/d3-interpolate': 3.0.4 + '@types/d3-path': 3.1.1 + '@types/d3-polygon': 3.0.2 + '@types/d3-quadtree': 3.0.6 + '@types/d3-random': 3.0.4 + '@types/d3-scale': 4.0.9 + '@types/d3-scale-chromatic': 3.1.0 + '@types/d3-selection': 3.0.12 + '@types/d3-shape': 3.2.0 + '@types/d3-time': 3.0.4 + '@types/d3-time-format': 4.0.3 + '@types/d3-timer': 3.0.2 + '@types/d3-transition': 3.0.9 + '@types/d3-zoom': 3.0.9 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.10': {} + + '@types/geojson@7946.0.16': {} + + '@types/node@26.6.6': + dependencies: + undici-types: 8.9.0 + + '@types/react-dom@19.3.0(@types/react@19.3.0)': + dependencies: + '@types/react': 19.3.0 + + '@types/react@19.3.0': + dependencies: + csstype: 3.2.3 + + '@types/trusted-types@2.0.7': + optional: true + + '@upsetjs/venn.js@2.0.0': + optionalDependencies: + d3-selection: 3.0.0 + d3-transition: 3.0.1(d3-selection@3.0.0) + + '@vitejs/plugin-react@6.1.2(vite@8.3.5(@types/node@26.6.6))': + dependencies: + '@rolldown/pluginutils': 1.0.1 + vite: 8.3.5(@types/node@26.6.6) + + '@vitest/mocker@5.0.5(vite@8.3.5(@types/node@26.6.6))': + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@vitest/spy': 5.0.5 + estree-walker: 3.0.3 + magic-string: 1.4.5 + optionalDependencies: + vite: 8.3.5(@types/node@26.6.6) + + '@vitest/spy@5.0.5': {} + + anymatch@3.1.3: + dependencies: + normalize-path: 3.0.0 + picomatch: 2.3.2 + + aria-hidden@1.2.6: + dependencies: + tslib: 2.9.1 + + assertion-error@2.0.1: {} + + bidi-js@1.1.0: + dependencies: + require-from-string: 2.0.2 + + binary-extensions@2.3.0: {} + + braces@3.0.3: + dependencies: + fill-range: 7.1.1 + + browser-fs-access@0.29.1: {} + + canvas-roundrect-polyfill@0.0.1: {} + + chai@6.3.0: {} + + chevrotain-allstar@0.3.1(chevrotain@11.0.3): + dependencies: + chevrotain: 11.0.3 + lodash-es: 4.18.1 + + chevrotain@11.0.3: + dependencies: + '@chevrotain/cst-dts-gen': 11.0.3 + '@chevrotain/gast': 11.0.3 + '@chevrotain/regexp-to-ast': 11.0.3 + '@chevrotain/types': 11.0.3 + '@chevrotain/utils': 11.0.3 + lodash-es: 4.17.21 + + chokidar@3.6.0: + dependencies: + anymatch: 3.1.3 + braces: 3.0.3 + glob-parent: 5.1.2 + is-binary-path: 2.1.0 + is-glob: 4.0.3 + normalize-path: 3.0.0 + readdirp: 3.6.0 + optionalDependencies: + fsevents: 2.3.3 + + clsx@1.1.1: {} + + commander@7.2.0: {} + + commander@8.3.0: {} + + cose-base@1.0.3: + dependencies: + layout-base: 1.0.2 + + cose-base@2.2.0: + dependencies: + layout-base: 2.0.1 + + crc-32@0.3.0: {} + + cross-env@7.0.3: + dependencies: + cross-spawn: 7.0.6 + + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + + css-tree@3.2.1: + dependencies: + mdn-data: 2.27.1 + source-map-js: 1.2.2 + + csstype@3.2.3: {} + + cytoscape-cose-bilkent@4.1.0(cytoscape@3.34.4): + dependencies: + cose-base: 1.0.3 + cytoscape: 3.34.4 + + cytoscape-fcose@2.2.0(cytoscape@3.34.4): + dependencies: + cose-base: 2.2.0 + cytoscape: 3.34.4 + + cytoscape@3.34.4: {} + + d3-array@2.12.1: + dependencies: + internmap: 1.0.1 + + d3-array@3.2.4: + dependencies: + internmap: 2.0.3 + + d3-axis@3.0.0: {} + + d3-brush@3.0.0: + dependencies: + d3-dispatch: 3.0.1 + d3-drag: 3.0.0 + d3-interpolate: 3.0.1 + d3-selection: 3.0.0 + d3-transition: 3.0.1(d3-selection@3.0.0) + + d3-chord@3.0.1: + dependencies: + d3-path: 3.1.0 + + d3-color@3.1.0: {} + + d3-contour@4.0.2: + dependencies: + d3-array: 3.2.4 + + d3-delaunay@6.0.4: + dependencies: + delaunator: 5.1.0 + + d3-dispatch@3.0.1: {} + + d3-drag@3.0.0: + dependencies: + d3-dispatch: 3.0.1 + d3-selection: 3.0.0 + + d3-dsv@3.0.1: + dependencies: + commander: 7.2.0 + iconv-lite: 0.6.3 + rw: 1.3.3 + + d3-ease@3.0.1: {} + + d3-fetch@3.0.1: + dependencies: + d3-dsv: 3.0.1 + + d3-force@3.0.0: + dependencies: + d3-dispatch: 3.0.1 + d3-quadtree: 3.0.1 + d3-timer: 3.0.1 + + d3-format@3.1.2: {} + + d3-geo@3.1.1: + dependencies: + d3-array: 3.2.4 + + d3-hierarchy@3.1.2: {} + + d3-interpolate@3.0.1: + dependencies: + d3-color: 3.1.0 + + d3-path@1.0.9: {} + + d3-path@3.1.0: {} + + d3-polygon@3.0.1: {} + + d3-quadtree@3.0.1: {} + + d3-random@3.0.1: {} + + d3-sankey@0.12.3: + dependencies: + d3-array: 2.12.1 + d3-shape: 1.3.7 + + d3-scale-chromatic@3.1.0: + dependencies: + d3-color: 3.1.0 + d3-interpolate: 3.0.1 + + d3-scale@4.0.2: + dependencies: + d3-array: 3.2.4 + d3-format: 3.1.2 + d3-interpolate: 3.0.1 + d3-time: 3.1.0 + d3-time-format: 4.1.0 + + d3-selection@3.0.0: {} + + d3-shape@1.3.7: + dependencies: + d3-path: 1.0.9 + + d3-shape@3.2.0: + dependencies: + d3-path: 3.1.0 + + d3-time-format@4.1.0: + dependencies: + d3-time: 3.1.0 + + d3-time@3.1.0: + dependencies: + d3-array: 3.2.4 + + d3-timer@3.0.1: {} + + d3-transition@3.0.1(d3-selection@3.0.0): + dependencies: + d3-color: 3.1.0 + d3-dispatch: 3.0.1 + d3-ease: 3.0.1 + d3-interpolate: 3.0.1 + d3-selection: 3.0.0 + d3-timer: 3.0.1 + + d3-zoom@3.0.0: + dependencies: + d3-dispatch: 3.0.1 + d3-drag: 3.0.0 + d3-interpolate: 3.0.1 + d3-selection: 3.0.0 + d3-transition: 3.0.1(d3-selection@3.0.0) + + d3@7.9.0: + dependencies: + d3-array: 3.2.4 + d3-axis: 3.0.0 + d3-brush: 3.0.0 + d3-chord: 3.0.1 + d3-color: 3.1.0 + d3-contour: 4.0.2 + d3-delaunay: 6.0.4 + d3-dispatch: 3.0.1 + d3-drag: 3.0.0 + d3-dsv: 3.0.1 + d3-ease: 3.0.1 + d3-fetch: 3.0.1 + d3-force: 3.0.0 + d3-format: 3.1.2 + d3-geo: 3.1.1 + d3-hierarchy: 3.1.2 + d3-interpolate: 3.0.1 + d3-path: 3.1.0 + d3-polygon: 3.0.1 + d3-quadtree: 3.0.1 + d3-random: 3.0.1 + d3-scale: 4.0.2 + d3-scale-chromatic: 3.1.0 + d3-selection: 3.0.0 + d3-shape: 3.2.0 + d3-time: 3.1.0 + d3-time-format: 4.1.0 + d3-timer: 3.0.1 + d3-transition: 3.0.1(d3-selection@3.0.0) + d3-zoom: 3.0.0 + + dagre-d3-es@7.0.14: + dependencies: + d3: 7.9.0 + lodash-es: 4.18.1 + + data-urls@8.0.0: + dependencies: + whatwg-mimetype: 5.0.0 + whatwg-url: 17.3.0 + transitivePeerDependencies: + - '@noble/hashes' + + dayjs@1.11.23: {} + + decimal.js@10.6.0: {} + + delaunator@5.1.0: + dependencies: + robust-predicates: 3.0.3 + + detect-libc@2.1.2: {} + + detect-node-es@1.1.0: {} + + dompurify@3.4.17: + optionalDependencies: + '@types/trusted-types': 2.0.7 + + entities@9.0.0: {} + + es-module-lexer@2.3.2: {} + + es-toolkit@1.53.1: {} + + es6-promise-pool@2.5.0: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.10 + + expect-type@1.4.0: {} + + fastdom@1.0.12: + dependencies: + strictdom: 1.0.1 + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + fill-range@7.1.1: + dependencies: + to-regex-range: 5.0.1 + + fractional-indexing@3.2.0: {} + + fsevents@2.3.3: + optional: true + + fuzzy@0.1.3: {} + + get-nonce@1.0.1: {} + + glob-parent@5.1.2: + dependencies: + is-glob: 4.0.3 + + glur@1.1.2: {} + + hachure-fill@0.5.2: {} + + html-encoding-sniffer@7.0.0: + dependencies: + '@exodus/bytes': 1.16.0 + transitivePeerDependencies: + - '@noble/hashes' + + iconv-lite@0.6.3: + dependencies: + safer-buffer: 2.1.2 + + image-blob-reduce@3.0.1: + dependencies: + pica: 7.1.1 + + immutable@4.3.9: {} + + import-meta-resolve@4.2.0: {} + + inherits@2.0.4: {} + + internmap@1.0.1: {} + + internmap@2.0.3: {} + + is-binary-path@2.1.0: + dependencies: + binary-extensions: 2.3.0 + + is-extglob@2.1.1: {} + + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + + is-number@7.0.0: {} + + is-potential-custom-element-name@1.0.1: {} + + isexe@2.0.0: {} + + jotai-scope@0.7.2(jotai@2.11.0(@types/react@19.3.0)(react@19.3.1))(react@19.3.1): + dependencies: + jotai: 2.11.0(@types/react@19.3.0)(react@19.3.1) + react: 19.3.1 + + jotai@2.11.0(@types/react@19.3.0)(react@19.3.1): + optionalDependencies: + '@types/react': 19.3.0 + react: 19.3.1 + + jsdom@30.1.3: + dependencies: + '@asamuzakjp/css-color': 7.1.9 + '@asamuzakjp/dom-selector': 10.0.5 + '@bramus/specificity': 2.4.3 + '@csstools/css-syntax-patches-for-csstree': 1.1.16(css-tree@3.2.1) + '@exodus/bytes': 1.16.0 + css-tree: 3.2.1 + data-urls: 8.0.0 + decimal.js: 10.6.0 + html-encoding-sniffer: 7.0.0 + is-potential-custom-element-name: 1.0.1 + lru-cache: 11.5.3 + parse5: 8.1.0 + saxes: 6.0.0 + tough-cookie: 6.0.2 + undici: 8.12.3 + w3c-xmlserializer: 6.0.0 + webidl-conversions: 8.0.1 + whatwg-mimetype: 5.0.0 + whatwg-url: 17.3.0 + xml-name-validator: 5.0.0 + transitivePeerDependencies: + - '@noble/hashes' + + katex@0.16.47: + dependencies: + commander: 8.3.0 + + khroma@2.1.0: {} + + langium@3.3.1: + dependencies: + chevrotain: 11.0.3 + chevrotain-allstar: 0.3.1(chevrotain@11.0.3) + vscode-languageserver: 9.0.1 + vscode-languageserver-textdocument: 1.0.16 + vscode-uri: 3.0.8 + + layout-base@1.0.2: {} + + layout-base@2.0.1: {} + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + lodash-es@4.17.21: {} + + lodash-es@4.18.1: {} + + lodash.debounce@4.0.8: {} + + lodash.throttle@4.1.1: {} + + lru-cache@11.5.3: {} + + magic-string@1.4.5: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + marked@16.4.2: {} + + mdn-data@2.27.1: {} + + mermaid@11.17.2: + dependencies: + '@braintree/sanitize-url': 7.1.2 + '@iconify/utils': 3.1.7 + '@mermaid-js/parser': 1.2.1 + '@types/d3': 7.4.3 + '@upsetjs/venn.js': 2.0.0 + cytoscape: 3.34.4 + cytoscape-cose-bilkent: 4.1.0(cytoscape@3.34.4) + cytoscape-fcose: 2.2.0(cytoscape@3.34.4) + d3: 7.9.0 + d3-sankey: 0.12.3 + dagre-d3-es: 7.0.14 + dayjs: 1.11.23 + dompurify: 3.4.17 + es-toolkit: 1.53.1 + fastdom: 1.0.12 + katex: 0.16.47 + khroma: 2.1.0 + marked: 16.4.2 + roughjs: 4.6.6 + stylis: 4.4.0 + ts-dedent: 2.3.0 + uuid: 14.0.3 + + multimath@2.0.0: + dependencies: + glur: 1.1.2 + object-assign: 4.1.1 + + nanoid@3.3.20: {} + + nanoid@3.3.3: {} + + nanoid@4.0.2: {} + + normalize-path@3.0.0: {} + + object-assign@4.1.1: {} + + obug@3.0.0: {} + + open-color@1.9.1: {} + + package-manager-detector@1.9.0: {} + + pako@2.0.3: {} + + parse5@8.1.0: + dependencies: + entities: 9.0.0 + + path-data-parser@0.1.0: {} + + path-key@3.1.1: {} + + perfect-freehand@1.2.0: {} + + pica@7.1.1: + dependencies: + glur: 1.1.2 + inherits: 2.0.4 + multimath: 2.0.0 + object-assign: 4.1.1 + webworkify: 1.5.0 + + picocolors@1.1.1: {} + + picomatch@2.3.2: {} + + picomatch@4.0.7: {} + + png-chunk-text@1.0.0: {} + + png-chunks-encode@1.0.0: + dependencies: + crc-32: 0.3.0 + sliced: 1.0.1 + + png-chunks-extract@1.0.0: + dependencies: + crc-32: 0.3.0 + + points-on-curve@0.2.0: {} + + points-on-curve@1.0.1: {} + + points-on-path@0.2.1: + dependencies: + path-data-parser: 0.1.0 + points-on-curve: 0.2.0 + + postcss@8.5.32: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.2 + + punycode@2.3.1: {} + + pwacompat@2.0.17: {} + + react-dom@19.3.1(react@19.3.1): + dependencies: + react: 19.3.1 + scheduler: 0.28.0 + + react-remove-scroll-bar@2.3.8(@types/react@19.3.0)(react@19.3.1): + dependencies: + react: 19.3.1 + react-style-singleton: 2.2.3(@types/react@19.3.0)(react@19.3.1) + tslib: 2.9.1 + optionalDependencies: + '@types/react': 19.3.0 + + react-remove-scroll@2.7.2(@types/react@19.3.0)(react@19.3.1): + dependencies: + react: 19.3.1 + react-remove-scroll-bar: 2.3.8(@types/react@19.3.0)(react@19.3.1) + react-style-singleton: 2.2.3(@types/react@19.3.0)(react@19.3.1) + tslib: 2.9.1 + use-callback-ref: 1.3.3(@types/react@19.3.0)(react@19.3.1) + use-sidecar: 1.1.3(@types/react@19.3.0)(react@19.3.1) + optionalDependencies: + '@types/react': 19.3.0 + + react-style-singleton@2.2.3(@types/react@19.3.0)(react@19.3.1): + dependencies: + get-nonce: 1.0.1 + react: 19.3.1 + tslib: 2.9.1 + optionalDependencies: + '@types/react': 19.3.0 + + react@19.3.1: {} + + readdirp@3.6.0: + dependencies: + picomatch: 2.3.2 + + require-from-string@2.0.2: {} + + robust-predicates@3.0.3: {} + + rolldown@1.2.16: + dependencies: + '@oxc-project/types': 0.156.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.16 + '@rolldown/binding-android-arm64': 1.2.16 + '@rolldown/binding-darwin-arm64': 1.2.16 + '@rolldown/binding-darwin-x64': 1.2.16 + '@rolldown/binding-freebsd-x64': 1.2.16 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.16 + '@rolldown/binding-linux-arm64-gnu': 1.2.16 + '@rolldown/binding-linux-arm64-musl': 1.2.16 + '@rolldown/binding-linux-ppc64-gnu': 1.2.16 + '@rolldown/binding-linux-s390x-gnu': 1.2.16 + '@rolldown/binding-linux-x64-gnu': 1.2.16 + '@rolldown/binding-linux-x64-musl': 1.2.16 + '@rolldown/binding-openharmony-arm64': 1.2.16 + '@rolldown/binding-win32-arm64-msvc': 1.2.16 + '@rolldown/binding-win32-x64-msvc': 1.2.16 + + roughjs@4.6.4: + dependencies: + hachure-fill: 0.5.2 + path-data-parser: 0.1.0 + points-on-curve: 0.2.0 + points-on-path: 0.2.1 + + roughjs@4.6.6: + dependencies: + hachure-fill: 0.5.2 + path-data-parser: 0.1.0 + points-on-curve: 0.2.0 + points-on-path: 0.2.1 + + rw@1.3.3: {} + + safer-buffer@2.1.2: {} + + sass@1.51.0: + dependencies: + chokidar: 3.6.0 + immutable: 4.3.9 + source-map-js: 1.2.2 + + saxes@6.0.0: + dependencies: + xmlchars: 2.2.0 + + scheduler@0.28.0: {} + + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + + sliced@1.0.1: {} + + source-map-js@1.2.2: {} + + std-env@4.3.0: {} + + strictdom@1.0.1: {} + + stylis@4.4.0: {} + + tinybench@6.2.3: {} + + tinyexec@1.3.1: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + tldts-core@7.4.20: {} + + tldts@7.4.19: + dependencies: + tldts-core: 7.4.20 + + to-regex-range@5.0.1: + dependencies: + is-number: 7.0.0 + + tough-cookie@6.0.2: + dependencies: + tldts: 7.4.19 + + tr46@7.0.0: + dependencies: + punycode: 2.3.1 + + ts-dedent@2.3.0: {} + + tslib@2.9.1: {} + + tunnel-rat@0.1.2(@types/react@19.3.0)(react@19.3.1): + dependencies: + zustand: 4.5.7(@types/react@19.3.0)(react@19.3.1) + transitivePeerDependencies: + - '@types/react' + - immer + - react + + typescript@6.0.3: {} + + undici-types@8.9.0: {} + + undici@8.12.3: {} + + use-callback-ref@1.3.3(@types/react@19.3.0)(react@19.3.1): + dependencies: + react: 19.3.1 + tslib: 2.9.1 + optionalDependencies: + '@types/react': 19.3.0 + + use-sidecar@1.1.3(@types/react@19.3.0)(react@19.3.1): + dependencies: + detect-node-es: 1.1.0 + react: 19.3.1 + tslib: 2.9.1 + optionalDependencies: + '@types/react': 19.3.0 + + use-sync-external-store@1.7.0(react@19.3.1): + dependencies: + react: 19.3.1 + + uuid@14.0.3: {} + + vite@8.3.5(@types/node@26.6.6): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.32 + rolldown: 1.2.16 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 26.6.6 + fsevents: 2.3.3 + + vitest@5.0.5(@types/node@26.6.6)(jsdom@30.1.3)(vite@8.3.5(@types/node@26.6.6)): + dependencies: + '@types/chai': 5.2.3 + '@vitest/mocker': 5.0.5(vite@8.3.5(@types/node@26.6.6)) + chai: 6.3.0 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 1.4.5 + obug: 3.0.0 + picomatch: 4.0.7 + std-env: 4.3.0 + tinybench: 6.2.3 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + vite: 8.3.5(@types/node@26.6.6) + why-is-node-running: 3.2.1 + optionalDependencies: + '@types/node': 26.6.6 + jsdom: 30.1.3 + transitivePeerDependencies: + - msw + + vscode-jsonrpc@8.2.0: {} + + vscode-languageserver-protocol@3.17.5: + dependencies: + vscode-jsonrpc: 8.2.0 + vscode-languageserver-types: 3.17.5 + + vscode-languageserver-textdocument@1.0.16: {} + + vscode-languageserver-types@3.17.5: {} + + vscode-languageserver@9.0.1: + dependencies: + vscode-languageserver-protocol: 3.17.5 + + vscode-uri@3.0.8: {} + + w3c-xmlserializer@6.0.0: + dependencies: + xml-name-validator: 5.0.0 + + webidl-conversions@8.0.1: {} + + webworkify@1.5.0: {} + + whatwg-mimetype@5.0.0: {} + + whatwg-url@17.3.0: + dependencies: + '@exodus/bytes': 1.16.0 + tr46: 7.0.0 + webidl-conversions: 8.0.1 + transitivePeerDependencies: + - '@noble/hashes' + + which@2.0.2: + dependencies: + isexe: 2.0.0 + + why-is-node-running@3.2.1: {} + + xml-name-validator@5.0.0: {} + + xmlchars@2.2.0: {} + + zustand@4.5.7(@types/react@19.3.0)(react@19.3.1): + dependencies: + use-sync-external-store: 1.7.0(react@19.3.1) + optionalDependencies: + '@types/react': 19.3.0 + react: 19.3.1 diff --git a/plugins/official/excalidraw/web-src/src/assets.ts b/plugins/official/excalidraw/web-src/src/assets.ts new file mode 100644 index 00000000..64824bb5 --- /dev/null +++ b/plugins/official/excalidraw/web-src/src/assets.ts @@ -0,0 +1,6 @@ +/** + * Excalidraw loads its fonts from `EXCALIDRAW_ASSET_PATH` (else from a CDN, + * which the frame can't reach): the page's own directory, where the build + * copies them. Imported before Excalidraw. + */ +window.EXCALIDRAW_ASSET_PATH = new URL("./", window.location.href).href; diff --git a/plugins/official/excalidraw/web-src/src/downloads.ts b/plugins/official/excalidraw/web-src/src/downloads.ts new file mode 100644 index 00000000..ec1ff3bc --- /dev/null +++ b/plugins/official/excalidraw/web-src/src/downloads.ts @@ -0,0 +1,25 @@ +/** + * The frame may not download files (no `allow-downloads`): Excalidraw's + * "Save to disk" and image export click a download link, which this turns + * into the IDE's save dialog (`openidea.saveFile`). + */ +const click = HTMLAnchorElement.prototype.click; + +export function routeDownloadsToTheIde(bridge: OpenideaBridge) { + HTMLAnchorElement.prototype.click = function (this: HTMLAnchorElement) { + const href = this.href; + if (!this.hasAttribute("download") || !/^(blob|data):/.test(href)) return click.call(this); + const name = this.download || "untitled"; + void fetch(href) + .then((r) => r.blob()) + .then((data) => bridge.saveFile({ name, data, filters: filtersFor(name) })) + .catch((e: unknown) => console.error("could not save", name, e)); + }; +} + +function filtersFor(name: string): OpenideaFileFilter[] | undefined { + const ext = /\.([\w]+)$/.exec(name)?.[1]?.toLowerCase(); + if (!ext) return undefined; + const label: Record = { png: "PNG image", svg: "SVG image", excalidraw: "Excalidraw drawing" }; + return [{ name: label[ext] ?? ext.toUpperCase(), extensions: [ext] }]; +} diff --git a/plugins/official/excalidraw/web-src/src/main.tsx b/plugins/official/excalidraw/web-src/src/main.tsx new file mode 100644 index 00000000..a2cb221c --- /dev/null +++ b/plugins/official/excalidraw/web-src/src/main.tsx @@ -0,0 +1,123 @@ +/** + * The Excalidraw plugin's page: the canvas of the `.excalidraw` file its + * custom editor shows, kept in step with the file's text (see sync.ts), in + * the IDE's light or dark theme. + */ +import "./assets"; +import { Excalidraw, MainMenu, THEME } from "@excalidraw/excalidraw"; +import "@excalidraw/excalidraw/index.css"; +import type { ExcalidrawImperativeAPI, UIOptions } from "@excalidraw/excalidraw/types"; +import { StrictMode, useEffect, useMemo, useRef, useState } from "react"; +import { createRoot } from "react-dom/client"; +import { routeDownloadsToTheIde } from "./downloads"; +import { applyScene, codec, exportName, loadSceneFonts, type Scene } from "./scene"; +import { DocumentSync } from "./sync"; + +// The canvas is the file's: the IDE opens, saves and themes it, so the page +// keeps only what works on the drawing itself (no Open / Save to, no links +// out of a page without network). +const UI_OPTIONS: UIOptions = { + canvasActions: { + changeViewBackgroundColor: true, + clearCanvas: true, + export: false, + loadScene: false, + saveAsImage: true, + saveToActiveFile: false, + toggleTheme: false, + }, +}; + +function Menu() { + return ( + + + + + + + + + ); +} + +function useIdeTheme(bridge: OpenideaBridge): "dark" | "light" { + const [dark, setDark] = useState(bridge.theme?.dark ?? window.matchMedia?.("(prefers-color-scheme: dark)").matches); + useEffect(() => bridge.onThemeChange((t) => setDark(t.dark)), [bridge]); + return dark ? THEME.DARK : THEME.LIGHT; +} + +type Start = { scene: Scene | null; error: string | null; readOnly: boolean; name: string }; + +function App({ bridge }: { bridge: OpenideaBridge }) { + const theme = useIdeTheme(bridge); + const [api, setApi] = useState(null); + const [start, setStart] = useState(null); + const [error, setError] = useState(null); + // The document's `source`: the canvas doesn't keep it, the file should. + const source = useRef(undefined); + // `apply` reads the API when the document changes, which is after the canvas exists. + const sync = useMemo(() => { + let current: ExcalidrawImperativeAPI | null = null; + const s = new DocumentSync(bridge.document, codec, { + apply: (scene) => { + source.current = scene.source; + if (current) applyScene(current, scene); + }, + error: setError, + }); + return Object.assign(s, { bind: (a: ExcalidrawImperativeAPI | null) => void (current = a) }); + }, [bridge]); + + useEffect(() => { + sync.start().then( + (s) => { + source.current = s.scene?.source; + setStart(s); + setError(s.error); + }, + (e: unknown) => + setStart({ scene: null, error: String(e instanceof Error ? e.message : e), readOnly: true, name: "" }), + ); + }, [sync]); + + useEffect(() => { + sync.bind(api); + if (api) void loadSceneFonts(api); + }, [api, sync]); + + if (!start) return null; + if (!start.scene && error) + return ( +
+

This file can't be shown as a drawing until its text is valid again:

+
{error}
+
+ ); + return ( + sync.changed({ elements, appState, files, source: source.current })} + > + + + ); +} + +const bridge = window.openidea; +const root = createRoot(document.getElementById("root")!); +if (bridge) { + routeDownloadsToTheIde(bridge); + root.render( + + + , + ); +} else { + root.render(

This page runs inside OpenIDEA.

); +} diff --git a/plugins/official/excalidraw/web-src/src/openidea.d.ts b/plugins/official/excalidraw/web-src/src/openidea.d.ts new file mode 100644 index 00000000..f7d50e91 --- /dev/null +++ b/plugins/official/excalidraw/web-src/src/openidea.d.ts @@ -0,0 +1,41 @@ +/** The IDE's frame bridge (`window.openidea`), injected before the page's scripts. */ +interface OpenideaDocumentState { + version: number; + text: string; +} + +interface OpenideaTextEdit { + from: number; + to: number; + insert: string; +} + +interface OpenideaFileFilter { + name: string; + extensions: string[]; +} + +interface OpenideaBridge { + postMessage(text: string): void; + onMessage(fn: (text: string) => void): void; + readonly theme: { dark: boolean; vars: Readonly> } | null; + onThemeChange(fn: (theme: { dark: boolean; vars: Readonly> }) => void): void; + document: { + /** `name`: the file's name, without its directory. */ + get(): Promise; + onChange(fn: (state: OpenideaDocumentState) => void): void; + edit(version: number, edits: OpenideaTextEdit[]): Promise<{ version: number }>; + replace(version: number, text: string): Promise<{ version: number }>; + }; + saveFile(options: { + name: string; + data: string | Uint8Array | ArrayBuffer | Blob; + filters?: OpenideaFileFilter[]; + }): Promise; + openFile(options?: { filters?: OpenideaFileFilter[] }): Promise<{ name: string; data: Uint8Array } | null>; +} + +interface Window { + openidea?: OpenideaBridge; + EXCALIDRAW_ASSET_PATH?: string | string[]; +} diff --git a/plugins/official/excalidraw/web-src/src/scene.test.ts b/plugins/official/excalidraw/web-src/src/scene.test.ts new file mode 100644 index 00000000..9712d8ab --- /dev/null +++ b/plugins/official/excalidraw/web-src/src/scene.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; +import { SOURCE, exportName, parseScene, serializeScene } from "./scene"; + +const scene = (text: string) => { + const parsed = parseScene(text); + if ("error" in parsed) throw new Error(parsed.error); + return parsed.scene; +}; + +describe("scene files", () => { + it("keeps the file's source and writes ours, never the page's address, when it had none", () => { + const own = JSON.parse( + serializeScene(scene('{"type":"excalidraw","source":"https://excalidraw.com","elements":[]}')), + ); + expect(own.source).toBe("https://excalidraw.com"); + const none = JSON.parse(serializeScene(scene('{"type":"excalidraw","elements":[]}'))); + expect(none.source).toBe(SOURCE); + for (const page of ["openidea-plugin://localhost", "http://openidea-plugin.localhost"]) { + const fixed = JSON.parse(serializeScene(scene(`{"type":"excalidraw","source":"${page}","elements":[]}`))); + expect(fixed.source).toBe(SOURCE); + } + }); + + it("reads element skeletons and refuses what isn't a drawing", () => { + // (Labels become text elements in the browser; jsdom can't measure text.) + const s = scene('[{"type":"rectangle","x":0,"y":0,"width":10,"height":10}]'); + expect(s.elements[0]).toMatchObject({ type: "rectangle", width: 10 }); + expect(typeof s.elements[0]!.seed).toBe("number"); + expect(parseScene("{not json")).toHaveProperty("error"); + expect(parseScene('{"type":"other"}')).toHaveProperty("error"); + expect(parseScene("")).toHaveProperty("scene"); + }); + + it("names exports after the file", () => { + expect(exportName("diagram.excalidraw")).toBe("diagram"); + expect(exportName("Flow.Excalidraw.json")).toBe("Flow"); + expect(exportName("notes.v2.excalidraw")).toBe("notes.v2"); + expect(exportName("")).toBe("drawing"); + }); +}); diff --git a/plugins/official/excalidraw/web-src/src/scene.ts b/plugins/official/excalidraw/web-src/src/scene.ts new file mode 100644 index 00000000..f31ec443 --- /dev/null +++ b/plugins/official/excalidraw/web-src/src/scene.ts @@ -0,0 +1,170 @@ +/** + * The one module that talks to `@excalidraw/excalidraw`'s data API: reading a + * `.excalidraw` file into a scene (through Excalidraw's own `restore`, so old + * files and element skeletons work), writing it back in the format + * Excalidraw saves, and showing a scene that changed in the text. + */ +import { + CaptureUpdateAction, + convertToExcalidrawElements, + getNonDeletedElements, + getSceneVersion, + restore, + serializeAsJSON, +} from "@excalidraw/excalidraw"; +import type { OrderedExcalidrawElement } from "@excalidraw/excalidraw/element/types"; +import type { AppState, BinaryFiles, ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types"; +import type { SceneCodec } from "./sync"; + +export interface Scene { + elements: readonly OrderedExcalidrawElement[]; + appState: Partial; + files: BinaryFiles; + /** The file's `source`, kept as it was. */ + source?: string; +} + +/** `source` of files that had none (Excalidraw would write the page's address). */ +export const SOURCE = "https://openidea.dev"; + +type Skeleton = NonNullable[0]>[number]; + +const isRecord = (v: unknown): v is Record => typeof v === "object" && v !== null && !Array.isArray(v); + +/** + * Hand-written or generated files often hold element skeletons + * (`{ type: "rectangle", x, y, label: { text } }`) rather than full elements: + * expand those, keep full elements (their ids and versions) as they are. + */ +function expandSkeletons(raw: readonly unknown[]): unknown[] { + const out: unknown[] = []; + for (const entry of raw) { + if (!isRecord(entry) || typeof entry.type !== "string") continue; + const skeleton = "label" in entry || typeof entry.seed !== "number"; + if (!skeleton) { + out.push(entry); + continue; + } + try { + out.push(...convertToExcalidrawElements([entry as unknown as Skeleton], { regenerateIds: false })); + } catch { + out.push(entry); + } + } + return out; +} + +export function parseScene(text: string): { scene: Scene } | { error: string } { + let data: unknown = {}; + if (text.trim()) { + try { + data = JSON.parse(text); + } catch (e) { + return { error: e instanceof Error ? e.message : String(e) }; + } + } + if (Array.isArray(data)) data = { elements: data }; + if (!isRecord(data)) return { error: "An Excalidraw file is a JSON object (or an array of elements)." }; + if (typeof data.type === "string" && !data.type.startsWith("excalidraw")) + return { error: `Not an Excalidraw file: its "type" is "${data.type}".` }; + if (data.elements !== undefined && !Array.isArray(data.elements)) return { error: '"elements" must be an array.' }; + const restored = restore( + { + elements: expandSkeletons((data.elements as unknown[]) ?? []) as never, + appState: (isRecord(data.appState) ? data.appState : {}) as Partial, + files: (isRecord(data.files) ? data.files : {}) as BinaryFiles, + }, + null, + null, + { refreshDimensions: false, repairBindings: true }, + ); + // The page's own address (what Excalidraw writes here) is no source worth keeping. + const own = /^(openidea-plugin:|https?:\/\/openidea-plugin\.localhost)/; + const source = + typeof data.source === "string" && data.source.trim() && !own.test(data.source) ? data.source : undefined; + return { scene: { elements: restored.elements, appState: restored.appState, files: restored.files ?? {}, source } }; +} + +/** + * As Excalidraw saves to disk (`serializeAsJSON(…, "local")`), with a final + * newline, keeping the file's `source`: Excalidraw writes the page's origin, + * which here is the IDE's internal plugin URL. + */ +export function serializeScene(scene: Scene): string { + const json = serializeAsJSON(scene.elements, scene.appState, scene.files, "local"); + const source = JSON.stringify(scene.source ?? SOURCE); + // `source` is the third key, before any element: the first match is the file's own. + return `${json.replace(/"source": "(?:[^"\\]|\\.)*"/, `"source": ${source}`)}\n`; +} + +/** What is saved changes iff this does: pointer moves, zoom and selection don't. */ +export function sceneSignature(scene: Scene): string { + const elements = getNonDeletedElements(scene.elements); + const a = scene.appState; + const files = Object.keys(scene.files).sort().join(","); + return [ + getSceneVersion(elements), + elements.length, + a.viewBackgroundColor, + a.gridSize, + a.gridStep, + a.gridModeEnabled, + files, + ].join(":"); +} + +export const codec: SceneCodec = { parse: parseScene, serialize: serializeScene, signature: sceneSignature }; + +/** Shows a scene the text changed to, keeping the view (scroll, zoom) and the canvas's undo history. */ +export function applyScene(api: ExcalidrawImperativeAPI, scene: Scene) { + const files = Object.values(scene.files); + if (files.length) api.addFiles(files); + const { viewBackgroundColor, gridSize, gridStep, gridModeEnabled } = scene.appState; + const appState: Pick = { + viewBackgroundColor: viewBackgroundColor ?? "#ffffff", + gridSize: gridSize ?? 20, + gridStep: gridStep ?? 5, + gridModeEnabled: gridModeEnabled ?? false, + }; + api.updateScene({ elements: scene.elements, appState, captureUpdate: CaptureUpdateAction.NEVER }); + void loadSceneFonts(api); +} + +/** + * Excalidraw loads the fonts of the scene it starts with, not of scenes set + * later, and WebKit's canvas doesn't load a font by drawing with it: load + * them, then redraw text (new element objects drop Excalidraw's cached text + * canvases) without recording a change. + */ +export async function loadSceneFonts(api: ExcalidrawImperativeAPI) { + const fonts = new Set(); + for (const el of api.getSceneElements()) { + if (el.type === "text") fonts.add(`${el.fontSize}px ${fontStack(el.fontFamily)}`); + } + if (!fonts.size || !document.fonts?.load) return; + await Promise.allSettled([...fonts].map((f) => document.fonts.load(f))); + api.updateScene({ + elements: api.getSceneElementsIncludingDeleted().map((el) => ({ ...el })), + captureUpdate: CaptureUpdateAction.NEVER, + }); +} + +/** Excalidraw's font family ids (`FONT_FAMILY`) → their CSS stack. */ +function fontStack(id: number): string { + const names: Record = { + 1: "Virgil", + 2: "Helvetica", + 3: "Cascadia", + 5: "Excalifont, Xiaolai", + 6: "Nunito", + 7: "Lilita One", + 8: "Comic Shanns", + 9: "Liberation Sans", + }; + return `${names[id] ?? "Excalifont, Xiaolai"}, Segoe UI Emoji`; +} + +/** What exports are called: the file's name without its extension. */ +export function exportName(file: string): string { + return file.replace(/\.excalidraw(\.json)?$/i, "") || "drawing"; +} diff --git a/plugins/official/excalidraw/web-src/src/sync.test.ts b/plugins/official/excalidraw/web-src/src/sync.test.ts new file mode 100644 index 00000000..3a7500b2 --- /dev/null +++ b/plugins/official/excalidraw/web-src/src/sync.test.ts @@ -0,0 +1,107 @@ +import { describe, expect, it, vi } from "vitest"; +import { DocumentSync, type SceneCodec, type SyncPort } from "./sync"; + +/** Scenes are plain strings here: the text is the scene. */ +const codec: SceneCodec = { + parse: (text) => (text.startsWith("!") ? { error: "bad" } : { scene: text }), + serialize: (scene) => scene, + signature: (scene) => scene, +}; + +function port(initial: string) { + let version = 0; + let text = initial; + let listener: (s: { version: number; text: string }) => void = () => {}; + const p = { + get: vi.fn(async () => ({ version, text, readOnly: false, name: "a.excalidraw" })), + replace: vi.fn(async (at: number, next: string) => { + if (at !== version) throw new Error("stale"); + text = next; + return { version: ++version }; + }), + onChange: (fn: typeof listener) => void (listener = fn), + /** An edit made in the text editor. */ + external(next: string) { + text = next; + listener({ version: ++version, text }); + }, + text: () => text, + } satisfies SyncPort & Record; + return p; +} + +const hooks = () => ({ apply: vi.fn(), error: vi.fn() }); + +describe("DocumentSync", () => { + it("starts from the document and writes canvas changes back, once per saved change", async () => { + const p = port("a"); + const h = hooks(); + const sync = new DocumentSync(p, codec, h, 0); + expect(await sync.start()).toEqual({ scene: "a", error: null, readOnly: false, name: "a.excalidraw" }); + sync.changed("a"); + await sync.flush(); + expect(p.replace).not.toHaveBeenCalled(); + sync.changed("ab"); + sync.changed("abc"); + await sync.flush(); + expect(p.replace).toHaveBeenCalledTimes(1); + expect(p.text()).toBe("abc"); + }); + + it("shows edits made elsewhere and doesn't write them back", async () => { + const p = port("a"); + const h = hooks(); + const sync = new DocumentSync(p, codec, h, 0); + await sync.start(); + p.external("from the text editor"); + expect(h.apply).toHaveBeenCalledWith("from the text editor"); + sync.changed("from the text editor"); + await sync.flush(); + expect(p.replace).not.toHaveBeenCalled(); + // The next canvas edit is based on the new version. + sync.changed("canvas"); + await sync.flush(); + expect(p.text()).toBe("canvas"); + }); + + it("lets the document win a race: a stale write is dropped and the canvas takes the text", async () => { + const p = port("a"); + const h = hooks(); + const sync = new DocumentSync(p, codec, h, 0); + await sync.start(); + sync.changed("canvas"); + // The document moved on without the sync hearing of it yet. + p.replace.mockImplementationOnce(async () => { + throw new Error("stale"); + }); + await sync.flush(); + expect(p.get).toHaveBeenCalledTimes(2); + expect(p.text()).toBe("a"); + }); + + it("never overwrites text that doesn't parse, and resumes when it does", async () => { + const p = port("a"); + const h = hooks(); + const sync = new DocumentSync(p, codec, h, 0); + await sync.start(); + p.external("!broken"); + expect(h.error).toHaveBeenLastCalledWith("bad"); + sync.changed("canvas"); + await sync.flush(); + expect(p.text()).toBe("!broken"); + p.external("fixed"); + expect(h.error).toHaveBeenLastCalledWith(null); + sync.changed("canvas"); + await sync.flush(); + expect(p.text()).toBe("canvas"); + }); + + it("starts read-only and invalid documents without writing", async () => { + const p = port("!broken"); + const sync = new DocumentSync(p, codec, hooks(), 0); + expect(await sync.start()).toEqual({ scene: null, error: "bad", readOnly: false, name: "a.excalidraw" }); + sync.changed("x"); + await sync.flush(); + expect(p.replace).not.toHaveBeenCalled(); + }); +}); diff --git a/plugins/official/excalidraw/web-src/src/sync.ts b/plugins/official/excalidraw/web-src/src/sync.ts new file mode 100644 index 00000000..8af22cc8 --- /dev/null +++ b/plugins/official/excalidraw/web-src/src/sync.ts @@ -0,0 +1,128 @@ +/** + * Keeps the canvas and the file's text in step through the IDE's document + * bridge. The text is the truth: the canvas starts from it, its edits are + * written back (debounced, versioned) and edits made elsewhere (the text + * editor, Undo, another window) replace what the canvas shows. + * + * - Canvas changes that don't change what is saved (pointer moves, zoom, + * selection) write nothing: they're compared by `signature`. + * - A write that lost a race (`stale`) is dropped and the canvas takes the + * document's text. + * - Text that doesn't parse is never overwritten: the canvas stops writing + * until the text is valid again. + */ +export interface SyncPort { + get(): Promise<{ version: number; text: string; readOnly: boolean; name?: string }>; + replace(version: number, text: string): Promise<{ version: number }>; + onChange(fn: (state: { version: number; text: string }) => void): void; +} + +export interface SceneCodec { + parse(text: string): { scene: S } | { error: string }; + serialize(scene: S): string; + /** Equal for scenes that save the same. */ + signature(scene: S): string; +} + +export interface SyncHooks { + /** Show a scene the document changed to. */ + apply(scene: S): void; + /** The document's text doesn't parse (`null`: it does again). */ + error(message: string | null): void; +} + +export class DocumentSync { + private version = 0; + private text = ""; + private readOnly = false; + private valid = true; + private signature: string | null = null; + private pending: S | null = null; + private timer: ReturnType | null = null; + private writing: Promise | null = null; + + constructor( + private readonly port: SyncPort, + private readonly codec: SceneCodec, + private readonly hooks: SyncHooks, + private readonly delayMs = 250, + ) {} + + /** The document's scene to start from. */ + async start(): Promise<{ scene: S | null; error: string | null; readOnly: boolean; name: string }> { + const doc = await this.port.get(); + this.version = doc.version; + this.text = doc.text; + this.readOnly = doc.readOnly; + this.port.onChange((state) => this.external(state)); + const parsed = this.codec.parse(doc.text); + if ("error" in parsed) { + this.valid = false; + return { scene: null, error: parsed.error, readOnly: doc.readOnly, name: doc.name ?? "" }; + } + this.signature = this.codec.signature(parsed.scene); + return { scene: parsed.scene, error: null, readOnly: doc.readOnly, name: doc.name ?? "" }; + } + + /** The canvas changed. */ + changed(scene: S) { + if (this.readOnly || !this.valid) return; + const signature = this.codec.signature(scene); + if (signature === this.signature) return; + this.signature = signature; + this.pending = scene; + if (this.timer) clearTimeout(this.timer); + this.timer = setTimeout(() => { + this.timer = null; + void this.flush(); + }, this.delayMs); + } + + /** Writes what is pending now (also waits for a write in flight). */ + async flush(): Promise { + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + while (this.writing) await this.writing; + const scene = this.pending; + this.pending = null; + if (scene === null) return; + const text = this.codec.serialize(scene); + if (text === this.text) return; + this.writing = (async () => { + try { + const { version } = await this.port.replace(this.version, text); + this.version = version; + this.text = text; + } catch (e) { + if (!(e instanceof Error && e.message === "stale")) throw e; + // Someone else changed it first: theirs wins. + this.external(await this.port.get()); + } + })().finally(() => { + this.writing = null; + }); + await this.writing; + } + + private external(state: { version: number; text: string }) { + this.version = state.version; + if (state.text === this.text) return; + this.text = state.text; + // The document moved on: what the canvas had pending is based on the old text. + if (this.timer) clearTimeout(this.timer); + this.timer = null; + this.pending = null; + const parsed = this.codec.parse(state.text); + if ("error" in parsed) { + this.valid = false; + this.hooks.error(parsed.error); + return; + } + this.valid = true; + this.signature = this.codec.signature(parsed.scene); + this.hooks.error(null); + this.hooks.apply(parsed.scene); + } +} diff --git a/plugins/official/excalidraw/web-src/src/test-setup.ts b/plugins/official/excalidraw/web-src/src/test-setup.ts new file mode 100644 index 00000000..1ecf7bcd --- /dev/null +++ b/plugins/official/excalidraw/web-src/src/test-setup.ts @@ -0,0 +1,10 @@ +/** + * jsdom has no canvas: Excalidraw probes a 2D context when it loads (and + * measures text with it). A context whose methods do nothing is enough for + * its data API. + */ +const context = new Proxy( + { filter: "none", measureText: (text: string) => ({ width: text.length * 8 }) } as Record, + { get: (target, key) => (key in target ? target[key] : () => undefined) }, +); +HTMLCanvasElement.prototype.getContext = (() => context) as unknown as HTMLCanvasElement["getContext"]; diff --git a/plugins/official/excalidraw/web-src/tsconfig.json b/plugins/official/excalidraw/web-src/tsconfig.json new file mode 100644 index 00000000..3e73e29b --- /dev/null +++ b/plugins/official/excalidraw/web-src/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "isolatedModules": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "types": ["vite/client", "node"] + }, + "include": ["src", "vite.config.ts"] +} diff --git a/plugins/official/excalidraw/web-src/vite.config.ts b/plugins/official/excalidraw/web-src/vite.config.ts new file mode 100644 index 00000000..fd731090 --- /dev/null +++ b/plugins/official/excalidraw/web-src/vite.config.ts @@ -0,0 +1,48 @@ +/** + * Builds the page into ../web (not checked in: plugins/build.sh builds it). + * Relative URLs throughout: the IDE serves the page from + * the plugin package under its own URL scheme. Excalidraw's fonts are copied + * next to it; the page points Excalidraw at them (src/assets.ts). + */ +import { cpSync, existsSync, rmSync } from "node:fs"; +import { createRequire } from "node:module"; +import path from "node:path"; +import react from "@vitejs/plugin-react"; +import type { Plugin } from "vite"; +import { defineConfig } from "vitest/config"; + +const require = createRequire(import.meta.url); +const outDir = path.resolve(import.meta.dirname, "../web"); + +function excalidrawFonts(): Plugin { + return { + name: "openidea:excalidraw-fonts", + apply: "build", + closeBundle() { + const fonts = path.resolve(path.dirname(require.resolve("@excalidraw/excalidraw")), "fonts"); + if (!existsSync(fonts)) throw new Error(`no Excalidraw fonts at ${fonts}`); + rmSync(path.join(outDir, "fonts"), { recursive: true, force: true }); + cpSync(fonts, path.join(outDir, "fonts"), { recursive: true }); + }, + }; +} + +export default defineConfig({ + base: "./", + plugins: [react(), excalidrawFonts()], + define: { "process.env.IS_PREACT": JSON.stringify("false") }, + build: { + outDir, + emptyOutDir: true, + target: "es2022", + sourcemap: false, + assetsInlineLimit: 0, + chunkSizeWarningLimit: 4096, + }, + test: { + // Excalidraw needs a DOM even for its data API; its packages ship JSON and CSS imports Node can't load. + environment: "jsdom", + setupFiles: ["./src/test-setup.ts"], + server: { deps: { inline: [/@excalidraw/, /open-color/] } }, + }, +}); diff --git a/plugins/official/git-toolbox/.gitignore b/plugins/official/git-toolbox/.gitignore new file mode 100644 index 00000000..ea8c4bf7 --- /dev/null +++ b/plugins/official/git-toolbox/.gitignore @@ -0,0 +1 @@ +/target diff --git a/plugins/official/git-toolbox/Cargo.lock b/plugins/official/git-toolbox/Cargo.lock new file mode 100644 index 00000000..9ad60b81 --- /dev/null +++ b/plugins/official/git-toolbox/Cargo.lock @@ -0,0 +1,333 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "openidea-plugin-openidea-git-toolbox" +version = "0.1.0" +dependencies = [ + "openidea-plugin", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[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 = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +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 = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/plugins/official/git-toolbox/Cargo.toml b/plugins/official/git-toolbox/Cargo.toml new file mode 100644 index 00000000..98e03ddd --- /dev/null +++ b/plugins/official/git-toolbox/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "openidea-plugin-openidea-git-toolbox" +version = "0.1.0" +edition = "2024" +publish = false + +# A plugin builds on its own (target wasm32-wasip2), outside any IDE workspace. +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../sdk/rust/openidea-plugin" } + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/plugins/official/git-toolbox/dist/plugin.wasm b/plugins/official/git-toolbox/dist/plugin.wasm new file mode 100644 index 00000000..9479f183 Binary files /dev/null and b/plugins/official/git-toolbox/dist/plugin.wasm differ diff --git a/plugins/official/git-toolbox/dist/plugin.wasm.sources b/plugins/official/git-toolbox/dist/plugin.wasm.sources new file mode 100644 index 00000000..fd509401 --- /dev/null +++ b/plugins/official/git-toolbox/dist/plugin.wasm.sources @@ -0,0 +1 @@ +ad545605b33c6f4e55a06a376333de3162739ed920b5d7d277942e50a4420083 diff --git a/plugins/official/git-toolbox/plugin.toml b/plugins/official/git-toolbox/plugin.toml new file mode 100644 index 00000000..ff5bbfce --- /dev/null +++ b/plugins/official/git-toolbox/plugin.toml @@ -0,0 +1,26 @@ +id = "openidea.git-toolbox" +name = "Git Toolbox" +version = "0.1.0" +description = "Fetches your repositories in the background and shows the branch with how far it is ahead of and behind its upstream in the status bar." +authors = ["OpenIDEA contributors"] +license = "Apache-2.0" +change-notes = "0.1.0 — first release: auto-fetch every 5 minutes, ahead/behind in the status bar, Fetch Now." +engines.openidea = "^1.0" +wasm = "dist/plugin.wasm" +# Fetches on schedule (also after being reclaimed while idle) and refreshes +# the status bar when the focused editor or a repository changes. +activation = ["on-schedule:300", "on-event:editor-focused", "on-event:vcs-changed", "on-command:*"] + +[capabilities] +# `vcs.write` runs `git fetch` (only in trusted projects). +required = ["project.read", "vcs.read", "vcs.write", "events", "storage"] + +[[contributes.commands]] +id = "fetch" +title = "Git Toolbox: Fetch Now" +category = "Git Toolbox" + +[[contributes.commands]] +id = "refresh" +title = "Git Toolbox: Refresh Status" +category = "Git Toolbox" diff --git a/plugins/official/git-toolbox/src/lib.rs b/plugins/official/git-toolbox/src/lib.rs new file mode 100644 index 00000000..5201eae9 --- /dev/null +++ b/plugins/official/git-toolbox/src/lib.rs @@ -0,0 +1,242 @@ +//! Git Toolbox for OpenIDEA: background fetch of every open project's +//! repository (on the plugin's `on-schedule`, which also fires after the +//! instance was reclaimed while idle), and the focused project's branch with +//! its ahead/behind counts in the status bar. + +use openidea_plugin::host::{self, storage}; +use openidea_plugin::{ + Error, Event, Invocation, NotificationLevel, Plugin, Project, RepositoryStatus, StatusItem, register_plugin, +}; + +const ITEM: &str = "branch"; +const LAST_FETCH: &str = "last-fetch:"; +/// Root of the project shown in the status bar. +const SHOWN: &str = "shown-root"; + +#[derive(Default)] +pub struct GitToolbox; + +fn now_secs() -> u64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) +} + +/// `main ↑1 ↓2`; a detached HEAD shows its commit. +pub fn label(s: &RepositoryStatus) -> String { + let mut out = match (&s.branch, &s.commit) { + (Some(b), _) => b.clone(), + (None, Some(c)) => c.chars().take(8).collect(), + (None, None) => "(no commits)".to_owned(), + }; + if s.upstream.is_some() { + if s.ahead > 0 { + out.push_str(&format!(" ↑{}", s.ahead)); + } + if s.behind > 0 { + out.push_str(&format!(" ↓{}", s.behind)); + } + } + if let Some(op) = &s.operation { + out.push_str(&format!(" ({op})")); + } + out +} + +fn ago(secs: u64) -> String { + match secs { + 0..60 => "just now".into(), + 60..3600 => format!("{} min ago", secs / 60), + _ => format!("{} h ago", secs / 3600), + } +} + +fn tooltip(s: &RepositoryStatus) -> String { + let mut lines = vec![s.root.clone()]; + match &s.upstream { + Some(up) => lines.push(format!("{} ahead, {} behind {up}", s.ahead, s.behind)), + None => lines.push("No upstream branch".into()), + } + if s.changed_files > 0 { + lines.push(format!("{} changed files", s.changed_files)); + } + let last = storage::get(&format!("{LAST_FETCH}{}", s.root)).ok().flatten().and_then(|v| v.parse::().ok()); + lines.push(match last { + Some(t) => format!("Fetched {}", ago(now_secs().saturating_sub(t))), + None => "Not fetched yet".into(), + }); + lines.push("Click to fetch now".into()); + lines.join("\n") +} + +/// Shows `project`'s repository in the status bar (or hides the item). +fn show(project: &Project) -> Result<(), Error> { + match project.vcs_status()? { + Some(s) => { + let _ = storage::set(SHOWN, &project.root()?); + host::set_status_item( + ITEM, + &StatusItem { text: label(&s), tooltip: Some(tooltip(&s)), command: Some("fetch".into()) }, + ); + } + None => host::remove_status_item(ITEM), + } + Ok(()) +} + +/// The project the status bar follows: the invoking window's, else the one +/// shown last, else the first open one. +fn current(ctx: &Invocation) -> Option { + if let Some(p) = ctx.project() { + return Some(p); + } + let projects = host::projects().ok()?; + let shown = storage::get(SHOWN).ok().flatten(); + let index = projects.iter().position(|p| p.root().ok() == shown).unwrap_or(0); + projects.into_iter().nth(index) +} + +/// Fetches `projects` in one cancellable task. Returns how many were fetched. +fn fetch(projects: &[Project]) -> Result { + let task = host::begin_task("Fetching", true); + let total = projects.len() as u32; + let mut fetched = 0; + let mut last_error = None; + for (i, p) in projects.iter().enumerate() { + if task.is_cancelled() { + return Err(Error::Cancelled); + } + let root = p.root()?; + let name = root.rsplit(['/', '\\']).next().unwrap_or(&root).to_owned(); + task.report(i as u32, Some(total), Some(&name)); + if p.vcs_status()?.is_none() { + continue; + } + match p.vcs_fetch() { + Ok(()) => { + fetched += 1; + let _ = storage::set(&format!("{LAST_FETCH}{root}"), &now_secs().to_string()); + } + Err(Error::Cancelled) => return Err(Error::Cancelled), + Err(e) => { + host::log(openidea_plugin::LogLevel::Warn, &format!("fetch {root}: {e}")); + last_error = Some(e); + } + } + } + task.report(total, Some(total), None); + match last_error { + Some(e) if fetched == 0 => Err(e), + _ => Ok(fetched), + } +} + +impl Plugin for GitToolbox { + fn run_command(&mut self, id: &str, ctx: &Invocation, _arg: Option<&str>) -> Result, Error> { + let project = current(ctx).ok_or("no project is open")?; + match id { + "fetch" => { + let n = fetch(std::slice::from_ref(&project))?; + show(&project)?; + Ok((n == 0).then(|| "The project is not in a git repository.".to_owned())) + } + "refresh" => { + show(&project)?; + Ok(None) + } + _ => Err(Error::NotFound(format!("command {id}"))), + } + } + + fn handle_events(&mut self, events: &[Event], ctx: &Invocation) { + if events.contains(&Event::Scheduled) { + let projects = host::projects().unwrap_or_default(); + if let Err(e) = fetch(&projects) + && e != Error::Cancelled + { + host::notify(NotificationLevel::Warning, "Git Toolbox: fetch failed", &e.to_string()); + } + } + if let Some(p) = current(ctx) { + let _ = show(&p); + } + } +} + +register_plugin!(GitToolbox); + +#[cfg(test)] +mod tests { + use super::*; + use openidea_plugin::mock::MockHost; + + fn status(ahead: u32, behind: u32) -> RepositoryStatus { + RepositoryStatus { + root: "/project".into(), + branch: Some("main".into()), + commit: Some("0123456789abcdef".into()), + upstream: Some("origin/main".into()), + ahead, + behind, + ..RepositoryStatus::default() + } + } + + #[test] + fn labels() { + assert_eq!(label(&status(0, 0)), "main"); + assert_eq!(label(&status(1, 2)), "main ↑1 ↓2"); + let detached = RepositoryStatus { branch: None, ..status(0, 0) }; + assert_eq!(label(&detached), "01234567"); + let rebasing = RepositoryStatus { operation: Some("rebase".into()), ..status(0, 3) }; + assert_eq!(label(&rebasing), "main ↓3 (rebase)"); + } + + #[test] + fn scheduled_fetch_updates_the_status_bar() { + let host = MockHost::install(); + host.add_project("/other"); + host.set_vcs_status(Some(status(0, 4))); + GitToolbox.handle_events(&[Event::Scheduled], &host.invocation()); + assert_eq!(host.fetches(), 2, "every open project"); + let item = &host.status_items()["branch"]; + assert_eq!(item.text, "main ↓4"); + assert!(item.tooltip.as_deref().unwrap().contains("Fetched just now")); + assert_eq!(item.command.as_deref(), Some("fetch")); + let task = &host.tasks()[0]; + assert!(task.ended && task.reports.last() == Some(&(2, Some(2), None))); + } + + #[test] + fn focus_changes_only_refresh() { + let host = MockHost::install(); + host.set_vcs_status(Some(status(1, 0))); + GitToolbox.handle_events(&[Event::EditorFocused(Some("/project/a.rs".into()))], &host.invocation()); + assert_eq!(host.fetches(), 0); + assert_eq!(host.status_items()["branch"].text, "main ↑1"); + host.set_vcs_status(None); + GitToolbox.handle_events(&[Event::VcsChanged("/project".into())], &host.invocation()); + assert!(host.status_items().is_empty(), "not a repository any more"); + } + + #[test] + fn failures_and_cancellation() { + let host = MockHost::install(); + host.set_vcs_status(Some(status(0, 0))); + host.fail_fetch(Some(Error::Failed("no network".into()))); + GitToolbox.handle_events(&[Event::Scheduled], &host.invocation()); + assert_eq!(host.notifications()[0].body, "no network"); + let err = GitToolbox.run_command("fetch", &host.invocation(), None).unwrap_err(); + assert_eq!(err, Error::Failed("no network".into())); + host.fail_fetch(Some(Error::Cancelled)); + GitToolbox.handle_events(&[Event::Scheduled], &host.invocation()); + assert_eq!(host.notifications().len(), 1, "a cancelled fetch is not an error to report"); + } + + #[test] + fn without_vcs_write_it_still_shows_the_branch() { + let host = MockHost::install().with_capabilities(&["project.read", "vcs.read", "storage"]); + host.set_vcs_status(Some(status(0, 1))); + GitToolbox.handle_events(&[Event::Scheduled], &host.invocation()); + assert!(host.notifications()[0].body.contains("vcs.write")); + assert_eq!(host.status_items()["branch"].text, "main ↓1"); + } +} diff --git a/plugins/official/graphviz/.gitignore b/plugins/official/graphviz/.gitignore new file mode 100644 index 00000000..2aa0170a --- /dev/null +++ b/plugins/official/graphviz/.gitignore @@ -0,0 +1,4 @@ +web-src/node_modules/ +# Built by plugins/build.sh, not checked in. +web/ +web.sources diff --git a/plugins/official/graphviz/Cargo.lock b/plugins/official/graphviz/Cargo.lock new file mode 100644 index 00000000..f7341f4a --- /dev/null +++ b/plugins/official/graphviz/Cargo.lock @@ -0,0 +1,334 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "openidea-plugin-openidea-graphviz" +version = "0.1.0" +dependencies = [ + "openidea-plugin", + "serde_json", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[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 = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +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 = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/plugins/official/graphviz/Cargo.toml b/plugins/official/graphviz/Cargo.toml new file mode 100644 index 00000000..69c6235c --- /dev/null +++ b/plugins/official/graphviz/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "openidea-plugin-openidea-graphviz" +version = "0.1.0" +edition = "2024" +publish = false + +# A plugin builds on its own (target wasm32-wasip2), outside any IDE workspace. +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../sdk/rust/openidea-plugin" } +serde_json = "1" + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/plugins/official/graphviz/NOTICE.md b/plugins/official/graphviz/NOTICE.md new file mode 100644 index 00000000..cf8b4298 --- /dev/null +++ b/plugins/official/graphviz/NOTICE.md @@ -0,0 +1,28 @@ +# Third-party software + +The page in `web/` is built from `web-src/` and bundles: + +- **Viz.js** (`@viz-js/viz` 3.31.0), MIT License, Copyright (c) Michael Daines — + https://github.com/mdaines/viz-js +- **Graphviz** 16.1.0, compiled to WebAssembly inside Viz.js, Eclipse Public License 1.0 — + https://graphviz.org, https://gitlab.com/graphviz/graphviz + +The MIT License: + +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software +> and associated documentation files (the "Software"), to deal in the Software without +> restriction, including without limitation the rights to use, copy, modify, merge, publish, +> distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the +> Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or +> substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING +> BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +> DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +The Eclipse Public License 1.0 is at https://www.eclipse.org/legal/epl-v10.html. Graphviz's +source code is available from the links above. diff --git a/plugins/official/graphviz/dist/plugin.wasm b/plugins/official/graphviz/dist/plugin.wasm new file mode 100644 index 00000000..fa2c8114 Binary files /dev/null and b/plugins/official/graphviz/dist/plugin.wasm differ diff --git a/plugins/official/graphviz/dist/plugin.wasm.sources b/plugins/official/graphviz/dist/plugin.wasm.sources new file mode 100644 index 00000000..8e261ce0 --- /dev/null +++ b/plugins/official/graphviz/dist/plugin.wasm.sources @@ -0,0 +1 @@ +de353be96a6b66629901f55a8027a0f27107a7ac2fb9d891089db1b7fd716299 diff --git a/plugins/official/graphviz/icons/graphviz.svg b/plugins/official/graphviz/icons/graphviz.svg new file mode 100644 index 00000000..30cb594a --- /dev/null +++ b/plugins/official/graphviz/icons/graphviz.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/plugins/official/graphviz/icons/graphviz_dark.svg b/plugins/official/graphviz/icons/graphviz_dark.svg new file mode 100644 index 00000000..545c3b97 --- /dev/null +++ b/plugins/official/graphviz/icons/graphviz_dark.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/plugins/official/graphviz/languages/dot.toml b/plugins/official/graphviz/languages/dot.toml new file mode 100644 index 00000000..fa0f70c9 --- /dev/null +++ b/plugins/official/graphviz/languages/dot.toml @@ -0,0 +1,8 @@ +id = "dot" +name = "DOT" +extensions = ["dot", "gv"] +line-comment = "//" +block-comment = ["/*", "*/"] +indent = { tab-size = 4, insert-spaces = true } +# No DOT mode in CodeMirror: C's highlights the strings, comments, numbers and braces. +ui-mode = "C" diff --git a/plugins/official/graphviz/plugin.toml b/plugins/official/graphviz/plugin.toml new file mode 100644 index 00000000..04f87a2e --- /dev/null +++ b/plugins/official/graphviz/plugin.toml @@ -0,0 +1,38 @@ +id = "openidea.graphviz" +name = "Graphviz" +version = "0.1.0" +description = "Graphviz DOT files (.dot, .gv) with a live preview beside the text: rendered as you type with any layout engine, syntax errors in the editor and the Problems view, export to SVG and PNG." +authors = ["OpenIDEA contributors"] +license = "Apache-2.0" +change-notes = "0.1.0 — first release: live preview (Graphviz compiled to WebAssembly), layout engines, zoom, errors as problems, SVG and PNG export." +engines.openidea = "^1.0" +wasm = "dist/plugin.wasm" +activation = ["on-view:preview"] + +[capabilities] +# Problems: published for the project's file (project.read), on the lines +# Graphviz names (editor.read: the previewed text). +required = ["editor.read", "project.read"] + +[[contributes.customEditors]] +id = "preview" +title = "Preview" +patterns = ["*.dot", "*.gv"] +priority = "default" +layout = "split" +web = "web/index.html" + +[[contributes.languages]] +path = "languages/dot.toml" + +[[contributes.fileIcons]] +id = "graphviz" +patterns = ["*.dot", "*.gv"] +icon = "icons/graphviz.svg" +iconDark = "icons/graphviz_dark.svg" + +[[contributes.fileTemplates]] +id = "graph" +name = "Graphviz Graph" +extension = "dot" +path = "templates/graph.dot" diff --git a/plugins/official/graphviz/src/lib.rs b/plugins/official/graphviz/src/lib.rs new file mode 100644 index 00000000..cd76c651 --- /dev/null +++ b/plugins/official/graphviz/src/lib.rs @@ -0,0 +1,141 @@ +//! Graphviz for OpenIDEA: `.dot` / `.gv` files open in the text editor with a +//! live preview beside them. The preview is a web page (`web-src/`: viz.js, +//! Graphviz compiled to WebAssembly) that renders the document as it changes; +//! what Graphviz reports it sends here, and the plugin publishes it as the +//! file's problems, on the line Graphviz names. + +use openidea_plugin::views::{View, ViewEvent, Viewport, Views}; +use openidea_plugin::{Diagnostic, Error, Invocation, Plugin, Position, Range, Severity, host, register_plugin}; +use serde_json::Value; + +pub const VIEW: &str = "preview"; +/// Problems published for one file at most. +const MAX_PROBLEMS: usize = 100; + +/// One message from Graphviz, as the page reports it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Report { + /// 1-based, when Graphviz names one. + pub line: Option, + pub message: String, + pub error: bool, +} + +/// The page's `{"op": "problems", "items": [{"line", "message", "level"}]}`. +pub fn parse_reports(message: &str) -> Option> { + let v: Value = serde_json::from_str(message).ok()?; + if v.get("op").and_then(Value::as_str) != Some("problems") { + return None; + } + let items = v.get("items")?.as_array()?; + Some( + items + .iter() + .take(MAX_PROBLEMS) + .filter_map(|i| { + Some(Report { + line: i.get("line").and_then(Value::as_u64).and_then(|l| u32::try_from(l).ok()), + message: i.get("message")?.as_str()?.trim().to_owned(), + error: i.get("level").and_then(Value::as_str) != Some("warning"), + }) + }) + .collect(), + ) +} + +/// `reports` as diagnostics of `text`: on the named line (clamped to the +/// document), the whole of it; without a line, on the first. +pub fn diagnostics(text: &str, reports: &[Report]) -> Vec { + let lines: Vec<&str> = text.lines().collect(); + reports + .iter() + .map(|r| { + let line = r.line.map_or(0, |l| l.saturating_sub(1)).min(lines.len().saturating_sub(1) as u32); + let len = lines.get(line as usize).map_or(0, |l| l.encode_utf16().count() as u32); + Diagnostic { + range: Range::new(Position::new(line, 0), Position::new(line, len)), + severity: if r.error { Severity::Error } else { Severity::Warning }, + message: r.message.clone(), + code: Some("graphviz".into()), + } + }) + .collect() +} + +#[derive(Default)] +pub struct Graphviz; + +impl Plugin for Graphviz { + fn run_command(&mut self, id: &str, _ctx: &Invocation, _arg: Option<&str>) -> Result, Error> { + Err(Error::NotFound(format!("command {id}"))) + } +} + +impl Views for Graphviz { + fn render(&mut self, view: &str, _viewport: Option, _ctx: &Invocation) -> Result { + if view != VIEW { + return Err(Error::NotFound(view.into())); + } + // The preview is the plugin's web page; nothing is rendered here. + Ok(View::message("The preview is shown by the plugin's page.")) + } + + fn handle(&mut self, view: &str, event: ViewEvent, ctx: &Invocation) -> Result<(), Error> { + if view != VIEW { + return Err(Error::NotFound(view.into())); + } + let ViewEvent::Message(message) = event else { return Ok(()) }; + let Some(reports) = parse_reports(&message) else { return Ok(()) }; + let editor = ctx.editor().ok_or_else(|| Error::Invalid("the preview needs its document".into()))?; + let text = editor.document()?.text; + // A file outside the open projects has no problems to publish to; its + // preview shows what went wrong anyway. + match host::publish_diagnostics(&editor.path(), &diagnostics(&text, &reports)) { + Err(Error::Invalid(_)) => Ok(()), + other => other, + } + } +} + +register_plugin!(Graphviz, views); + +#[cfg(test)] +mod tests { + use super::*; + use openidea_plugin::mock::MockHost; + + #[test] + fn reports_become_problems_on_their_line() { + let msg = r#"{"op":"problems","items":[ + {"line":2,"message":"syntax error in line 2 near '}'","level":"error"}, + {"line":null,"message":"Warning: no such engine","level":"warning"}, + {"line":99,"message":"past the end"}, + {"nope":1} + ]}"#; + let reports = parse_reports(msg).unwrap(); + assert_eq!(reports.len(), 3); + let d = diagnostics("digraph {\n a -> }\n", &reports); + assert_eq!( + (d[0].range, d[0].severity), + (Range::new(Position::new(1, 0), Position::new(1, 8)), Severity::Error) + ); + assert_eq!((d[1].range.start.line, d[1].severity), (0, Severity::Warning)); + assert_eq!(d[2].range.start.line, 1, "clamped to the last line"); + assert!(parse_reports(r#"{"op":"other"}"#).is_none()); + assert!(parse_reports("garbage").is_none()); + assert!(diagnostics("", &reports).iter().all(|d| d.range.start.line == 0)); + } + + #[test] + fn publishes_for_the_previewed_file_and_clears() { + let host = MockHost::install().with_capabilities(&["editor.read", "project.read"]); + host.open_editor("/project/a.dot", "dot", "digraph {\n a -> \n}\n", &[(0, 0, 0, 0)]); + let mut p = Graphviz; + let msg = + r#"{"op":"problems","items":[{"line":3,"message":"syntax error in line 3 near '}'","level":"error"}]}"#; + p.handle(VIEW, ViewEvent::Message(msg.into()), &host.invocation()).unwrap(); + assert_eq!(host.diagnostics()["/project/a.dot"][0].range.start.line, 2); + p.handle(VIEW, ViewEvent::Message(r#"{"op":"problems","items":[]}"#.into()), &host.invocation()).unwrap(); + assert!(host.diagnostics().get("/project/a.dot").is_none_or(Vec::is_empty)); + } +} diff --git a/plugins/official/graphviz/templates/graph.dot b/plugins/official/graphviz/templates/graph.dot new file mode 100644 index 00000000..450238b6 --- /dev/null +++ b/plugins/official/graphviz/templates/graph.dot @@ -0,0 +1,11 @@ +digraph G { + rankdir=LR; + node [shape=box, style=rounded]; + + start [label="Start"]; + work [label="Do the work"]; + done [label="Done", shape=doublecircle]; + + start -> work -> done; + work -> work [label="again"]; +} diff --git a/plugins/official/graphviz/web-src/index.html b/plugins/official/graphviz/web-src/index.html new file mode 100644 index 00000000..adf0f73c --- /dev/null +++ b/plugins/official/graphviz/web-src/index.html @@ -0,0 +1,25 @@ + + + + + + Graphviz + + + + +
+ + + + diff --git a/plugins/official/graphviz/web-src/package.json b/plugins/official/graphviz/web-src/package.json new file mode 100644 index 00000000..3e26eb31 --- /dev/null +++ b/plugins/official/graphviz/web-src/package.json @@ -0,0 +1,20 @@ +{ + "name": "openidea-plugin-graphviz-web", + "private": true, + "version": "0.1.0", + "type": "module", + "description": "The Graphviz plugin's preview page; `pnpm build` writes it to ../web.", + "scripts": { + "build": "tsc --noEmit && vite build", + "test": "vitest run" + }, + "dependencies": { + "@viz-js/viz": "3.31.0" + }, + "devDependencies": { + "@types/node": "^26.6.6", + "typescript": "~6.0.3", + "vite": "^8.0.16", + "vitest": "^5.0.5" + } +} diff --git a/plugins/official/graphviz/web-src/pnpm-lock.yaml b/plugins/official/graphviz/web-src/pnpm-lock.yaml new file mode 100644 index 00000000..84c2010e --- /dev/null +++ b/plugins/official/graphviz/web-src/pnpm-lock.yaml @@ -0,0 +1,669 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + '@viz-js/viz': + specifier: 3.31.0 + version: 3.31.0 + devDependencies: + '@types/node': + specifier: ^26.6.6 + version: 26.6.6 + typescript: + specifier: ~6.0.3 + version: 6.0.3 + vite: + specifier: ^8.0.16 + version: 8.3.5(@types/node@26.6.6) + vitest: + specifier: ^5.0.5 + version: 5.0.5(@types/node@26.6.6)(vite@8.3.5(@types/node@26.6.6)) + +packages: + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@oxc-project/types@0.156.0': + resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} + + '@rolldown/binding-android-arm-eabi@1.2.16': + resolution: {integrity: sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.16': + resolution: {integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.16': + resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.16': + resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.16': + resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.16': + resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.16': + resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.16': + resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.16': + resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.16': + resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.16': + resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.16': + resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.16': + resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.10': + resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==} + + '@types/node@26.6.6': + resolution: {integrity: sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==} + + '@vitest/mocker@5.0.5': + resolution: {integrity: sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==} + peerDependencies: + msw: ^2.4.9 || ^3.0.0 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/spy@5.0.5': + resolution: {integrity: sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==} + + '@viz-js/viz@3.31.0': + resolution: {integrity: sha512-r7zlQdRvcwvIpjHGgs+KNWHeE/P5/Dq7k8ZAKaMCbZqomxCBJV78gVuQYaHzFVca+kB0mX0fMW9UFevCOBG50A==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + chai@6.3.0: + resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} + engines: {node: '>=18'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + magic-string@1.4.5: + resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + obug@3.0.0: + resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} + engines: {node: '>=12.20.0'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + postcss@8.5.32: + resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} + engines: {node: ^10 || ^12 || >=14} + + rolldown@1.2.16: + resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} + engines: {node: '>=0.10.0'} + + std-env@4.3.0: + resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + + tinybench@6.2.3: + resolution: {integrity: sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==} + engines: {node: '>=20.0.0'} + + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + typescript@6.0.3: + resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@8.9.0: + resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} + + vite@8.3.5: + resolution: {integrity: sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.7.1 || ^0.8.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@5.0.5: + resolution: {integrity: sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==} + engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 5.0.5 + '@vitest/browser-preview': 5.0.5 + '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 + '@vitest/coverage-istanbul': 5.0.5 + '@vitest/coverage-v8': 5.0.5 + '@vitest/ui': 5.0.5 + happy-dom: '*' + jsdom: '*' + vite: ^6.4.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + why-is-node-running@3.2.1: + resolution: {integrity: sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==} + engines: {node: '>=20.11'} + hasBin: true + +snapshots: + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@oxc-project/types@0.156.0': {} + + '@rolldown/binding-android-arm-eabi@1.2.16': + optional: true + + '@rolldown/binding-android-arm64@1.2.16': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.16': + optional: true + + '@rolldown/binding-darwin-x64@1.2.16': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.16': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.16': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.16': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.16': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.16': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.16': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.10': {} + + '@types/node@26.6.6': + dependencies: + undici-types: 8.9.0 + + '@vitest/mocker@5.0.5(vite@8.3.5(@types/node@26.6.6))': + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@vitest/spy': 5.0.5 + estree-walker: 3.0.3 + magic-string: 1.4.5 + optionalDependencies: + vite: 8.3.5(@types/node@26.6.6) + + '@vitest/spy@5.0.5': {} + + '@viz-js/viz@3.31.0': {} + + assertion-error@2.0.1: {} + + chai@6.3.0: {} + + detect-libc@2.1.2: {} + + es-module-lexer@2.3.2: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.10 + + expect-type@1.4.0: {} + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + fsevents@2.3.3: + optional: true + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + magic-string@1.4.5: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + nanoid@3.3.20: {} + + obug@3.0.0: {} + + picocolors@1.1.1: {} + + picomatch@4.0.7: {} + + postcss@8.5.32: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.2 + + rolldown@1.2.16: + dependencies: + '@oxc-project/types': 0.156.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.16 + '@rolldown/binding-android-arm64': 1.2.16 + '@rolldown/binding-darwin-arm64': 1.2.16 + '@rolldown/binding-darwin-x64': 1.2.16 + '@rolldown/binding-freebsd-x64': 1.2.16 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.16 + '@rolldown/binding-linux-arm64-gnu': 1.2.16 + '@rolldown/binding-linux-arm64-musl': 1.2.16 + '@rolldown/binding-linux-ppc64-gnu': 1.2.16 + '@rolldown/binding-linux-s390x-gnu': 1.2.16 + '@rolldown/binding-linux-x64-gnu': 1.2.16 + '@rolldown/binding-linux-x64-musl': 1.2.16 + '@rolldown/binding-openharmony-arm64': 1.2.16 + '@rolldown/binding-win32-arm64-msvc': 1.2.16 + '@rolldown/binding-win32-x64-msvc': 1.2.16 + + source-map-js@1.2.2: {} + + std-env@4.3.0: {} + + tinybench@6.2.3: {} + + tinyexec@1.3.1: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + typescript@6.0.3: {} + + undici-types@8.9.0: {} + + vite@8.3.5(@types/node@26.6.6): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.32 + rolldown: 1.2.16 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 26.6.6 + fsevents: 2.3.3 + + vitest@5.0.5(@types/node@26.6.6)(vite@8.3.5(@types/node@26.6.6)): + dependencies: + '@types/chai': 5.2.3 + '@vitest/mocker': 5.0.5(vite@8.3.5(@types/node@26.6.6)) + chai: 6.3.0 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 1.4.5 + obug: 3.0.0 + picomatch: 4.0.7 + std-env: 4.3.0 + tinybench: 6.2.3 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + vite: 8.3.5(@types/node@26.6.6) + why-is-node-running: 3.2.1 + optionalDependencies: + '@types/node': 26.6.6 + transitivePeerDependencies: + - msw + + why-is-node-running@3.2.1: {} diff --git a/plugins/official/graphviz/web-src/src/main.ts b/plugins/official/graphviz/web-src/src/main.ts new file mode 100644 index 00000000..04f8d5d8 --- /dev/null +++ b/plugins/official/graphviz/web-src/src/main.ts @@ -0,0 +1,213 @@ +/** + * The Graphviz plugin's preview: renders the `.dot` file it is opened beside + * (read only: the text editor next to it is where it changes) with viz.js, + * follows the IDE theme, zooms and pans, exports SVG and PNG through the + * IDE's save dialog, and sends what Graphviz reports to the plugin's code, + * which turns it into the file's problems. + */ +import { instance, type Viz } from "@viz-js/viz"; +import { ENGINES, type Engine, exportName, problemsOf, renderOptions } from "./render"; + +const RENDER_DELAY_MS = 150; +const MIN_ZOOM = 0.1; +const MAX_ZOOM = 8; +/** The most Fit enlarges a small graph to (opening a file never enlarges it). */ +const MAX_FIT = 4; + +const $ = (id: string) => document.getElementById(id) as T; + +function start(bridge: OpenideaBridge) { + const stage = $("stage"); + const canvas = $("canvas"); + const banner = $("banner"); + const engineSelect = $("engine"); + const zoomLabel = $("zoom-label"); + + for (const e of ENGINES) engineSelect.add(new Option(e, e)); + + let viz: Viz | null = null; + let text = ""; + let name = "graph.dot"; + let engine: Engine = "dot"; + let zoom = 1; + let fitted = true; + // How far fitting may enlarge: 1 until the user asks for Fit. + let fitCap = 1; + let timer = 0; + let lastProblems = ""; + + const foreground = () => bridge.theme?.vars["--openidea-fg"] ?? null; + + function setZoom(z: number, keepFit = false) { + zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, z)); + fitted = keepFit; + // `zoom`, not a transform: the scroll area follows the scaled size. + canvas.style.zoom = String(zoom); + zoomLabel.textContent = `${Math.round(zoom * 100)}%`; + } + + function fit() { + const svg = canvas.querySelector("svg"); + if (!svg) return; + // Graphviz sizes its SVG in points; these are CSS pixels at 100%. + const w = svg.width.baseVal.value; + const h = svg.height.baseVal.value; + if (!w || !h) return; + // The canvas's padding (16px a side) scales with it; a pixel spare for rounding. + const pad = 32; + const z = Math.min((stage.clientWidth - 1) / (w + pad), (stage.clientHeight - 1) / (h + pad), fitCap); + setZoom(z > 0 && Number.isFinite(z) ? z : 1, true); + } + + /** What Graphviz said, to the plugin (only when it changed: each one republishes the problems). */ + function report(problems: ReturnType) { + const key = JSON.stringify(problems); + if (key === lastProblems) return; + lastProblems = key; + bridge.postMessage(JSON.stringify({ op: "problems", items: problems })); + } + + function render() { + if (!viz) return; + const result = viz.render(text, renderOptions(engine, foreground())); + const problems = problemsOf(result); + report(problems); + if (result.status === "success") { + canvas.innerHTML = result.output; + canvas.classList.remove("stale"); + banner.hidden = true; + if (fitted) fit(); + } else { + // The last good graph stays, dimmed, under what went wrong. + canvas.classList.add("stale"); + banner.hidden = false; + banner.textContent = problems.map((p) => (p.line ? `Line ${p.line}: ${p.message}` : p.message)).join("\n"); + } + } + + const schedule = (delay = RENDER_DELAY_MS) => { + clearTimeout(timer); + timer = window.setTimeout(render, delay); + }; + + /** The graph as Graphviz draws it, without the theme's defaults. */ + function exportSvg(): string | null { + if (!viz) return null; + const result = viz.render(text, renderOptions(engine, null)); + return result.status === "success" ? result.output : null; + } + + /** Runs an export; a failure (no dialog, the image not drawn) shows in the banner. */ + async function exporting(run: () => Promise) { + try { + await run(); + } catch (e) { + banner.hidden = false; + banner.textContent = `Export failed: ${e instanceof Error ? e.message : String(e)}`; + } + } + + async function saveSvg() { + const svg = exportSvg(); + if (!svg) return; + await bridge.saveFile({ + name: exportName(name, "svg"), + data: svg, + filters: [{ name: "SVG image", extensions: ["svg"] }], + }); + } + + async function savePng() { + const svg = exportSvg(); + if (!svg) return; + const url = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" })); + try { + const img = new Image(); + await new Promise((resolve, reject) => { + img.onload = () => resolve(); + img.onerror = () => reject(new Error("the graph could not be drawn as an image")); + img.src = url; + }); + const scale = 2; + const c = document.createElement("canvas"); + c.width = Math.ceil(img.naturalWidth * scale); + c.height = Math.ceil(img.naturalHeight * scale); + const ctx = c.getContext("2d")!; + ctx.scale(scale, scale); + ctx.drawImage(img, 0, 0); + const png = await new Promise((resolve) => c.toBlob(resolve, "image/png")); + if (!png) throw new Error("the image could not be encoded"); + await bridge.saveFile({ + name: exportName(name, "png"), + data: png, + filters: [{ name: "PNG image", extensions: ["png"] }], + }); + } finally { + URL.revokeObjectURL(url); + } + } + + engineSelect.addEventListener("change", () => { + engine = engineSelect.value as Engine; + fitted = true; + schedule(0); + }); + $("zoom-in").addEventListener("click", () => setZoom(zoom * 1.25)); + $("zoom-out").addEventListener("click", () => setZoom(zoom / 1.25)); + $("zoom-fit").addEventListener("click", () => { + fitCap = MAX_FIT; + fit(); + }); + $("zoom-reset").addEventListener("click", () => setZoom(1)); + $("export-svg").addEventListener("click", () => void exporting(saveSvg)); + $("export-png").addEventListener("click", () => void exporting(savePng)); + // ⌘/Ctrl + wheel (and pinch) zooms; the wheel alone scrolls. + stage.addEventListener( + "wheel", + (e) => { + if (!e.ctrlKey && !e.metaKey) return; + e.preventDefault(); + setZoom(zoom * Math.exp(-e.deltaY / 300)); + }, + { passive: false }, + ); + // Dragging pans. + stage.addEventListener("pointerdown", (e) => { + if (e.button !== 0) return; + const [x, y, left, top] = [e.clientX, e.clientY, stage.scrollLeft, stage.scrollTop]; + stage.setPointerCapture(e.pointerId); + stage.classList.add("panning"); + const move = (m: PointerEvent) => { + stage.scrollLeft = left - (m.clientX - x); + stage.scrollTop = top - (m.clientY - y); + }; + const up = () => { + stage.classList.remove("panning"); + stage.removeEventListener("pointermove", move); + stage.removeEventListener("pointerup", up); + }; + stage.addEventListener("pointermove", move); + stage.addEventListener("pointerup", up); + }); + new ResizeObserver(() => fitted && fit()).observe(stage); + bridge.onThemeChange(() => schedule(0)); + bridge.document.onChange((s) => { + text = s.text; + schedule(); + }); + + void (async () => { + const [doc, v] = await Promise.all([bridge.document.get(), instance()]); + viz = v; + text = doc.text; + name = doc.name || name; + render(); + })().catch((e: unknown) => { + banner.hidden = false; + banner.textContent = `The preview could not start: ${e instanceof Error ? e.message : String(e)}`; + }); +} + +const bridge = window.openidea; +if (bridge) start(bridge); +else document.body.textContent = "This page runs inside OpenIDEA."; diff --git a/plugins/official/graphviz/web-src/src/openidea.d.ts b/plugins/official/graphviz/web-src/src/openidea.d.ts new file mode 100644 index 00000000..3b370f10 --- /dev/null +++ b/plugins/official/graphviz/web-src/src/openidea.d.ts @@ -0,0 +1,40 @@ +/** The IDE's frame bridge (`window.openidea`), injected before the page's scripts. */ +interface OpenideaDocumentState { + version: number; + text: string; +} + +interface OpenideaTextEdit { + from: number; + to: number; + insert: string; +} + +interface OpenideaFileFilter { + name: string; + extensions: string[]; +} + +interface OpenideaBridge { + postMessage(text: string): void; + onMessage(fn: (text: string) => void): void; + readonly theme: { dark: boolean; vars: Readonly> } | null; + onThemeChange(fn: (theme: { dark: boolean; vars: Readonly> }) => void): void; + document: { + /** `name`: the file's name, without its directory. */ + get(): Promise; + onChange(fn: (state: OpenideaDocumentState) => void): void; + edit(version: number, edits: OpenideaTextEdit[]): Promise<{ version: number }>; + replace(version: number, text: string): Promise<{ version: number }>; + }; + saveFile(options: { + name: string; + data: string | Uint8Array | ArrayBuffer | Blob; + filters?: OpenideaFileFilter[]; + }): Promise; + openFile(options?: { filters?: OpenideaFileFilter[] }): Promise<{ name: string; data: Uint8Array } | null>; +} + +interface Window { + openidea?: OpenideaBridge; +} diff --git a/plugins/official/graphviz/web-src/src/render.test.ts b/plugins/official/graphviz/web-src/src/render.test.ts new file mode 100644 index 00000000..fe204b45 --- /dev/null +++ b/plugins/official/graphviz/web-src/src/render.test.ts @@ -0,0 +1,45 @@ +import { instance } from "@viz-js/viz"; +import { describe, expect, it } from "vitest"; +import { ENGINES, exportName, graphvizColor, problemsOf, renderOptions } from "./render"; + +describe("the preview's rendering", () => { + it("renders with the theme's colour as a default the graph can override", async () => { + const viz = await instance(); + const themed = viz.render('digraph { a -> b; c [color="red"] }', renderOptions("dot", "rgb(200, 200, 200)")); + expect(themed.status).toBe("success"); + const svg = themed.status === "success" ? themed.output : ""; + expect(svg).toContain('stroke="#c8c8c8"'); + expect(svg).toContain('stroke="red"'); + const plain = viz.render("digraph { a -> b }", renderOptions("dot", null)); + expect(plain.status === "success" && plain.output).not.toContain("#c8c8c8"); + }); + + it("names the line of a syntax error", async () => { + const viz = await instance(); + const result = viz.render("digraph {\n a -> b\n c -> }\n", renderOptions("dot", null)); + expect(result.status).toBe("failure"); + const [p] = problemsOf(result); + expect(p).toMatchObject({ line: 3, level: "error" }); + expect(p!.message).toMatch(/syntax error/); + }); + + it("offers only engines this Graphviz has", async () => { + const viz = await instance(); + for (const e of ENGINES) expect(viz.engines).toContain(e); + }); + + it("turns the theme's colours into Graphviz's", () => { + expect(graphvizColor("rgb(200, 200, 200)")).toBe("#c8c8c8"); + expect(graphvizColor("rgba(0, 128, 255, 0.5)")).toBe("#0080ff80"); + expect(graphvizColor("rgb(1 2 3 / 50%)")).toBe("#01020380"); + expect(graphvizColor("#ABCDEF")).toBe("#abcdef"); + expect(graphvizColor("var(--x)")).toBeNull(); + expect(renderOptions("dot", "nonsense").nodeAttributes).toBeUndefined(); + }); + + it("names exports after the file", () => { + expect(exportName("flow.dot", "svg")).toBe("flow.svg"); + expect(exportName("Flow.GV", "png")).toBe("Flow.png"); + expect(exportName("", "svg")).toBe("graph.svg"); + }); +}); diff --git a/plugins/official/graphviz/web-src/src/render.ts b/plugins/official/graphviz/web-src/src/render.ts new file mode 100644 index 00000000..a0507acc --- /dev/null +++ b/plugins/official/graphviz/web-src/src/render.ts @@ -0,0 +1,68 @@ +/** + * The preview's logic apart from the page: rendering options, Graphviz's + * messages as problems, export names. Kept free of the DOM so it is tested + * against the real Graphviz in Node. + */ +import type { RenderOptions, RenderResult } from "@viz-js/viz"; + +/** Layout engines offered, the default first. */ +export const ENGINES = ["dot", "neato", "fdp", "sfdp", "circo", "twopi", "osage", "patchwork"] as const; +export type Engine = (typeof ENGINES)[number]; + +export interface Problem { + /** 1-based, when Graphviz names one. */ + line: number | null; + message: string; + level: "error" | "warning"; +} + +/** + * Defaults a graph can still override: transparent background and the IDE's + * text colour, so an unstyled graph reads in a dark theme too. Exports use + * none of them (`null`): they look as Graphviz draws them. + */ +export function renderOptions(engine: Engine, foreground: string | null): RenderOptions { + const options: RenderOptions = { format: "svg", engine }; + const color = foreground && graphvizColor(foreground); + if (color) { + options.graphAttributes = { bgcolor: "transparent", color, fontcolor: color }; + options.nodeAttributes = { color, fontcolor: color }; + options.edgeAttributes = { color, fontcolor: color }; + } + return options; +} + +/** + * A CSS colour as Graphviz reads it (`#rrggbb[aa]`): the theme's variables + * are `rgb()` / `rgba()`, which it doesn't know. `null` when not one. + */ +export function graphvizColor(css: string): string | null { + const hex = (n: number) => + Math.round(Math.min(255, Math.max(0, n))) + .toString(16) + .padStart(2, "0"); + const value = css.trim(); + if (/^#([0-9a-f]{6}|[0-9a-f]{8})$/i.test(value)) return value.toLowerCase(); + const m = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:\s*[,/]\s*([\d.]+)(%?))?\s*\)$/i.exec(value); + if (!m) return null; + const alpha = m[4] === undefined ? 1 : Number(m[4]) / (m[5] ? 100 : 1); + return `#${hex(+m[1]!)}${hex(+m[2]!)}${hex(+m[3]!)}${alpha < 1 ? hex(alpha * 255) : ""}`; +} + +/** What Graphviz reported, as problems (on the line it names, if any). */ +export function problemsOf(result: RenderResult): Problem[] { + return result.errors.map((e) => { + const line = /\bline (\d+)\b/.exec(e.message); + return { + line: line ? Number(line[1]) : null, + message: e.message.replace(/^(Error|Warning):\s*/i, "").trim(), + level: e.level === "warning" ? "warning" : "error", + }; + }); +} + +/** The name an export starts with: the file's, without `.dot` / `.gv`. */ +export function exportName(file: string, extension: string): string { + const base = file.replace(/\.(dot|gv)$/i, "") || "graph"; + return `${base}.${extension}`; +} diff --git a/plugins/official/graphviz/web-src/src/style.css b/plugins/official/graphviz/web-src/src/style.css new file mode 100644 index 00000000..013d14e2 --- /dev/null +++ b/plugins/official/graphviz/web-src/src/style.css @@ -0,0 +1,89 @@ +html, +body { + margin: 0; + width: 100%; + height: 100%; + overflow: hidden; + font: var(--openidea-font-size, 13px) var(--openidea-font-ui, system-ui, sans-serif); + color: var(--openidea-fg); + background: var(--openidea-bg, transparent); +} +.toolbar { + position: absolute; + top: 8px; + right: 8px; + z-index: 1; + display: flex; + align-items: center; + gap: 2px; + padding: 2px; + border: 1px solid var(--openidea-border); + border-radius: 6px; + background: var(--openidea-bg-elevated, var(--openidea-bg)); +} +.toolbar button, +.toolbar select { + height: 24px; + min-width: 24px; + padding: 0 6px; + font: inherit; + font-size: 12px; + color: var(--openidea-fg); + background: transparent; + border: 1px solid transparent; + border-radius: 4px; + cursor: pointer; +} +.toolbar select { + border-color: var(--openidea-border); + background: var(--openidea-bg-input, transparent); +} +.toolbar button:hover { + background: var(--openidea-bg-hover); +} +.toolbar .sep { + width: 1px; + height: 16px; + margin: 0 2px; + background: var(--openidea-border); +} +#zoom-label { + display: inline-block; + min-width: 36px; + font-variant-numeric: tabular-nums; +} +.stage { + position: absolute; + inset: 0; + overflow: auto; + cursor: grab; +} +.stage.panning { + cursor: grabbing; +} +.canvas { + display: inline-block; + padding: 16px; + user-select: none; +} +.canvas svg { + display: block; +} +.canvas.stale { + opacity: 0.35; +} +.banner { + position: absolute; + left: 8px; + right: 8px; + bottom: 8px; + z-index: 1; + padding: 6px 8px; + white-space: pre-wrap; + font-family: var(--openidea-font-mono, ui-monospace, monospace); + font-size: 12px; + color: var(--openidea-danger); + border: 1px solid color-mix(in srgb, var(--openidea-danger) 40%, transparent); + border-radius: 6px; + background: var(--openidea-bg-elevated, var(--openidea-bg)); +} diff --git a/plugins/official/graphviz/web-src/tsconfig.json b/plugins/official/graphviz/web-src/tsconfig.json new file mode 100644 index 00000000..da498883 --- /dev/null +++ b/plugins/official/graphviz/web-src/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "isolatedModules": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "types": ["vite/client", "node"] + }, + "include": ["src", "vite.config.ts"] +} diff --git a/plugins/official/graphviz/web-src/vite.config.ts b/plugins/official/graphviz/web-src/vite.config.ts new file mode 100644 index 00000000..17c7581d --- /dev/null +++ b/plugins/official/graphviz/web-src/vite.config.ts @@ -0,0 +1,18 @@ +/** + * Builds the page into ../web (not checked in: plugins/build.sh builds it). + * Relative URLs throughout: the IDE serves the page from the plugin package + * under its own URL scheme. + */ +import path from "node:path"; +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + base: "./", + build: { + outDir: path.resolve(import.meta.dirname, "../web"), + emptyOutDir: true, + target: "es2022", + sourcemap: false, + chunkSizeWarningLimit: 4096, + }, +}); diff --git a/templates/theme-plugin/README.md b/plugins/official/harbor-night/README.md similarity index 74% rename from templates/theme-plugin/README.md rename to plugins/official/harbor-night/README.md index 63f9a27a..34eaa5e8 100644 --- a/templates/theme-plugin/README.md +++ b/plugins/official/harbor-night/README.md @@ -1,12 +1,13 @@ -# Theme plugin template +# Harbor Night -A complete OpenIDEA theme plugin with one worked example, **Harbor Night**: a -dark theme with slate surfaces, a teal accent and a warm syntax palette. Copy -this folder to start your own theme. Full documentation, the token reference -and porting guides are in [`docs/plugins/themes.md`](../../docs/plugins/themes.md). +An OpenIDEA theme plugin, **Harbor Night**: a dark theme with slate surfaces, a +teal accent and a warm syntax palette. It is also where new themes start: +`openidea-plugin new --template theme` copies its theme files, or copy this +folder. Full documentation, the token reference and porting guides are in +[`docs/plugins/themes.md`](../../../docs/plugins/themes.md). ``` -theme-plugin/ +harbor-night/ ├─ plugin.toml # manifest: id, name, version, the theme files └─ themes/ ├─ harbor-night.theme.json # UI colours, every themeable token, grouped like tokens.css @@ -17,8 +18,9 @@ A theme plugin is data only: no code, no WebAssembly, no build step. ## Make your own -1. Copy the folder, for example to `~/openidea-themes/theme-my-theme`. -2. In `plugin.toml`, change `id` (lowercase, `a-z 0-9 - _`), `name`, +1. Run `openidea-plugin new --template theme`, or copy the folder, for + example to `~/openidea-themes/my-theme`. +2. In `plugin.toml`, change `id` (lowercase, `a-z 0-9 - _ .`), `name`, `description`, `authors` and the two paths. 3. Rename the theme files. In the theme file, set `id`, `name` and `kind` (`"dark"` or `"light"`, the built-in base for anything you leave out). @@ -49,5 +51,5 @@ JSON or values are reported in Settings › Plugins with the file and line. ## Licence -The template and Harbor Night are part of OpenIDEA (Apache-2.0). When you port +Harbor Night is part of OpenIDEA (Apache-2.0). When you port someone else's theme, keep its licence and credit its authors. diff --git a/plugins/official/harbor-night/plugin.toml b/plugins/official/harbor-night/plugin.toml new file mode 100644 index 00000000..1fdc1d7e --- /dev/null +++ b/plugins/official/harbor-night/plugin.toml @@ -0,0 +1,16 @@ +# A theme plugin is data only: no `wasm`, no capabilities, nothing to compile. +# `openidea-plugin new --template theme` starts a new theme from this one. +id = "openidea.harbor-night" +name = "Harbor Night" +version = "0.1.0" +description = "A dark theme: slate surfaces, a teal accent and a warm syntax palette." +authors = ["OpenIDEA contributors"] +license = "Apache-2.0" +change-notes = "1.0.0 — first release." +engines.openidea = "^1.0" + +# One entry per theme. `editor-scheme` is optional: its tokens are merged over +# the theme's (IntelliJ's .theme.json + .icls pair). +[[contributes.themes]] +path = "themes/harbor-night.theme.json" +editor-scheme = "themes/harbor-night.scheme.json" diff --git a/templates/theme-plugin/themes/harbor-night.scheme.json b/plugins/official/harbor-night/themes/harbor-night.scheme.json similarity index 100% rename from templates/theme-plugin/themes/harbor-night.scheme.json rename to plugins/official/harbor-night/themes/harbor-night.scheme.json diff --git a/templates/theme-plugin/themes/harbor-night.theme.json b/plugins/official/harbor-night/themes/harbor-night.theme.json similarity index 100% rename from templates/theme-plugin/themes/harbor-night.theme.json rename to plugins/official/harbor-night/themes/harbor-night.theme.json diff --git a/plugins/official/key-promoter/.gitignore b/plugins/official/key-promoter/.gitignore new file mode 100644 index 00000000..ea8c4bf7 --- /dev/null +++ b/plugins/official/key-promoter/.gitignore @@ -0,0 +1 @@ +/target diff --git a/plugins/official/key-promoter/Cargo.lock b/plugins/official/key-promoter/Cargo.lock new file mode 100644 index 00000000..089dc610 --- /dev/null +++ b/plugins/official/key-promoter/Cargo.lock @@ -0,0 +1,333 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "openidea-plugin-openidea-key-promoter" +version = "0.1.0" +dependencies = [ + "openidea-plugin", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[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 = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +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 = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/plugins/official/key-promoter/Cargo.toml b/plugins/official/key-promoter/Cargo.toml new file mode 100644 index 00000000..9ecb09a7 --- /dev/null +++ b/plugins/official/key-promoter/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "openidea-plugin-openidea-key-promoter" +version = "0.1.0" +edition = "2024" +publish = false + +# A plugin builds on its own (target wasm32-wasip2), outside any IDE workspace. +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../sdk/rust/openidea-plugin" } + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/plugins/official/key-promoter/dist/plugin.wasm b/plugins/official/key-promoter/dist/plugin.wasm new file mode 100644 index 00000000..daefc884 Binary files /dev/null and b/plugins/official/key-promoter/dist/plugin.wasm differ diff --git a/plugins/official/key-promoter/dist/plugin.wasm.sources b/plugins/official/key-promoter/dist/plugin.wasm.sources new file mode 100644 index 00000000..9965326d --- /dev/null +++ b/plugins/official/key-promoter/dist/plugin.wasm.sources @@ -0,0 +1 @@ +345c39f818e4950914bf3fcc795fac9e30ff2d87ad3e66f24c7bc00800f92980 diff --git a/plugins/official/key-promoter/plugin.toml b/plugins/official/key-promoter/plugin.toml new file mode 100644 index 00000000..10f032b4 --- /dev/null +++ b/plugins/official/key-promoter/plugin.toml @@ -0,0 +1,31 @@ +id = "openidea.key-promoter" +name = "Key Promoter" +version = "0.1.0" +description = "Shows the keyboard shortcut of an action you ran with the mouse, and counts how often you could have used it." +authors = ["OpenIDEA contributors"] +license = "Apache-2.0" +change-notes = "0.1.0 — first release: shortcut tips, statistics, per-action \"don't show again\"." +engines.openidea = "^1.0" +wasm = "dist/plugin.wasm" +# Actions arrive in batches (a few seconds apart while the plugin is idle), +# so it is not woken for every click. +activation = ["on-event:action-performed", "on-command:*"] + +[capabilities] +# `events.input`: which actions you run and how (keyboard, menu, toolbar…). +required = ["events.input", "storage"] + +[[contributes.commands]] +id = "statistics" +title = "Key Promoter: Show Statistics" +category = "Key Promoter" + +[[contributes.commands]] +id = "reset" +title = "Key Promoter: Reset Statistics" +category = "Key Promoter" + +[[contributes.commands]] +id = "suppress-last" +title = "Key Promoter: Don't Show Tips for the Last Action" +category = "Key Promoter" diff --git a/plugins/official/key-promoter/src/lib.rs b/plugins/official/key-promoter/src/lib.rs new file mode 100644 index 00000000..4636e3db --- /dev/null +++ b/plugins/official/key-promoter/src/lib.rs @@ -0,0 +1,164 @@ +//! Key Promoter for OpenIDEA: when you run an action with the mouse (menu, +//! toolbar, context menu) that has a keyboard shortcut, it tells you the +//! shortcut. Counts persist in storage, so the tips survive restarts and the +//! instance being reclaimed while you work. + +use openidea_plugin::host::{self, storage}; +use openidea_plugin::{ActionSource, Error, Event, Invocation, NotificationLevel, Plugin, register_plugin}; + +/// Tips for one action are shown on these counts, then every `REPEAT_EVERY`. +const FIRST_TIPS: [u32; 3] = [1, 3, 10]; +const REPEAT_EVERY: u32 = 25; +const COUNT: &str = "count:"; +const TITLE: &str = "title:"; +const SUPPRESSED: &str = "suppressed:"; +const LAST: &str = "last-action"; + +#[derive(Default)] +pub struct KeyPromoter; + +fn get_u32(key: &str) -> u32 { + storage::get(key).ok().flatten().and_then(|v| v.parse().ok()).unwrap_or(0) +} + +impl Plugin for KeyPromoter { + fn run_command(&mut self, id: &str, _ctx: &Invocation, _arg: Option<&str>) -> Result, Error> { + match id { + "statistics" => { + let mut rows: Vec<(u32, String)> = storage::keys(COUNT)? + .into_iter() + .map(|k| { + let action = &k[COUNT.len()..]; + let title = storage::get(&format!("{TITLE}{action}")) + .ok() + .flatten() + .unwrap_or_else(|| action.to_owned()); + (get_u32(&k), title) + }) + .collect(); + rows.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1))); + let body = if rows.is_empty() { + "No missed shortcuts yet.".to_owned() + } else { + rows.iter().take(15).map(|(n, t)| format!("{n}× {t}")).collect::>().join("\n") + }; + host::notify(NotificationLevel::Info, "Key Promoter: missed shortcuts", &body); + Ok(Some(body)) + } + "reset" => { + for k in storage::keys("")? { + storage::delete(&k)?; + } + Ok(Some("Key Promoter statistics were reset.".into())) + } + "suppress-last" => { + let action = storage::get(LAST)?.ok_or("no tip was shown yet")?; + storage::set(&format!("{SUPPRESSED}{action}"), "1")?; + Ok(Some(format!("No more tips for {action}."))) + } + _ => Err(Error::NotFound(format!("command {id}"))), + } + } + + fn handle_events(&mut self, events: &[Event], _ctx: &Invocation) { + // One tip per batch at most: the last action that deserves one. + let mut tip = None; + for e in events { + let Event::ActionPerformed(a) = e else { continue }; + if a.source == ActionSource::Keyboard { + continue; + } + let Some(shortcut) = &a.shortcut else { continue }; + if storage::get(&format!("{SUPPRESSED}{}", a.action)).ok().flatten().is_some() { + continue; + } + let key = format!("{COUNT}{}", a.action); + let n = get_u32(&key) + 1; + if storage::set(&key, &n.to_string()).is_err() { + return; // storage denied or full: nothing to count with + } + let _ = storage::set(&format!("{TITLE}{}", a.action), &a.title); + if FIRST_TIPS.contains(&n) || n.is_multiple_of(REPEAT_EVERY) { + tip = Some((a.clone(), shortcut.clone(), n)); + } + } + if let Some((a, shortcut, n)) = tip { + let _ = storage::set(LAST, &a.action); + let times = if n == 1 { "once".to_owned() } else { format!("{n} times") }; + host::notify( + NotificationLevel::Info, + &format!("{}: {shortcut}", a.title), + &format!("You ran it with the mouse {times}. Press {shortcut} next time."), + ); + } + } +} + +register_plugin!(KeyPromoter); + +#[cfg(test)] +mod tests { + use super::*; + use openidea_plugin::ActionPerformed; + use openidea_plugin::mock::MockHost; + + fn action(id: &str, source: ActionSource, shortcut: Option<&str>) -> Event { + Event::ActionPerformed(ActionPerformed { + action: id.into(), + title: format!("Title of {id}"), + source, + shortcut: shortcut.map(str::to_owned), + }) + } + + #[test] + fn tips_for_mouse_use_of_actions_with_shortcuts() { + let host = MockHost::install(); + let ctx = host.invocation(); + let mut p = KeyPromoter; + p.handle_events( + &[ + action("a", ActionSource::Keyboard, Some("Ctrl+A")), + action("b", ActionSource::Menu, None), + action("c", ActionSource::Toolbar, Some("Ctrl+C")), + ], + &ctx, + ); + let notes = host.notifications(); + assert_eq!(notes.len(), 1); + assert_eq!(notes[0].title, "Title of c: Ctrl+C"); + assert!(notes[0].body.contains("once")); + // Second use: counted, no tip (next at 3). + p.handle_events(&[action("c", ActionSource::Menu, Some("Ctrl+C"))], &ctx); + assert_eq!(host.notifications().len(), 1); + p.handle_events(&[action("c", ActionSource::Menu, Some("Ctrl+C"))], &ctx); + assert!(host.notifications()[1].body.contains("3 times")); + assert_eq!(host.storage()["count:c"], "3"); + } + + #[test] + fn statistics_survive_a_new_instance_and_can_be_suppressed() { + let host = MockHost::install(); + let ctx = host.invocation(); + KeyPromoter.handle_events(&[action("x", ActionSource::Menu, Some("F2"))], &ctx); + // A fresh instance (after idle reclaim) reads the counts back. + let stats = KeyPromoter.run_command("statistics", &ctx, None).unwrap().unwrap(); + assert_eq!(stats, "1× Title of x"); + KeyPromoter.run_command("suppress-last", &ctx, None).unwrap(); + KeyPromoter.handle_events(&vec![action("x", ActionSource::Menu, Some("F2")); 2], &ctx); + assert_eq!(host.notifications().len(), 2, "the tip and the statistics; none after suppressing"); + KeyPromoter.run_command("reset", &ctx, None).unwrap(); + assert!(host.storage().is_empty()); + } + + #[test] + fn without_storage_it_stays_quiet() { + let host = MockHost::install().with_capabilities(&["events.input"]); + KeyPromoter.handle_events(&[action("x", ActionSource::Menu, Some("F2"))], &host.invocation()); + assert!(host.notifications().is_empty()); + assert_eq!( + KeyPromoter.run_command("statistics", &host.invocation(), None).unwrap_err(), + Error::Denied("storage".into()) + ); + } +} diff --git a/plugins/official/license-header/Cargo.lock b/plugins/official/license-header/Cargo.lock new file mode 100644 index 00000000..736eea2b --- /dev/null +++ b/plugins/official/license-header/Cargo.lock @@ -0,0 +1,333 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "openidea-plugin-openidea-license-header" +version = "0.1.0" +dependencies = [ + "openidea-plugin", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[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 = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +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 = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/plugins/official/license-header/Cargo.toml b/plugins/official/license-header/Cargo.toml new file mode 100644 index 00000000..efac88b0 --- /dev/null +++ b/plugins/official/license-header/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "openidea-plugin-openidea-license-header" +version = "0.1.0" +edition = "2024" +publish = false + +# A plugin builds on its own (target wasm32-wasip2), outside any IDE workspace. +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../sdk/rust/openidea-plugin" } + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/plugins/official/license-header/dist/plugin.wasm b/plugins/official/license-header/dist/plugin.wasm new file mode 100644 index 00000000..6cd6d293 Binary files /dev/null and b/plugins/official/license-header/dist/plugin.wasm differ diff --git a/plugins/official/license-header/dist/plugin.wasm.sources b/plugins/official/license-header/dist/plugin.wasm.sources new file mode 100644 index 00000000..01859b4b --- /dev/null +++ b/plugins/official/license-header/dist/plugin.wasm.sources @@ -0,0 +1 @@ +6a4210a3978f058b3526427eb41ef398924e8c011cc4dc53c19f5419d31501f3 diff --git a/plugins/official/license-header/plugin.toml b/plugins/official/license-header/plugin.toml new file mode 100644 index 00000000..af970e2e --- /dev/null +++ b/plugins/official/license-header/plugin.toml @@ -0,0 +1,35 @@ +id = "openidea.license-header" +name = "License Header" +version = "0.1.0" +description = "Keeps a copyright and SPDX license header at the top of source files: files without one are reported when they open, a quick fix adds it, and a project scan lists every file that still needs one." +authors = ["OpenIDEA contributors"] +license = "Apache-2.0" +change-notes = "0.1.0 — first release: missing headers reported on open and save, Add License Header quick fix and command, project scan in the background." +engines.openidea = "^1.0" +wasm = "dist/plugin.wasm" +activation = ["on-event:file-opened", "on-event:file-saved", "on-command:*"] + +[capabilities] +required = ["events", "project.read", "editor.read", "editor.write"] + +[[contributes.providers]] +kinds = ["code-actions"] +languages = ["*"] + +[[contributes.commands]] +id = "add" +title = "License Header: Add to Current File" +category = "License Header" + +[[contributes.commands]] +id = "scan" +title = "License Header: Find Files Without a Header" +category = "License Header" + +[[contributes.menus]] +menu = "tools" +command = "scan" + +[contributes.settings] +title = "License Header" +schema = "settings.schema.json" diff --git a/plugins/official/license-header/settings.schema.json b/plugins/official/license-header/settings.schema.json new file mode 100644 index 00000000..83600dfb --- /dev/null +++ b/plugins/official/license-header/settings.schema.json @@ -0,0 +1,21 @@ +{ + "properties": { + "owner": { + "type": "string", + "title": "Copyright holder", + "description": "Written after the year, e.g. \"ACME Inc.\"; empty for none.", + "default": "" + }, + "license": { + "type": "string", + "title": "License (SPDX identifier)", + "description": "e.g. Apache-2.0, MIT, GPL-3.0-or-later; empty for no SPDX line.", + "default": "Apache-2.0" + }, + "reportOnOpen": { + "type": "boolean", + "title": "Report files without a header when they open", + "default": true + } + } +} diff --git a/plugins/official/license-header/src/lib.rs b/plugins/official/license-header/src/lib.rs new file mode 100644 index 00000000..7fd5d789 --- /dev/null +++ b/plugins/official/license-header/src/lib.rs @@ -0,0 +1,395 @@ +//! License Header for OpenIDEA: a copyright and SPDX license header at the top +//! of source files, in the file's own comment syntax. +//! +//! - A file without one is reported (an info diagnostic on its first line) +//! when it opens, and again when it is saved, so adding the header clears it. +//! - The quick fix and *License Header: Add to Current File* insert it (after a +//! `#!` line or a Python encoding line, which must stay first). +//! - *Find Files Without a Header* scans the project in a background task and +//! reports every source file that needs one in the Problems view. + +use openidea_plugin::host; +use openidea_plugin::providers::{CodeAction, Document, Providers}; +use openidea_plugin::{ + Diagnostic, Error, Event, Invocation, NotificationLevel, Plugin, Position, Project, Range, Severity, TextEdit, + register_plugin, +}; + +/// Lines looked at for an existing header. +const HEADER_LINES: usize = 15; +/// Files a scan reads at most. +const MAX_SCAN: u32 = 5000; +/// Files larger than this are skipped by a scan. +const MAX_FILE: usize = 1 << 20; +const CODE: &str = "missing-license-header"; + +/// How a file writes a header: line comments, or one block comment. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Comment { + Line(&'static str), + Block(&'static str, &'static str), +} + +/// The comment syntax for `path`, `None` for files that don't get a header. +pub fn comment_for(path: &str) -> Option { + let name = path.rsplit(['/', '\\']).next().unwrap_or(path); + let lower = name.to_ascii_lowercase(); + if matches!(lower.as_str(), "dockerfile" | "makefile" | "justfile") { + return Some(Comment::Line("#")); + } + let ext = lower.rsplit_once('.').map(|(_, e)| e)?; + Some(match ext { + "rs" | "java" | "kt" | "kts" | "scala" | "groovy" | "gradle" | "go" | "js" | "jsx" | "mjs" | "cjs" | "ts" + | "tsx" | "mts" | "cts" | "c" | "h" | "cc" | "cpp" | "cxx" | "hpp" | "hh" | "m" | "mm" | "cs" | "swift" + | "dart" | "proto" | "sol" | "zig" | "v" => Comment::Line("//"), + "css" | "scss" | "less" => Comment::Block("/*", " */"), + "py" | "sh" | "bash" | "zsh" | "fish" | "rb" | "pl" | "r" | "ps1" | "yaml" | "yml" | "toml" | "cmake" + | "tf" | "nix" | "ex" | "exs" | "jl" => Comment::Line("#"), + "sql" | "lua" | "hs" | "elm" => Comment::Line("--"), + _ => return None, + }) +} + +/// Whether `text` already starts with a header (copyright or license notice). +pub fn has_header(text: &str) -> bool { + text.lines().take(HEADER_LINES).any(|l| { + let l = l.to_ascii_lowercase(); + l.contains("copyright") || l.contains("spdx-license-identifier") || l.contains("licensed under") + }) +} + +/// The header's lines, without comment markers. +pub fn header_lines(year: i64, owner: &str, license: &str) -> Vec { + let owner = owner.trim(); + let mut lines = + vec![if owner.is_empty() { format!("Copyright (c) {year}") } else { format!("Copyright (c) {year} {owner}") }]; + if !license.trim().is_empty() { + lines.push(format!("SPDX-License-Identifier: {}", license.trim())); + } + lines +} + +/// The header as `comment` writes it, with a blank line after it. +pub fn render(comment: Comment, lines: &[String]) -> String { + let mut out = String::new(); + match comment { + Comment::Line(prefix) => { + for l in lines { + out.push_str(&format!("{prefix} {l}\n")); + } + } + Comment::Block(open, close) => { + out.push_str(open); + out.push('\n'); + for l in lines { + out.push_str(&format!(" * {l}\n")); + } + out.push_str(close); + out.push('\n'); + } + } + out.push('\n'); + out +} + +/// The line the header goes on: after a `#!` line and a Python encoding line. +pub fn insert_line(text: &str) -> u32 { + let mut line = 0; + let mut lines = text.lines(); + if lines.next().is_some_and(|l| l.starts_with("#!")) { + line = 1; + if lines.next().is_some_and(is_encoding_line) { + line = 2; + } + } else if text.lines().next().is_some_and(is_encoding_line) { + line = 1; + } + line +} + +fn is_encoding_line(l: &str) -> bool { + l.starts_with('#') && (l.contains("coding:") || l.contains("coding=")) +} + +/// The edit that adds the header to `path`'s `text`, `None` when it has one or takes none. +pub fn header_edit(path: &str, text: &str, year: i64, owner: &str, license: &str) -> Option { + let comment = comment_for(path)?; + if has_header(text) { + return None; + } + let at = Position::new(insert_line(text), 0); + let mut insert = render(comment, &header_lines(year, owner, license)); + // After a first line without a newline (a lone shebang). + if at.line > 0 && text.lines().count() == at.line as usize && !text.ends_with('\n') { + insert.insert(0, '\n'); + } + Some(TextEdit { range: Range::new(at, at), text: insert }) +} + +fn missing(text: &str) -> Diagnostic { + let line = insert_line(text); + let len = text.lines().nth(line as usize).map_or(0, |l| l.encode_utf16().count() as u32); + Diagnostic { + range: Range::new(Position::new(line, 0), Position::new(line, len)), + severity: Severity::Info, + message: "No license header".into(), + code: Some(CODE.into()), + } +} + +/// Reports `path` when it takes a header and has none, clears it otherwise. +pub fn report(path: &str, text: &str) -> Result { + let lacking = comment_for(path).is_some() && !has_header(text); + host::publish_diagnostics(path, &if lacking { vec![missing(text)] } else { Vec::new() })?; + Ok(lacking) +} + +/// The current year (WASI wall clock), from days since the epoch. +fn this_year() -> i64 { + let secs = + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0); + year_of_day(secs.div_euclid(86_400)) +} + +/// The proleptic Gregorian year of `day` days since 1970-01-01. +pub fn year_of_day(day: i64) -> i64 { + let z = day + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + yoe + era * 400 + i64::from(month <= 2) +} + +fn settings() -> (String, String) { + ( + host::setting_string("owner").unwrap_or_default(), + host::setting_string("license").unwrap_or_else(|| "Apache-2.0".into()), + ) +} + +fn project_of(path: &str) -> Option { + host::projects() + .ok()? + .into_iter() + .filter(|p| p.root().is_ok_and(|r| path.starts_with(&r))) + .max_by_key(|p| p.root().map(|r| r.len()).unwrap_or(0)) +} + +#[derive(Default)] +pub struct LicenseHeader; + +impl LicenseHeader { + fn add_to_editor(&self, ctx: &Invocation) -> Result, Error> { + let editor = ctx.editor().ok_or_else(|| Error::Invalid("focus an editor first".into()))?; + let (path, doc) = (editor.path(), editor.document()?); + if comment_for(&path).is_none() { + return Err(Error::Invalid("this kind of file takes no license header".into())); + } + let (owner, license) = settings(); + let Some(edit) = header_edit(&path, &doc.text, this_year(), &owner, &license) else { + return Ok(Some("The file already has a license header.".into())); + }; + editor.apply_edits(doc.version, &[edit])?; + Ok(None) + } + + /// Reports every source file of the project without a header; returns (checked, lacking). + fn scan(&self, project: &Project) -> Result<(u32, u32), Error> { + let files: Vec = project + .find_files("**/*", MAX_SCAN * 4)? + .into_iter() + .filter(|f| comment_for(f).is_some()) + .take(MAX_SCAN as usize) + .collect(); + let total = files.len() as u32; + let task = host::begin_task("License Header: checking files", true); + let (mut checked, mut lacking) = (0, 0); + for (i, path) in files.iter().enumerate() { + if task.is_cancelled() { + break; + } + if i % 20 == 0 { + let name = path.rsplit('/').next().unwrap_or(path); + task.report(i as u32, Some(total), Some(name)); + } + let Ok(text) = project.read_file(path) else { continue }; + if text.len() > MAX_FILE { + continue; + } + checked += 1; + if report(path, &text)? { + lacking += 1; + } + } + Ok((checked, lacking)) + } +} + +impl Plugin for LicenseHeader { + fn run_command(&mut self, id: &str, ctx: &Invocation, _arg: Option<&str>) -> Result, Error> { + match id { + "add" => self.add_to_editor(ctx), + "scan" => { + let project = ctx.project().ok_or_else(|| Error::Invalid("open a project first".into()))?; + let (checked, lacking) = self.scan(&project)?; + let body = match lacking { + 0 => format!("All {checked} source files have one."), + 1 => format!("1 of {checked} source files has none; see the Problems view."), + n => format!("{n} of {checked} source files have none; see the Problems view."), + }; + host::notify(NotificationLevel::Info, "License headers", &body); + Ok(None) + } + _ => Err(Error::NotFound(format!("command {id}"))), + } + } + + fn handle_events(&mut self, events: &[Event], _ctx: &Invocation) { + for e in events { + let (path, opened) = match e { + Event::FileOpened(p) => (p, true), + Event::FileSaved(p) => (p, false), + _ => continue, + }; + if comment_for(path).is_none() || (opened && !host::setting_bool("reportOnOpen").unwrap_or(true)) { + continue; + } + let Some(project) = project_of(path) else { continue }; + if let Ok(text) = project.read_file(path) { + let _ = report(path, &text); + } + } + } +} + +impl Providers for LicenseHeader { + fn code_actions(&mut self, doc: &Document, _selection: Range) -> Vec { + let (owner, license) = settings(); + let Some(edit) = header_edit(&doc.path, &doc.text, this_year(), &owner, &license) else { return Vec::new() }; + vec![CodeAction { + title: "Add license header".into(), + kind: Some("quickfix".into()), + preferred: true, + edits: vec![(doc.path.clone(), vec![edit])], + }] + } +} + +register_plugin!(LicenseHeader, providers); + +#[cfg(test)] +mod tests { + use super::*; + use openidea_plugin::mock::MockHost; + + fn doc(path: &str, text: &str) -> Document { + Document { path: path.into(), language: String::new(), version: 1, text: text.into() } + } + + #[test] + fn writes_the_header_in_each_files_comment_syntax() { + let lines = header_lines(2026, "ACME Inc.", "MIT"); + assert_eq!( + render(comment_for("a/b.rs").unwrap(), &lines), + "// Copyright (c) 2026 ACME Inc.\n// SPDX-License-Identifier: MIT\n\n" + ); + assert_eq!(render(comment_for("x.py").unwrap(), &lines[..1]), "# Copyright (c) 2026 ACME Inc.\n\n"); + assert_eq!( + render(comment_for("s.css").unwrap(), &lines), + "/*\n * Copyright (c) 2026 ACME Inc.\n * SPDX-License-Identifier: MIT\n */\n\n" + ); + assert_eq!(comment_for("q.SQL"), Some(Comment::Line("--"))); + assert_eq!(comment_for("Dockerfile"), Some(Comment::Line("#"))); + assert_eq!(comment_for("README.md"), None); + assert_eq!(comment_for("noext"), None); + assert_eq!(header_lines(2026, " ", ""), ["Copyright (c) 2026"]); + } + + #[test] + fn keeps_shebang_and_encoding_lines_first() { + assert_eq!(insert_line("fn main() {}\n"), 0); + assert_eq!(insert_line("#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nprint()\n"), 2); + assert_eq!(insert_line("#!/bin/sh\necho\n"), 1); + assert_eq!(insert_line("# coding=latin-1\nx = 1\n"), 1); + let e = header_edit("run.sh", "#!/bin/sh", 2026, "", "").unwrap(); + assert_eq!((e.range.start, e.text.as_str()), (Position::new(1, 0), "\n# Copyright (c) 2026\n\n")); + } + + #[test] + fn an_existing_header_is_left_alone() { + assert!(has_header("// SPDX-License-Identifier: Apache-2.0\nfn x() {}")); + assert!(has_header("/*\n * Licensed under the MIT license\n */")); + assert!(has_header(&format!("{}// Copyright 2020\n", "\n".repeat(10)))); + assert!(!has_header(&format!("{}// Copyright 2020\n", "\n".repeat(20))), "only the top of the file counts"); + assert!(header_edit("a.rs", "// Copyright (c) 2020 X\n", 2026, "", "").is_none()); + } + + #[test] + fn years() { + assert_eq!(year_of_day(0), 1970); + assert_eq!(year_of_day(19_722), 2023); // 2023-12-31 + assert_eq!(year_of_day(19_723), 2024); // 2024-01-01 + assert_eq!(year_of_day(20_759), 2026); + } + + #[test] + fn reports_on_open_and_save_and_fixes() { + let host = MockHost::install().with_capabilities(&["events", "project.read", "editor.read", "editor.write"]); + host.add_file("src/a.rs", "fn a() {}\n"); + host.add_file("src/b.rs", "// Copyright (c) 2020 X\nfn b() {}\n"); + let mut p = LicenseHeader; + p.handle_events( + &[Event::FileOpened("/project/src/a.rs".into()), Event::FileOpened("/project/src/b.rs".into())], + &host.invocation(), + ); + let d = host.diagnostics(); + assert_eq!(d["/project/src/a.rs"][0].code.as_deref(), Some(CODE)); + assert!(d.get("/project/src/b.rs").is_none_or(Vec::is_empty)); + + // Off when opening, still on saving. + host.set_setting("reportOnOpen", "false"); + host.add_file("src/c.rs", "fn c() {}\n"); + p.handle_events(&[Event::FileOpened("/project/src/c.rs".into())], &host.invocation()); + assert!(host.diagnostics().get("/project/src/c.rs").is_none_or(Vec::is_empty)); + p.handle_events(&[Event::FileSaved("/project/src/c.rs".into())], &host.invocation()); + assert_eq!(host.diagnostics()["/project/src/c.rs"].len(), 1); + + host.set_setting("owner", "\"ACME\""); + let actions = p.code_actions(&doc("/project/src/a.rs", "fn a() {}\n"), Range::default()); + assert_eq!(actions[0].title, "Add license header"); + let (path, edits) = &actions[0].edits[0]; + assert_eq!(path, "/project/src/a.rs"); + assert!( + edits[0].text.starts_with(&format!( + "// Copyright (c) {} ACME\n// SPDX-License-Identifier: Apache-2.0\n", + this_year() + )) + ); + assert!(p.code_actions(&doc("/project/README.md", "x"), Range::default()).is_empty()); + + // The command edits the focused editor once. + host.open_editor("/project/src/a.rs", "rust", "fn a() {}\n", &[(0, 0, 0, 0)]); + assert_eq!(p.run_command("add", &host.invocation(), None).unwrap(), None); + assert!(has_header(&host.editor_text())); + assert!(p.run_command("add", &host.invocation(), None).unwrap().unwrap().contains("already")); + } + + #[test] + fn scans_the_project_in_a_task() { + let host = MockHost::install().with_capabilities(&["events", "project.read"]); + host.add_file("src/a.rs", "fn a() {}\n"); + host.add_file("src/b.py", "# Copyright 2024 X\n"); + host.add_file("notes.md", "no header needed\n"); + let mut p = LicenseHeader; + p.run_command("scan", &host.invocation(), None).unwrap(); + let d = host.diagnostics(); + assert_eq!(d["/project/src/a.rs"].len(), 1); + assert!(d.get("/project/src/b.py").is_none_or(Vec::is_empty)); + assert!(!d.contains_key("/project/notes.md")); + assert_eq!(host.tasks().len(), 1); + assert!(host.notifications()[0].body.contains("1 of 2"), "{:?}", host.notifications()); + } +} diff --git a/plugins/official/material-icons/generate.py b/plugins/official/material-icons/generate.py new file mode 100644 index 00000000..d1f024ed --- /dev/null +++ b/plugins/official/material-icons/generate.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +"""Generates icons/*.svg and icons/theme.json of the Material Icons plugin. + +Flat, original icons on the Material colour palette: language files are +coloured badges with a short label, well-known files get glyphs, folders are +tinted by role. Edit the tables below and run `python3 generate.py`, then +`openidea-plugin check .`. Not part of the package (plugin.toml does not +reference it), so it is not installed. +""" + +import json +import pathlib + +HERE = pathlib.Path(__file__).resolve().parent +OUT = HERE / "icons" +FONT = "system-ui, -apple-system, Segoe UI, Roboto, sans-serif" + + +def svg(body: str) -> str: + return f'{body}\n' + + +def badge(color: str, label: str, fg: str = "#fff") -> str: + size = {1: 9.5, 2: 7.4, 3: 5.6}[len(label)] + y = 8 + size * 0.36 + label = label.replace("&", "&").replace("<", "<").replace(">", ">") + return svg( + f'' + f'{label}' + ) + + +def doc(color: str, inner: str = "") -> str: + return svg( + f'' + f'{inner}' + ) + + +def folder(color: str, open_: bool = False) -> str: + if open_: + return svg( + f'' + f'' + ) + return svg( + f'' + ) + + +def stroke(d: str, color: str = "#fff", width: float = 1.4) -> str: + return ( + f'' + ) + + +def gear(color: str) -> str: + teeth = "".join( + f'' + for a in range(0, 360, 45) + ) + return svg(f'{teeth}') + + +def atom(color: str) -> str: + rings = "".join( + f'' for a in (0, 60, 120) + ) + return svg(f'{rings}') + + +def package(color: str) -> str: + return svg( + f'' + '' + '' + ) + + +GLYPHS = { + "file": doc("#90a4ae"), + "text": doc("#90a4ae", stroke("M5 7.5h6M5 10h6M5 12.5h4", width=1.1)), + "markdown": svg( + '' + + stroke("M3 10.5v-5l2 2.5 2-2.5v5", width=1.3) + + stroke("M11 5.5v5M9.2 8.8l1.8 1.8 1.8-1.8", width=1.3) + ), + "image": svg( + '' + '' + '' + ), + "archive": svg( + '' + '' + '' + ), + "lock": svg( + '' + + stroke("M5.5 7V5a2.5 2.5 0 0 1 5 0v2", "#90a4ae", 1.8) + + '' + ), + "git": svg( + '' + + stroke("M6.3 5v6M6.3 6.4c0 1.8 3.7.4 3.7 2.1", width=1.1) + + '' + ), + "settings": gear("#78909c"), + "env": gear("#fbc02d"), + "readme": svg( + '' + '' + ), + "license": svg( + '' + + stroke("M3.6 4.6h6.4M3.6 6.8h4", "#fff", 1.1) + + '' + ), + "shell": svg( + '' + + stroke("M4 5.5l2.5 2.5L4 10.5", width=1.5) + + stroke("M8 10.8h4", width=1.5) + ), + "database": svg( + '' + '' + + stroke("M2.5 7.5c0 1.1 2.5 2 5.5 2s5.5-.9 5.5-2", "#ffe082", 0.9) + ), + "html": svg('' + stroke("M6 5L3.5 8 6 11M10 5l2.5 3L10 11")), + "xml": svg('' + stroke("M5.5 5L3 8l2.5 3M10.5 5L13 8l-2.5 3M9 4.5l-2 7", width=1.2)), + "json": badge("#fbc02d", "{}", "#5d4037"), + "react": atom("#00bcd4"), + "react-ts": atom("#0288d1"), + "docker": svg( + '' + '' + '' + '' + '' + ), + "npm": package("#cb3837"), + "cargo": package("#ff7043"), + "gomod": package("#00acc1"), + "pnpm": package("#f9ad00"), + "test": svg( + '' + stroke("M4.2 8.2l2.4 2.4 5.2-5.2", width=1.7) + ), + "vite": badge("#9575cd", "V"), + "tsconfig": badge("#0288d1", "TS", "#bbdefb"), + "makefile": badge("#ef5350", "M"), + "editorconfig": gear("#90a4ae"), + "font": badge("#ef5350", "Aa"), + "pdf": badge("#e53935", "PDF"), + "svg": badge("#ffb300", "SVG", "#4e342e"), + "audio": svg(''), + "video": svg(''), +} + +# extension → (icon id, colour, label[, label colour]) +LANGUAGES = { + "rust": ("#ff7043", "RS", ["rs"]), + "typescript": ("#0288d1", "TS", ["ts", "mts", "cts"]), + "typescript-def": ("#0277bd", "D", ["d.ts", "d.mts", "d.cts"]), + "javascript": ("#fbc02d", "JS", ["js", "mjs", "cjs"], "#3e2723"), + "python": ("#3572a5", "PY", ["py", "pyi", "pyw"], "#ffd54f"), + "go": ("#00acc1", "GO", ["go"]), + "java": ("#e53935", "J", ["java"]), + "class": ("#8d6e63", "CL", ["class", "jar"]), + "kotlin": ("#7e57c2", "KT", ["kt", "kts"]), + "groovy": ("#4db6ac", "GR", ["groovy", "gradle"]), + "scala": ("#d32f2f", "SC", ["scala", "sc", "sbt"]), + "c": ("#5c6bc0", "C", ["c"]), + "cpp": ("#1e88e5", "C++", ["cpp", "cc", "cxx", "c++"]), + "header": ("#9575cd", "H", ["h", "hpp", "hh", "hxx", "inl"]), + "csharp": ("#388e3c", "C#", ["cs", "csx"]), + "fsharp": ("#378bba", "F#", ["fs", "fsi", "fsx"]), + "swift": ("#ff5722", "SW", ["swift"]), + "objc": ("#607d8b", "OC", ["m", "mm"]), + "ruby": ("#c62828", "RB", ["rb", "erb", "rake", "gemspec"]), + "php": ("#7986cb", "PHP", ["php"]), + "perl": ("#5c6bc0", "PL", ["pl", "pm"]), + "lua": ("#3949ab", "LUA", ["lua"]), + "r": ("#1976d2", "R", ["r", "rmd"]), + "julia": ("#9558b2", "JL", ["jl"]), + "dart": ("#40c4ff", "D", ["dart"], "#01579b"), + "elixir": ("#7e57c2", "EX", ["ex", "exs", "heex"]), + "erlang": ("#c2185b", "ER", ["erl", "hrl"]), + "haskell": ("#7e57c2", "HS", ["hs", "lhs"]), + "ocaml": ("#ef6c00", "ML", ["ml", "mli"]), + "clojure": ("#64dd17", "CLJ", ["clj", "cljs", "cljc", "edn"], "#1b5e20"), + "zig": ("#f9a825", "Z", ["zig", "zon"], "#3e2723"), + "nim": ("#ffc107", "NIM", ["nim"], "#3e2723"), + "solidity": ("#546e7a", "SOL", ["sol"]), + "vue": ("#41b883", "V", ["vue"]), + "svelte": ("#ff3e00", "S", ["svelte"]), + "astro": ("#ff5d01", "A", ["astro"]), + "css": ("#42a5f5", "#", ["css"]), + "sass": ("#ec407a", "#", ["scss", "sass"]), + "less": ("#1565c0", "LS", ["less"]), + "yaml": ("#e53935", "YML", ["yaml", "yml"]), + "toml": ("#8d6e63", "TML", ["toml"]), + "ini": ("#78909c", "INI", ["ini", "cfg", "conf", "properties"]), + "csv": ("#43a047", "CSV", ["csv", "tsv"]), + "graphql": ("#e535ab", "GQ", ["graphql", "gql"]), + "proto": ("#26a69a", "PB", ["proto"]), + "wasm": ("#654ff0", "WA", ["wasm", "wat"]), + "nix": ("#5277c3", "NIX", ["nix"]), + "terraform": ("#7b42bc", "TF", ["tf", "tfvars", "hcl"]), + "powershell": ("#0277bd", "PS", ["ps1", "psm1", "psd1"]), + "batch": ("#546e7a", "BAT", ["bat", "cmd"]), + "tex": ("#008080", "TEX", ["tex", "sty", "bib"]), + "vim": ("#43a047", "VI", ["vim"]), + "diff": ("#66bb6a", "+-", ["diff", "patch"]), + "log": ("#78909c", "LOG", ["log"]), + "notebook": ("#f57c00", "NB", ["ipynb"]), + "http": ("#3f51b5", "API", ["http", "rest"]), +} + +GLYPH_EXTENSIONS = { + "text": ["txt", "text"], + "markdown": ["md", "markdown", "mdx"], + "image": ["png", "jpg", "jpeg", "gif", "webp", "bmp", "ico", "avif", "tif", "tiff", "icns"], + "svg": ["svg"], + "pdf": ["pdf"], + "archive": ["zip", "tar", "gz", "tgz", "bz2", "xz", "7z", "rar", "zst"], + "lock": ["lock"], + "shell": ["sh", "bash", "zsh", "fish"], + "database": ["sql", "sqlite", "db", "prisma"], + "html": ["html", "htm", "xhtml"], + "xml": ["xml", "xsd", "xsl", "plist", "iml"], + "json": ["json", "jsonc", "json5"], + "react": ["jsx"], + "react-ts": ["tsx"], + "test": [f"{kind}.{ext}" for kind in ("test", "spec") for ext in ("ts", "tsx", "js", "jsx", "mjs", "mts")] + + ["test.rs", "test.py"], + "font": ["ttf", "otf", "woff", "woff2"], + "audio": ["mp3", "wav", "ogg", "flac", "m4a"], + "video": ["mp4", "mov", "webm", "mkv", "avi"], + "env": ["env"], +} + +FILE_NAMES = { + "readme": ["readme", "readme.md", "readme.txt", "readme.rst"], + "license": ["license", "licence", "license.md", "licence.md", "license.txt", "copying", "notice"], + "git": [".gitignore", ".gitattributes", ".gitmodules", ".gitkeep", ".mailmap"], + "docker": ["dockerfile", "containerfile", ".dockerignore", "docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml"], + "npm": ["package.json", ".npmrc", ".npmignore"], + "cargo": ["cargo.toml", "rust-toolchain", "rust-toolchain.toml"], + "gomod": ["go.mod", "go.sum", "go.work"], + "pnpm": ["pnpm-workspace.yaml"], + "lock": ["cargo.lock", "package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "poetry.lock", "uv.lock", "gemfile.lock", "composer.lock"], + "env": [".env", ".env.local", ".env.development", ".env.production", ".env.example"], + "tsconfig": ["tsconfig.json", "jsconfig.json", "tsconfig.base.json"], + "vite": ["vite.config.ts", "vite.config.js", "vite.config.mts", "vitest.config.ts", "vitest.config.mts"], + "makefile": ["makefile", "gnumakefile", "justfile", "cmakelists.txt"], + "editorconfig": [".editorconfig", ".prettierrc", ".prettierignore", ".oxlintrc.json", ".eslintrc", ".eslintrc.json", "mise.toml"], + "settings": [".clippy.toml", "clippy.toml", "rustfmt.toml", ".rustfmt.toml", "deny.toml"], +} + +# folder name → (icon id, colour) +FOLDERS = { + "folder-src": ("#4caf50", ["src", "source", "sources", "lib", "libs", "pkg", "internal", "crates", "packages"]), + "folder-test": ("#8bc34a", ["test", "tests", "__tests__", "spec", "specs", "e2e", "fixtures", "testdata"]), + "folder-docs": ("#42a5f5", ["doc", "docs", "documentation", "wiki"]), + "folder-dist": ("#e57373", ["dist", "build", "out", "target", "bin", "obj", "release", "coverage"]), + "folder-deps": ("#9ccc65", ["node_modules", "vendor", ".venv", "venv", "third_party", "deps"]), + "folder-git": ("#ff7043", [".git", ".github", ".gitlab", ".husky"]), + "folder-config": ("#78909c", ["config", "configs", ".config", ".vscode", ".idea", ".cargo", "settings", "etc"]), + "folder-assets": ("#26a69a", ["assets", "static", "public", "images", "img", "icons", "fonts", "media", "resources", "res"]), + "folder-scripts": ("#ffb74d", ["scripts", "script", "tools", "tasks", "ci"]), + "folder-components": ("#ffca28", ["components", "ui", "widgets", "views", "pages", "features"]), + "folder-styles": ("#ec407a", ["styles", "css", "scss", "theme", "themes"]), + "folder-plugins": ("#ab47bc", ["plugins", "extensions", "addons", "sdk"]), + "folder-i18n": ("#5c6bc0", ["i18n", "locales", "locale", "lang", "translations"]), + "folder-api": ("#26c6da", ["api", "server", "routes", "handlers", "rpc"]), + "folder-db": ("#ffa726", ["db", "database", "migrations", "sql", "schema"]), +} + + +def main() -> None: + OUT.mkdir(exist_ok=True) + for old in OUT.glob("*.svg"): + old.unlink() + icons: dict[str, str] = {} + + def add(name: str, content: str) -> None: + assert name not in icons, f"duplicate icon {name}" + icons[name] = content + (OUT / f"{name}.svg").write_text(content) + + for name, content in GLYPHS.items(): + add(name, content) + add("folder", folder("#90a4ae")) + add("folder-open", folder("#90a4ae", open_=True)) + + extensions: dict[str, str] = {} + + def map_ext(ext: str, icon: str) -> None: + assert ext not in extensions, f"extension {ext} mapped twice" + extensions[ext] = icon + + for name, (color, label, exts, *fg) in LANGUAGES.items(): + add(name, badge(color, label, *fg)) + for ext in exts: + map_ext(ext, name) + for icon, exts in GLYPH_EXTENSIONS.items(): + for ext in exts: + map_ext(ext, icon) + + file_names = {n: icon for icon, names in FILE_NAMES.items() for n in names} + folder_names: dict[str, str] = {} + for icon, (color, names) in FOLDERS.items(): + add(icon, folder(color)) + for n in names: + assert n not in folder_names, f"folder {n} mapped twice" + folder_names[n] = icon + + for mapping in (extensions, file_names, folder_names): + for key, icon in mapping.items(): + assert icon in icons, f"{key} → unknown icon {icon}" + + theme = { + "iconDefinitions": {name: f"icons/{name}.svg" for name in sorted(icons)}, + "file": "file", + "folder": "folder", + "folderExpanded": "folder-open", + "fileExtensions": dict(sorted(extensions.items())), + "fileNames": dict(sorted(file_names.items())), + "folderNames": dict(sorted(folder_names.items())), + } + (OUT / "theme.json").write_text(json.dumps(theme, indent=2) + "\n") + print(f"{len(icons)} icons, {len(extensions)} extensions, {len(file_names)} file names, {len(folder_names)} folders") + + +if __name__ == "__main__": + main() diff --git a/plugins/official/material-icons/icons/archive.svg b/plugins/official/material-icons/icons/archive.svg new file mode 100644 index 00000000..871bd064 --- /dev/null +++ b/plugins/official/material-icons/icons/archive.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/astro.svg b/plugins/official/material-icons/icons/astro.svg new file mode 100644 index 00000000..7bdb6e1e --- /dev/null +++ b/plugins/official/material-icons/icons/astro.svg @@ -0,0 +1 @@ +A diff --git a/plugins/official/material-icons/icons/audio.svg b/plugins/official/material-icons/icons/audio.svg new file mode 100644 index 00000000..515294d8 --- /dev/null +++ b/plugins/official/material-icons/icons/audio.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/batch.svg b/plugins/official/material-icons/icons/batch.svg new file mode 100644 index 00000000..6d1779b5 --- /dev/null +++ b/plugins/official/material-icons/icons/batch.svg @@ -0,0 +1 @@ +BAT diff --git a/plugins/official/material-icons/icons/c.svg b/plugins/official/material-icons/icons/c.svg new file mode 100644 index 00000000..408c3ee9 --- /dev/null +++ b/plugins/official/material-icons/icons/c.svg @@ -0,0 +1 @@ +C diff --git a/plugins/official/material-icons/icons/cargo.svg b/plugins/official/material-icons/icons/cargo.svg new file mode 100644 index 00000000..47b71a70 --- /dev/null +++ b/plugins/official/material-icons/icons/cargo.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/class.svg b/plugins/official/material-icons/icons/class.svg new file mode 100644 index 00000000..f0ac74af --- /dev/null +++ b/plugins/official/material-icons/icons/class.svg @@ -0,0 +1 @@ +CL diff --git a/plugins/official/material-icons/icons/clojure.svg b/plugins/official/material-icons/icons/clojure.svg new file mode 100644 index 00000000..28c9b47e --- /dev/null +++ b/plugins/official/material-icons/icons/clojure.svg @@ -0,0 +1 @@ +CLJ diff --git a/plugins/official/material-icons/icons/cpp.svg b/plugins/official/material-icons/icons/cpp.svg new file mode 100644 index 00000000..1a7fd743 --- /dev/null +++ b/plugins/official/material-icons/icons/cpp.svg @@ -0,0 +1 @@ +C++ diff --git a/plugins/official/material-icons/icons/csharp.svg b/plugins/official/material-icons/icons/csharp.svg new file mode 100644 index 00000000..0559e508 --- /dev/null +++ b/plugins/official/material-icons/icons/csharp.svg @@ -0,0 +1 @@ +C# diff --git a/plugins/official/material-icons/icons/css.svg b/plugins/official/material-icons/icons/css.svg new file mode 100644 index 00000000..deb851ee --- /dev/null +++ b/plugins/official/material-icons/icons/css.svg @@ -0,0 +1 @@ +# diff --git a/plugins/official/material-icons/icons/csv.svg b/plugins/official/material-icons/icons/csv.svg new file mode 100644 index 00000000..be856f62 --- /dev/null +++ b/plugins/official/material-icons/icons/csv.svg @@ -0,0 +1 @@ +CSV diff --git a/plugins/official/material-icons/icons/dart.svg b/plugins/official/material-icons/icons/dart.svg new file mode 100644 index 00000000..e6b1b6d1 --- /dev/null +++ b/plugins/official/material-icons/icons/dart.svg @@ -0,0 +1 @@ +D diff --git a/plugins/official/material-icons/icons/database.svg b/plugins/official/material-icons/icons/database.svg new file mode 100644 index 00000000..6b2e64bd --- /dev/null +++ b/plugins/official/material-icons/icons/database.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/diff.svg b/plugins/official/material-icons/icons/diff.svg new file mode 100644 index 00000000..387aeaa6 --- /dev/null +++ b/plugins/official/material-icons/icons/diff.svg @@ -0,0 +1 @@ ++- diff --git a/plugins/official/material-icons/icons/docker.svg b/plugins/official/material-icons/icons/docker.svg new file mode 100644 index 00000000..a5d9eeb4 --- /dev/null +++ b/plugins/official/material-icons/icons/docker.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/editorconfig.svg b/plugins/official/material-icons/icons/editorconfig.svg new file mode 100644 index 00000000..ddbdbeba --- /dev/null +++ b/plugins/official/material-icons/icons/editorconfig.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/elixir.svg b/plugins/official/material-icons/icons/elixir.svg new file mode 100644 index 00000000..3e13bbf9 --- /dev/null +++ b/plugins/official/material-icons/icons/elixir.svg @@ -0,0 +1 @@ +EX diff --git a/plugins/official/material-icons/icons/env.svg b/plugins/official/material-icons/icons/env.svg new file mode 100644 index 00000000..cde14e40 --- /dev/null +++ b/plugins/official/material-icons/icons/env.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/erlang.svg b/plugins/official/material-icons/icons/erlang.svg new file mode 100644 index 00000000..50e2c0a0 --- /dev/null +++ b/plugins/official/material-icons/icons/erlang.svg @@ -0,0 +1 @@ +ER diff --git a/plugins/official/material-icons/icons/file.svg b/plugins/official/material-icons/icons/file.svg new file mode 100644 index 00000000..7a89750a --- /dev/null +++ b/plugins/official/material-icons/icons/file.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-api.svg b/plugins/official/material-icons/icons/folder-api.svg new file mode 100644 index 00000000..c24ee893 --- /dev/null +++ b/plugins/official/material-icons/icons/folder-api.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-assets.svg b/plugins/official/material-icons/icons/folder-assets.svg new file mode 100644 index 00000000..6230bf1f --- /dev/null +++ b/plugins/official/material-icons/icons/folder-assets.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-components.svg b/plugins/official/material-icons/icons/folder-components.svg new file mode 100644 index 00000000..9b63a7f4 --- /dev/null +++ b/plugins/official/material-icons/icons/folder-components.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-config.svg b/plugins/official/material-icons/icons/folder-config.svg new file mode 100644 index 00000000..41d451d9 --- /dev/null +++ b/plugins/official/material-icons/icons/folder-config.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-db.svg b/plugins/official/material-icons/icons/folder-db.svg new file mode 100644 index 00000000..ccaab633 --- /dev/null +++ b/plugins/official/material-icons/icons/folder-db.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-deps.svg b/plugins/official/material-icons/icons/folder-deps.svg new file mode 100644 index 00000000..0ec80997 --- /dev/null +++ b/plugins/official/material-icons/icons/folder-deps.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-dist.svg b/plugins/official/material-icons/icons/folder-dist.svg new file mode 100644 index 00000000..69f3fb5b --- /dev/null +++ b/plugins/official/material-icons/icons/folder-dist.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-docs.svg b/plugins/official/material-icons/icons/folder-docs.svg new file mode 100644 index 00000000..f3a28601 --- /dev/null +++ b/plugins/official/material-icons/icons/folder-docs.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-git.svg b/plugins/official/material-icons/icons/folder-git.svg new file mode 100644 index 00000000..ba7bd394 --- /dev/null +++ b/plugins/official/material-icons/icons/folder-git.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-i18n.svg b/plugins/official/material-icons/icons/folder-i18n.svg new file mode 100644 index 00000000..6118c98e --- /dev/null +++ b/plugins/official/material-icons/icons/folder-i18n.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-open.svg b/plugins/official/material-icons/icons/folder-open.svg new file mode 100644 index 00000000..0accab51 --- /dev/null +++ b/plugins/official/material-icons/icons/folder-open.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-plugins.svg b/plugins/official/material-icons/icons/folder-plugins.svg new file mode 100644 index 00000000..c75c82fd --- /dev/null +++ b/plugins/official/material-icons/icons/folder-plugins.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-scripts.svg b/plugins/official/material-icons/icons/folder-scripts.svg new file mode 100644 index 00000000..e8a7cc79 --- /dev/null +++ b/plugins/official/material-icons/icons/folder-scripts.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-src.svg b/plugins/official/material-icons/icons/folder-src.svg new file mode 100644 index 00000000..26336c36 --- /dev/null +++ b/plugins/official/material-icons/icons/folder-src.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-styles.svg b/plugins/official/material-icons/icons/folder-styles.svg new file mode 100644 index 00000000..4ac2a7ab --- /dev/null +++ b/plugins/official/material-icons/icons/folder-styles.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder-test.svg b/plugins/official/material-icons/icons/folder-test.svg new file mode 100644 index 00000000..29b2cbcf --- /dev/null +++ b/plugins/official/material-icons/icons/folder-test.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/folder.svg b/plugins/official/material-icons/icons/folder.svg new file mode 100644 index 00000000..4002def3 --- /dev/null +++ b/plugins/official/material-icons/icons/folder.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/font.svg b/plugins/official/material-icons/icons/font.svg new file mode 100644 index 00000000..d7e454a4 --- /dev/null +++ b/plugins/official/material-icons/icons/font.svg @@ -0,0 +1 @@ +Aa diff --git a/plugins/official/material-icons/icons/fsharp.svg b/plugins/official/material-icons/icons/fsharp.svg new file mode 100644 index 00000000..cbf21c7b --- /dev/null +++ b/plugins/official/material-icons/icons/fsharp.svg @@ -0,0 +1 @@ +F# diff --git a/plugins/official/material-icons/icons/git.svg b/plugins/official/material-icons/icons/git.svg new file mode 100644 index 00000000..02ff7956 --- /dev/null +++ b/plugins/official/material-icons/icons/git.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/go.svg b/plugins/official/material-icons/icons/go.svg new file mode 100644 index 00000000..4525fef3 --- /dev/null +++ b/plugins/official/material-icons/icons/go.svg @@ -0,0 +1 @@ +GO diff --git a/plugins/official/material-icons/icons/gomod.svg b/plugins/official/material-icons/icons/gomod.svg new file mode 100644 index 00000000..a0a8000c --- /dev/null +++ b/plugins/official/material-icons/icons/gomod.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/graphql.svg b/plugins/official/material-icons/icons/graphql.svg new file mode 100644 index 00000000..7126760d --- /dev/null +++ b/plugins/official/material-icons/icons/graphql.svg @@ -0,0 +1 @@ +GQ diff --git a/plugins/official/material-icons/icons/groovy.svg b/plugins/official/material-icons/icons/groovy.svg new file mode 100644 index 00000000..8967bb44 --- /dev/null +++ b/plugins/official/material-icons/icons/groovy.svg @@ -0,0 +1 @@ +GR diff --git a/plugins/official/material-icons/icons/haskell.svg b/plugins/official/material-icons/icons/haskell.svg new file mode 100644 index 00000000..f20b1be3 --- /dev/null +++ b/plugins/official/material-icons/icons/haskell.svg @@ -0,0 +1 @@ +HS diff --git a/plugins/official/material-icons/icons/header.svg b/plugins/official/material-icons/icons/header.svg new file mode 100644 index 00000000..cf7e9e78 --- /dev/null +++ b/plugins/official/material-icons/icons/header.svg @@ -0,0 +1 @@ +H diff --git a/plugins/official/material-icons/icons/html.svg b/plugins/official/material-icons/icons/html.svg new file mode 100644 index 00000000..40dec724 --- /dev/null +++ b/plugins/official/material-icons/icons/html.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/http.svg b/plugins/official/material-icons/icons/http.svg new file mode 100644 index 00000000..c4a7ed51 --- /dev/null +++ b/plugins/official/material-icons/icons/http.svg @@ -0,0 +1 @@ +API diff --git a/plugins/official/material-icons/icons/image.svg b/plugins/official/material-icons/icons/image.svg new file mode 100644 index 00000000..8f67a7ab --- /dev/null +++ b/plugins/official/material-icons/icons/image.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/ini.svg b/plugins/official/material-icons/icons/ini.svg new file mode 100644 index 00000000..a70903c4 --- /dev/null +++ b/plugins/official/material-icons/icons/ini.svg @@ -0,0 +1 @@ +INI diff --git a/plugins/official/material-icons/icons/java.svg b/plugins/official/material-icons/icons/java.svg new file mode 100644 index 00000000..6a72019b --- /dev/null +++ b/plugins/official/material-icons/icons/java.svg @@ -0,0 +1 @@ +J diff --git a/plugins/official/material-icons/icons/javascript.svg b/plugins/official/material-icons/icons/javascript.svg new file mode 100644 index 00000000..e43c32ab --- /dev/null +++ b/plugins/official/material-icons/icons/javascript.svg @@ -0,0 +1 @@ +JS diff --git a/plugins/official/material-icons/icons/json.svg b/plugins/official/material-icons/icons/json.svg new file mode 100644 index 00000000..841dce8a --- /dev/null +++ b/plugins/official/material-icons/icons/json.svg @@ -0,0 +1 @@ +{} diff --git a/plugins/official/material-icons/icons/julia.svg b/plugins/official/material-icons/icons/julia.svg new file mode 100644 index 00000000..4fb97b14 --- /dev/null +++ b/plugins/official/material-icons/icons/julia.svg @@ -0,0 +1 @@ +JL diff --git a/plugins/official/material-icons/icons/kotlin.svg b/plugins/official/material-icons/icons/kotlin.svg new file mode 100644 index 00000000..af61a955 --- /dev/null +++ b/plugins/official/material-icons/icons/kotlin.svg @@ -0,0 +1 @@ +KT diff --git a/plugins/official/material-icons/icons/less.svg b/plugins/official/material-icons/icons/less.svg new file mode 100644 index 00000000..a6534d17 --- /dev/null +++ b/plugins/official/material-icons/icons/less.svg @@ -0,0 +1 @@ +LS diff --git a/plugins/official/material-icons/icons/license.svg b/plugins/official/material-icons/icons/license.svg new file mode 100644 index 00000000..a58c14bb --- /dev/null +++ b/plugins/official/material-icons/icons/license.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/lock.svg b/plugins/official/material-icons/icons/lock.svg new file mode 100644 index 00000000..1ee46f47 --- /dev/null +++ b/plugins/official/material-icons/icons/lock.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/log.svg b/plugins/official/material-icons/icons/log.svg new file mode 100644 index 00000000..0a8efff5 --- /dev/null +++ b/plugins/official/material-icons/icons/log.svg @@ -0,0 +1 @@ +LOG diff --git a/plugins/official/material-icons/icons/lua.svg b/plugins/official/material-icons/icons/lua.svg new file mode 100644 index 00000000..018aa579 --- /dev/null +++ b/plugins/official/material-icons/icons/lua.svg @@ -0,0 +1 @@ +LUA diff --git a/plugins/official/material-icons/icons/makefile.svg b/plugins/official/material-icons/icons/makefile.svg new file mode 100644 index 00000000..7fe3ad1f --- /dev/null +++ b/plugins/official/material-icons/icons/makefile.svg @@ -0,0 +1 @@ +M diff --git a/plugins/official/material-icons/icons/markdown.svg b/plugins/official/material-icons/icons/markdown.svg new file mode 100644 index 00000000..78c8400e --- /dev/null +++ b/plugins/official/material-icons/icons/markdown.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/nim.svg b/plugins/official/material-icons/icons/nim.svg new file mode 100644 index 00000000..defeaf39 --- /dev/null +++ b/plugins/official/material-icons/icons/nim.svg @@ -0,0 +1 @@ +NIM diff --git a/plugins/official/material-icons/icons/nix.svg b/plugins/official/material-icons/icons/nix.svg new file mode 100644 index 00000000..dace2f37 --- /dev/null +++ b/plugins/official/material-icons/icons/nix.svg @@ -0,0 +1 @@ +NIX diff --git a/plugins/official/material-icons/icons/notebook.svg b/plugins/official/material-icons/icons/notebook.svg new file mode 100644 index 00000000..67b85bf8 --- /dev/null +++ b/plugins/official/material-icons/icons/notebook.svg @@ -0,0 +1 @@ +NB diff --git a/plugins/official/material-icons/icons/npm.svg b/plugins/official/material-icons/icons/npm.svg new file mode 100644 index 00000000..aec46265 --- /dev/null +++ b/plugins/official/material-icons/icons/npm.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/objc.svg b/plugins/official/material-icons/icons/objc.svg new file mode 100644 index 00000000..429ce16b --- /dev/null +++ b/plugins/official/material-icons/icons/objc.svg @@ -0,0 +1 @@ +OC diff --git a/plugins/official/material-icons/icons/ocaml.svg b/plugins/official/material-icons/icons/ocaml.svg new file mode 100644 index 00000000..4be3ebdb --- /dev/null +++ b/plugins/official/material-icons/icons/ocaml.svg @@ -0,0 +1 @@ +ML diff --git a/plugins/official/material-icons/icons/pdf.svg b/plugins/official/material-icons/icons/pdf.svg new file mode 100644 index 00000000..777d161a --- /dev/null +++ b/plugins/official/material-icons/icons/pdf.svg @@ -0,0 +1 @@ +PDF diff --git a/plugins/official/material-icons/icons/perl.svg b/plugins/official/material-icons/icons/perl.svg new file mode 100644 index 00000000..82516150 --- /dev/null +++ b/plugins/official/material-icons/icons/perl.svg @@ -0,0 +1 @@ +PL diff --git a/plugins/official/material-icons/icons/php.svg b/plugins/official/material-icons/icons/php.svg new file mode 100644 index 00000000..20d1ae8e --- /dev/null +++ b/plugins/official/material-icons/icons/php.svg @@ -0,0 +1 @@ +PHP diff --git a/plugins/official/material-icons/icons/pnpm.svg b/plugins/official/material-icons/icons/pnpm.svg new file mode 100644 index 00000000..e581f13c --- /dev/null +++ b/plugins/official/material-icons/icons/pnpm.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/powershell.svg b/plugins/official/material-icons/icons/powershell.svg new file mode 100644 index 00000000..35fe8ce0 --- /dev/null +++ b/plugins/official/material-icons/icons/powershell.svg @@ -0,0 +1 @@ +PS diff --git a/plugins/official/material-icons/icons/proto.svg b/plugins/official/material-icons/icons/proto.svg new file mode 100644 index 00000000..49b84d9e --- /dev/null +++ b/plugins/official/material-icons/icons/proto.svg @@ -0,0 +1 @@ +PB diff --git a/plugins/official/material-icons/icons/python.svg b/plugins/official/material-icons/icons/python.svg new file mode 100644 index 00000000..a22894cc --- /dev/null +++ b/plugins/official/material-icons/icons/python.svg @@ -0,0 +1 @@ +PY diff --git a/plugins/official/material-icons/icons/r.svg b/plugins/official/material-icons/icons/r.svg new file mode 100644 index 00000000..31612708 --- /dev/null +++ b/plugins/official/material-icons/icons/r.svg @@ -0,0 +1 @@ +R diff --git a/plugins/official/material-icons/icons/react-ts.svg b/plugins/official/material-icons/icons/react-ts.svg new file mode 100644 index 00000000..30c7b00e --- /dev/null +++ b/plugins/official/material-icons/icons/react-ts.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/react.svg b/plugins/official/material-icons/icons/react.svg new file mode 100644 index 00000000..3c8af66c --- /dev/null +++ b/plugins/official/material-icons/icons/react.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/readme.svg b/plugins/official/material-icons/icons/readme.svg new file mode 100644 index 00000000..39c5652c --- /dev/null +++ b/plugins/official/material-icons/icons/readme.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/ruby.svg b/plugins/official/material-icons/icons/ruby.svg new file mode 100644 index 00000000..ed8beec6 --- /dev/null +++ b/plugins/official/material-icons/icons/ruby.svg @@ -0,0 +1 @@ +RB diff --git a/plugins/official/material-icons/icons/rust.svg b/plugins/official/material-icons/icons/rust.svg new file mode 100644 index 00000000..3bd8a2bf --- /dev/null +++ b/plugins/official/material-icons/icons/rust.svg @@ -0,0 +1 @@ +RS diff --git a/plugins/official/material-icons/icons/sass.svg b/plugins/official/material-icons/icons/sass.svg new file mode 100644 index 00000000..13bd12f6 --- /dev/null +++ b/plugins/official/material-icons/icons/sass.svg @@ -0,0 +1 @@ +# diff --git a/plugins/official/material-icons/icons/scala.svg b/plugins/official/material-icons/icons/scala.svg new file mode 100644 index 00000000..34cc3238 --- /dev/null +++ b/plugins/official/material-icons/icons/scala.svg @@ -0,0 +1 @@ +SC diff --git a/plugins/official/material-icons/icons/settings.svg b/plugins/official/material-icons/icons/settings.svg new file mode 100644 index 00000000..85a771c2 --- /dev/null +++ b/plugins/official/material-icons/icons/settings.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/shell.svg b/plugins/official/material-icons/icons/shell.svg new file mode 100644 index 00000000..bf37b097 --- /dev/null +++ b/plugins/official/material-icons/icons/shell.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/solidity.svg b/plugins/official/material-icons/icons/solidity.svg new file mode 100644 index 00000000..d6d6508f --- /dev/null +++ b/plugins/official/material-icons/icons/solidity.svg @@ -0,0 +1 @@ +SOL diff --git a/plugins/official/material-icons/icons/svelte.svg b/plugins/official/material-icons/icons/svelte.svg new file mode 100644 index 00000000..152e614f --- /dev/null +++ b/plugins/official/material-icons/icons/svelte.svg @@ -0,0 +1 @@ +S diff --git a/plugins/official/material-icons/icons/svg.svg b/plugins/official/material-icons/icons/svg.svg new file mode 100644 index 00000000..1115a97f --- /dev/null +++ b/plugins/official/material-icons/icons/svg.svg @@ -0,0 +1 @@ +SVG diff --git a/plugins/official/material-icons/icons/swift.svg b/plugins/official/material-icons/icons/swift.svg new file mode 100644 index 00000000..1d6d4461 --- /dev/null +++ b/plugins/official/material-icons/icons/swift.svg @@ -0,0 +1 @@ +SW diff --git a/plugins/official/material-icons/icons/terraform.svg b/plugins/official/material-icons/icons/terraform.svg new file mode 100644 index 00000000..5ff38d03 --- /dev/null +++ b/plugins/official/material-icons/icons/terraform.svg @@ -0,0 +1 @@ +TF diff --git a/plugins/official/material-icons/icons/test.svg b/plugins/official/material-icons/icons/test.svg new file mode 100644 index 00000000..b4922455 --- /dev/null +++ b/plugins/official/material-icons/icons/test.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/tex.svg b/plugins/official/material-icons/icons/tex.svg new file mode 100644 index 00000000..8d647f82 --- /dev/null +++ b/plugins/official/material-icons/icons/tex.svg @@ -0,0 +1 @@ +TEX diff --git a/plugins/official/material-icons/icons/text.svg b/plugins/official/material-icons/icons/text.svg new file mode 100644 index 00000000..1ad8d7b1 --- /dev/null +++ b/plugins/official/material-icons/icons/text.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/theme.json b/plugins/official/material-icons/icons/theme.json new file mode 100644 index 00000000..919c17fe --- /dev/null +++ b/plugins/official/material-icons/icons/theme.json @@ -0,0 +1,471 @@ +{ + "iconDefinitions": { + "archive": "icons/archive.svg", + "astro": "icons/astro.svg", + "audio": "icons/audio.svg", + "batch": "icons/batch.svg", + "c": "icons/c.svg", + "cargo": "icons/cargo.svg", + "class": "icons/class.svg", + "clojure": "icons/clojure.svg", + "cpp": "icons/cpp.svg", + "csharp": "icons/csharp.svg", + "css": "icons/css.svg", + "csv": "icons/csv.svg", + "dart": "icons/dart.svg", + "database": "icons/database.svg", + "diff": "icons/diff.svg", + "docker": "icons/docker.svg", + "editorconfig": "icons/editorconfig.svg", + "elixir": "icons/elixir.svg", + "env": "icons/env.svg", + "erlang": "icons/erlang.svg", + "file": "icons/file.svg", + "folder": "icons/folder.svg", + "folder-api": "icons/folder-api.svg", + "folder-assets": "icons/folder-assets.svg", + "folder-components": "icons/folder-components.svg", + "folder-config": "icons/folder-config.svg", + "folder-db": "icons/folder-db.svg", + "folder-deps": "icons/folder-deps.svg", + "folder-dist": "icons/folder-dist.svg", + "folder-docs": "icons/folder-docs.svg", + "folder-git": "icons/folder-git.svg", + "folder-i18n": "icons/folder-i18n.svg", + "folder-open": "icons/folder-open.svg", + "folder-plugins": "icons/folder-plugins.svg", + "folder-scripts": "icons/folder-scripts.svg", + "folder-src": "icons/folder-src.svg", + "folder-styles": "icons/folder-styles.svg", + "folder-test": "icons/folder-test.svg", + "font": "icons/font.svg", + "fsharp": "icons/fsharp.svg", + "git": "icons/git.svg", + "go": "icons/go.svg", + "gomod": "icons/gomod.svg", + "graphql": "icons/graphql.svg", + "groovy": "icons/groovy.svg", + "haskell": "icons/haskell.svg", + "header": "icons/header.svg", + "html": "icons/html.svg", + "http": "icons/http.svg", + "image": "icons/image.svg", + "ini": "icons/ini.svg", + "java": "icons/java.svg", + "javascript": "icons/javascript.svg", + "json": "icons/json.svg", + "julia": "icons/julia.svg", + "kotlin": "icons/kotlin.svg", + "less": "icons/less.svg", + "license": "icons/license.svg", + "lock": "icons/lock.svg", + "log": "icons/log.svg", + "lua": "icons/lua.svg", + "makefile": "icons/makefile.svg", + "markdown": "icons/markdown.svg", + "nim": "icons/nim.svg", + "nix": "icons/nix.svg", + "notebook": "icons/notebook.svg", + "npm": "icons/npm.svg", + "objc": "icons/objc.svg", + "ocaml": "icons/ocaml.svg", + "pdf": "icons/pdf.svg", + "perl": "icons/perl.svg", + "php": "icons/php.svg", + "pnpm": "icons/pnpm.svg", + "powershell": "icons/powershell.svg", + "proto": "icons/proto.svg", + "python": "icons/python.svg", + "r": "icons/r.svg", + "react": "icons/react.svg", + "react-ts": "icons/react-ts.svg", + "readme": "icons/readme.svg", + "ruby": "icons/ruby.svg", + "rust": "icons/rust.svg", + "sass": "icons/sass.svg", + "scala": "icons/scala.svg", + "settings": "icons/settings.svg", + "shell": "icons/shell.svg", + "solidity": "icons/solidity.svg", + "svelte": "icons/svelte.svg", + "svg": "icons/svg.svg", + "swift": "icons/swift.svg", + "terraform": "icons/terraform.svg", + "test": "icons/test.svg", + "tex": "icons/tex.svg", + "text": "icons/text.svg", + "toml": "icons/toml.svg", + "tsconfig": "icons/tsconfig.svg", + "typescript": "icons/typescript.svg", + "typescript-def": "icons/typescript-def.svg", + "video": "icons/video.svg", + "vim": "icons/vim.svg", + "vite": "icons/vite.svg", + "vue": "icons/vue.svg", + "wasm": "icons/wasm.svg", + "xml": "icons/xml.svg", + "yaml": "icons/yaml.svg", + "zig": "icons/zig.svg" + }, + "file": "file", + "folder": "folder", + "folderExpanded": "folder-open", + "fileExtensions": { + "7z": "archive", + "astro": "astro", + "avi": "video", + "avif": "image", + "bash": "shell", + "bat": "batch", + "bib": "tex", + "bmp": "image", + "bz2": "archive", + "c": "c", + "c++": "cpp", + "cc": "cpp", + "cfg": "ini", + "cjs": "javascript", + "class": "class", + "clj": "clojure", + "cljc": "clojure", + "cljs": "clojure", + "cmd": "batch", + "conf": "ini", + "cpp": "cpp", + "cs": "csharp", + "css": "css", + "csv": "csv", + "csx": "csharp", + "cts": "typescript", + "cxx": "cpp", + "d.cts": "typescript-def", + "d.mts": "typescript-def", + "d.ts": "typescript-def", + "dart": "dart", + "db": "database", + "diff": "diff", + "edn": "clojure", + "env": "env", + "erb": "ruby", + "erl": "erlang", + "ex": "elixir", + "exs": "elixir", + "fish": "shell", + "flac": "audio", + "fs": "fsharp", + "fsi": "fsharp", + "fsx": "fsharp", + "gemspec": "ruby", + "gif": "image", + "go": "go", + "gql": "graphql", + "gradle": "groovy", + "graphql": "graphql", + "groovy": "groovy", + "gz": "archive", + "h": "header", + "hcl": "terraform", + "heex": "elixir", + "hh": "header", + "hpp": "header", + "hrl": "erlang", + "hs": "haskell", + "htm": "html", + "html": "html", + "http": "http", + "hxx": "header", + "icns": "image", + "ico": "image", + "iml": "xml", + "ini": "ini", + "inl": "header", + "ipynb": "notebook", + "jar": "class", + "java": "java", + "jl": "julia", + "jpeg": "image", + "jpg": "image", + "js": "javascript", + "json": "json", + "json5": "json", + "jsonc": "json", + "jsx": "react", + "kt": "kotlin", + "kts": "kotlin", + "less": "less", + "lhs": "haskell", + "lock": "lock", + "log": "log", + "lua": "lua", + "m": "objc", + "m4a": "audio", + "markdown": "markdown", + "md": "markdown", + "mdx": "markdown", + "mjs": "javascript", + "mkv": "video", + "ml": "ocaml", + "mli": "ocaml", + "mm": "objc", + "mov": "video", + "mp3": "audio", + "mp4": "video", + "mts": "typescript", + "nim": "nim", + "nix": "nix", + "ogg": "audio", + "otf": "font", + "patch": "diff", + "pdf": "pdf", + "php": "php", + "pl": "perl", + "plist": "xml", + "pm": "perl", + "png": "image", + "prisma": "database", + "properties": "ini", + "proto": "proto", + "ps1": "powershell", + "psd1": "powershell", + "psm1": "powershell", + "py": "python", + "pyi": "python", + "pyw": "python", + "r": "r", + "rake": "ruby", + "rar": "archive", + "rb": "ruby", + "rest": "http", + "rmd": "r", + "rs": "rust", + "sass": "sass", + "sbt": "scala", + "sc": "scala", + "scala": "scala", + "scss": "sass", + "sh": "shell", + "sol": "solidity", + "spec.js": "test", + "spec.jsx": "test", + "spec.mjs": "test", + "spec.mts": "test", + "spec.ts": "test", + "spec.tsx": "test", + "sql": "database", + "sqlite": "database", + "sty": "tex", + "svelte": "svelte", + "svg": "svg", + "swift": "swift", + "tar": "archive", + "test.js": "test", + "test.jsx": "test", + "test.mjs": "test", + "test.mts": "test", + "test.py": "test", + "test.rs": "test", + "test.ts": "test", + "test.tsx": "test", + "tex": "tex", + "text": "text", + "tf": "terraform", + "tfvars": "terraform", + "tgz": "archive", + "tif": "image", + "tiff": "image", + "toml": "toml", + "ts": "typescript", + "tsv": "csv", + "tsx": "react-ts", + "ttf": "font", + "txt": "text", + "vim": "vim", + "vue": "vue", + "wasm": "wasm", + "wat": "wasm", + "wav": "audio", + "webm": "video", + "webp": "image", + "woff": "font", + "woff2": "font", + "xhtml": "html", + "xml": "xml", + "xsd": "xml", + "xsl": "xml", + "xz": "archive", + "yaml": "yaml", + "yml": "yaml", + "zig": "zig", + "zip": "archive", + "zon": "zig", + "zsh": "shell", + "zst": "archive" + }, + "fileNames": { + ".clippy.toml": "settings", + ".dockerignore": "docker", + ".editorconfig": "editorconfig", + ".env": "env", + ".env.development": "env", + ".env.example": "env", + ".env.local": "env", + ".env.production": "env", + ".eslintrc": "editorconfig", + ".eslintrc.json": "editorconfig", + ".gitattributes": "git", + ".gitignore": "git", + ".gitkeep": "git", + ".gitmodules": "git", + ".mailmap": "git", + ".npmignore": "npm", + ".npmrc": "npm", + ".oxlintrc.json": "editorconfig", + ".prettierignore": "editorconfig", + ".prettierrc": "editorconfig", + ".rustfmt.toml": "settings", + "bun.lockb": "lock", + "cargo.lock": "lock", + "cargo.toml": "cargo", + "clippy.toml": "settings", + "cmakelists.txt": "makefile", + "compose.yaml": "docker", + "compose.yml": "docker", + "composer.lock": "lock", + "containerfile": "docker", + "copying": "license", + "deny.toml": "settings", + "docker-compose.yaml": "docker", + "docker-compose.yml": "docker", + "dockerfile": "docker", + "gemfile.lock": "lock", + "gnumakefile": "makefile", + "go.mod": "gomod", + "go.sum": "gomod", + "go.work": "gomod", + "jsconfig.json": "tsconfig", + "justfile": "makefile", + "licence": "license", + "licence.md": "license", + "license": "license", + "license.md": "license", + "license.txt": "license", + "makefile": "makefile", + "mise.toml": "editorconfig", + "notice": "license", + "package-lock.json": "lock", + "package.json": "npm", + "pnpm-lock.yaml": "lock", + "pnpm-workspace.yaml": "pnpm", + "poetry.lock": "lock", + "readme": "readme", + "readme.md": "readme", + "readme.rst": "readme", + "readme.txt": "readme", + "rust-toolchain": "cargo", + "rust-toolchain.toml": "cargo", + "rustfmt.toml": "settings", + "tsconfig.base.json": "tsconfig", + "tsconfig.json": "tsconfig", + "uv.lock": "lock", + "vite.config.js": "vite", + "vite.config.mts": "vite", + "vite.config.ts": "vite", + "vitest.config.mts": "vite", + "vitest.config.ts": "vite", + "yarn.lock": "lock" + }, + "folderNames": { + ".cargo": "folder-config", + ".config": "folder-config", + ".git": "folder-git", + ".github": "folder-git", + ".gitlab": "folder-git", + ".husky": "folder-git", + ".idea": "folder-config", + ".venv": "folder-deps", + ".vscode": "folder-config", + "__tests__": "folder-test", + "addons": "folder-plugins", + "api": "folder-api", + "assets": "folder-assets", + "bin": "folder-dist", + "build": "folder-dist", + "ci": "folder-scripts", + "components": "folder-components", + "config": "folder-config", + "configs": "folder-config", + "coverage": "folder-dist", + "crates": "folder-src", + "css": "folder-styles", + "database": "folder-db", + "db": "folder-db", + "deps": "folder-deps", + "dist": "folder-dist", + "doc": "folder-docs", + "docs": "folder-docs", + "documentation": "folder-docs", + "e2e": "folder-test", + "etc": "folder-config", + "extensions": "folder-plugins", + "features": "folder-components", + "fixtures": "folder-test", + "fonts": "folder-assets", + "handlers": "folder-api", + "i18n": "folder-i18n", + "icons": "folder-assets", + "images": "folder-assets", + "img": "folder-assets", + "internal": "folder-src", + "lang": "folder-i18n", + "lib": "folder-src", + "libs": "folder-src", + "locale": "folder-i18n", + "locales": "folder-i18n", + "media": "folder-assets", + "migrations": "folder-db", + "node_modules": "folder-deps", + "obj": "folder-dist", + "out": "folder-dist", + "packages": "folder-src", + "pages": "folder-components", + "pkg": "folder-src", + "plugins": "folder-plugins", + "public": "folder-assets", + "release": "folder-dist", + "res": "folder-assets", + "resources": "folder-assets", + "routes": "folder-api", + "rpc": "folder-api", + "schema": "folder-db", + "script": "folder-scripts", + "scripts": "folder-scripts", + "scss": "folder-styles", + "sdk": "folder-plugins", + "server": "folder-api", + "settings": "folder-config", + "source": "folder-src", + "sources": "folder-src", + "spec": "folder-test", + "specs": "folder-test", + "sql": "folder-db", + "src": "folder-src", + "static": "folder-assets", + "styles": "folder-styles", + "target": "folder-dist", + "tasks": "folder-scripts", + "test": "folder-test", + "testdata": "folder-test", + "tests": "folder-test", + "theme": "folder-styles", + "themes": "folder-styles", + "third_party": "folder-deps", + "tools": "folder-scripts", + "translations": "folder-i18n", + "ui": "folder-components", + "vendor": "folder-deps", + "venv": "folder-deps", + "views": "folder-components", + "widgets": "folder-components", + "wiki": "folder-docs" + } +} diff --git a/plugins/official/material-icons/icons/toml.svg b/plugins/official/material-icons/icons/toml.svg new file mode 100644 index 00000000..e322c4c8 --- /dev/null +++ b/plugins/official/material-icons/icons/toml.svg @@ -0,0 +1 @@ +TML diff --git a/plugins/official/material-icons/icons/tsconfig.svg b/plugins/official/material-icons/icons/tsconfig.svg new file mode 100644 index 00000000..b1e3d321 --- /dev/null +++ b/plugins/official/material-icons/icons/tsconfig.svg @@ -0,0 +1 @@ +TS diff --git a/plugins/official/material-icons/icons/typescript-def.svg b/plugins/official/material-icons/icons/typescript-def.svg new file mode 100644 index 00000000..2bdef4cd --- /dev/null +++ b/plugins/official/material-icons/icons/typescript-def.svg @@ -0,0 +1 @@ +D diff --git a/plugins/official/material-icons/icons/typescript.svg b/plugins/official/material-icons/icons/typescript.svg new file mode 100644 index 00000000..ff3be503 --- /dev/null +++ b/plugins/official/material-icons/icons/typescript.svg @@ -0,0 +1 @@ +TS diff --git a/plugins/official/material-icons/icons/video.svg b/plugins/official/material-icons/icons/video.svg new file mode 100644 index 00000000..7bc2ac04 --- /dev/null +++ b/plugins/official/material-icons/icons/video.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/vim.svg b/plugins/official/material-icons/icons/vim.svg new file mode 100644 index 00000000..46ff8ce6 --- /dev/null +++ b/plugins/official/material-icons/icons/vim.svg @@ -0,0 +1 @@ +VI diff --git a/plugins/official/material-icons/icons/vite.svg b/plugins/official/material-icons/icons/vite.svg new file mode 100644 index 00000000..402a8dee --- /dev/null +++ b/plugins/official/material-icons/icons/vite.svg @@ -0,0 +1 @@ +V diff --git a/plugins/official/material-icons/icons/vue.svg b/plugins/official/material-icons/icons/vue.svg new file mode 100644 index 00000000..0481473a --- /dev/null +++ b/plugins/official/material-icons/icons/vue.svg @@ -0,0 +1 @@ +V diff --git a/plugins/official/material-icons/icons/wasm.svg b/plugins/official/material-icons/icons/wasm.svg new file mode 100644 index 00000000..b520537d --- /dev/null +++ b/plugins/official/material-icons/icons/wasm.svg @@ -0,0 +1 @@ +WA diff --git a/plugins/official/material-icons/icons/xml.svg b/plugins/official/material-icons/icons/xml.svg new file mode 100644 index 00000000..4f3edab6 --- /dev/null +++ b/plugins/official/material-icons/icons/xml.svg @@ -0,0 +1 @@ + diff --git a/plugins/official/material-icons/icons/yaml.svg b/plugins/official/material-icons/icons/yaml.svg new file mode 100644 index 00000000..e1f12636 --- /dev/null +++ b/plugins/official/material-icons/icons/yaml.svg @@ -0,0 +1 @@ +YML diff --git a/plugins/official/material-icons/icons/zig.svg b/plugins/official/material-icons/icons/zig.svg new file mode 100644 index 00000000..26894c3f --- /dev/null +++ b/plugins/official/material-icons/icons/zig.svg @@ -0,0 +1 @@ +Z diff --git a/plugins/official/material-icons/plugin.toml b/plugins/official/material-icons/plugin.toml new file mode 100644 index 00000000..4c56e7a6 --- /dev/null +++ b/plugins/official/material-icons/plugin.toml @@ -0,0 +1,15 @@ +id = "openidea.material-icons" +name = "Material Icons" +version = "0.1.0" +description = "Colourful file and folder icons on the Material palette: 100+ icons for languages, well-known files and project folders." +authors = ["OpenIDEA contributors"] +license = "Apache-2.0" +change-notes = "0.1.0 — first release: 106 icons covering 189 extensions, 71 file names and 92 folder names." +engines.openidea = "^1.0" + +# Apply it in Settings › Plugins › Material Icons. The icons are generated by +# generate.py (not part of the package); edit its tables and re-run it. +[[contributes.iconThemes]] +id = "material" +label = "Material Icons" +path = "icons/theme.json" diff --git a/plugins/official/mybatis/.gitignore b/plugins/official/mybatis/.gitignore new file mode 100644 index 00000000..ea8c4bf7 --- /dev/null +++ b/plugins/official/mybatis/.gitignore @@ -0,0 +1 @@ +/target diff --git a/plugins/official/mybatis/Cargo.lock b/plugins/official/mybatis/Cargo.lock new file mode 100644 index 00000000..f4c6da46 --- /dev/null +++ b/plugins/official/mybatis/Cargo.lock @@ -0,0 +1,333 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "openidea-plugin-openidea-mybatis" +version = "0.1.0" +dependencies = [ + "openidea-plugin", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[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 = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +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 = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/plugins/official/mybatis/Cargo.toml b/plugins/official/mybatis/Cargo.toml new file mode 100644 index 00000000..415bdf6a --- /dev/null +++ b/plugins/official/mybatis/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "openidea-plugin-openidea-mybatis" +version = "0.1.0" +edition = "2024" +publish = false + +# A plugin builds on its own (target wasm32-wasip2), outside any IDE workspace. +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../sdk/rust/openidea-plugin" } + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/plugins/official/mybatis/dist/plugin.wasm b/plugins/official/mybatis/dist/plugin.wasm new file mode 100644 index 00000000..5ed3800a Binary files /dev/null and b/plugins/official/mybatis/dist/plugin.wasm differ diff --git a/plugins/official/mybatis/dist/plugin.wasm.sources b/plugins/official/mybatis/dist/plugin.wasm.sources new file mode 100644 index 00000000..0241ff75 --- /dev/null +++ b/plugins/official/mybatis/dist/plugin.wasm.sources @@ -0,0 +1 @@ +f7df58bb0ab2b92370b148de2614174ec1ff9b01c0078b5c20bd331f82298616 diff --git a/plugins/official/mybatis/plugin.toml b/plugins/official/mybatis/plugin.toml new file mode 100644 index 00000000..fac11916 --- /dev/null +++ b/plugins/official/mybatis/plugin.toml @@ -0,0 +1,17 @@ +id = "openidea.mybatis" +name = "MyBatis Navigator" +version = "0.1.0" +description = "Jumps between MyBatis mapper interfaces and their XML statements (gutter arrows and Go to Definition), completes statement ids and #{parameters}." +authors = ["OpenIDEA contributors"] +license = "Apache-2.0" +change-notes = "0.1.0 — first release: navigation both ways, line markers, id and parameter completion." +engines.openidea = "^1.0" +wasm = "dist/plugin.wasm" +activation = ["on-command:*"] + +[capabilities] +required = ["project.read"] + +[[contributes.providers]] +kinds = ["definition", "line-markers", "completion"] +languages = ["java", "xml"] diff --git a/plugins/official/mybatis/src/lib.rs b/plugins/official/mybatis/src/lib.rs new file mode 100644 index 00000000..d10b135a --- /dev/null +++ b/plugins/official/mybatis/src/lib.rs @@ -0,0 +1,376 @@ +//! MyBatis Navigator for OpenIDEA: a mapper interface (`com.acme.UserMapper`) +//! and the XML with `` point at each +//! other: gutter arrows and Go to Definition on methods and statement ids, +//! completion of statement ids and `#{parameters}`. + +use openidea_plugin::providers::{CompletionItem, CompletionKind, Document, LineMarker, Providers}; +use openidea_plugin::text::{offset, position}; +use openidea_plugin::{Error, Invocation, Location, Plugin, Position, Project, Range, host, register_plugin}; +use std::collections::BTreeMap; +use std::time::{Duration, Instant}; + +/// How long the namespace → XML file index is trusted. +const INDEX_TTL: Duration = Duration::from_secs(30); +const MAX_XML: u32 = 5000; +const STATEMENTS: [&str; 4] = ["select", "insert", "update", "delete"]; + +/// A named thing and where its name is. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Named { + pub name: String, + pub range: Range, +} + +/// A mapper XML file. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct MapperXml { + pub namespace: Option, + /// `` (the id value's range). + pub statements: Vec, +} + +/// A Java interface. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct MapperJava { + /// Fully qualified name. + pub name: Option, + pub methods: Vec<(Named, Vec)>, +} + +fn range_of(text: &str, start: usize, end: usize) -> Range { + Range::new(position(text, start), position(text, end)) +} + +pub fn parse_xml(text: &str) -> MapperXml { + let mut out = MapperXml::default(); + let attr = |tag_start: usize, name: &str| -> Option<(String, usize, usize)> { + let tag_end = text[tag_start..].find('>').map_or(text.len(), |i| tag_start + i); + let tag = &text[tag_start..tag_end]; + let i = tag.find(&format!("{name}=\""))? + name.len() + 2; + let j = tag[i..].find('"')? + i; + Some((tag[i..j].to_owned(), tag_start + i, tag_start + j)) + }; + let mut at = 0; + while let Some(i) = text[at..].find('<') { + let start = at + i + 1; + at = start; + let name: String = text[start..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect(); + if name == "mapper" { + out.namespace = attr(start, "namespace").map(|(v, ..)| v); + } else if STATEMENTS.contains(&name.as_str()) + && let Some((id, s, e)) = attr(start, "id") + { + out.statements.push(Named { name: id, range: range_of(text, s, e) }); + } + } + out +} + +fn ident(c: char) -> bool { + c.is_alphanumeric() || c == '_' || c == '$' +} + +/// The interface's name and methods (with their parameter names). +pub fn parse_java(text: &str) -> MapperJava { + let package = + text.lines().find_map(|l| l.trim().strip_prefix("package ").map(|p| p.trim_end_matches(';').trim().to_owned())); + let Some(i) = text.find("interface ") else { return MapperJava::default() }; + let simple: String = text[i + 10..].trim_start().chars().take_while(|c| ident(*c)).collect(); + let name = Some(match package { + Some(p) => format!("{p}.{simple}"), + None => simple, + }); + let body_start = text[i..].find('{').map_or(text.len(), |b| i + b + 1); + let mut methods = Vec::new(); + let mut depth = 0; + let mut stmt_start = body_start; + let bytes: Vec<(usize, char)> = text[body_start..].char_indices().map(|(k, c)| (body_start + k, c)).collect(); + for (k, c) in bytes { + match c { + '{' => depth += 1, + '}' if depth == 0 => break, + '}' => { + depth -= 1; + stmt_start = k + 1; + } + ';' if depth == 0 => { + let stmt = &text[stmt_start..k]; + if let Some(paren) = stmt.find('(') { + let before = stmt[..paren].trim_end(); + let name_start = before.rfind(|c: char| !ident(c)).map_or(0, |p| p + 1); + let method = &before[name_start..]; + if !method.is_empty() && !before.contains(" default ") { + let s = stmt_start + name_start; + let params = stmt[paren + 1..stmt.rfind(')').unwrap_or(stmt.len())] + .split(',') + .filter_map(|p| { + // `@Param("id") long id` → the @Param name wins. + if let Some(q) = p.find("@Param(\"") { + return p[q + 8..].split('"').next().map(str::to_owned); + } + p.split_whitespace().last().map(|n| n.trim_matches(|c: char| !ident(c)).to_owned()) + }) + .filter(|n| !n.is_empty()) + .collect(); + methods.push(( + Named { name: method.to_owned(), range: range_of(text, s, s + method.len()) }, + params, + )); + } + } + stmt_start = k + 1; + } + _ => {} + } + } + MapperJava { name, methods } +} + +fn project_of(path: &str) -> Option { + host::projects() + .ok()? + .into_iter() + .filter(|p| p.root().is_ok_and(|r| path.starts_with(&r))) + .max_by_key(|p| p.root().map(|r| r.len()).unwrap_or(0)) +} + +#[derive(Default)] +pub struct Navigator { + /// project root → (namespace → XML path), with when it was built. + xml_index: BTreeMap)>, +} + +impl Navigator { + /// The XML mapping `namespace`, (re)indexing the project when needed. + fn xml_for(&mut self, project: &Project, namespace: &str) -> Option<(String, MapperXml)> { + let root = project.root().ok()?; + for attempt in 0..2 { + let fresh = self.xml_index.get(&root).is_some_and(|(at, _)| at.elapsed() < INDEX_TTL); + if !fresh || attempt == 1 { + let mut map = BTreeMap::new(); + for path in project.find_files("**/*.xml", MAX_XML).ok()? { + let Ok(text) = project.read_file(&path) else { continue }; + if !text.contains(" Option<(String, MapperJava)> { + let rel = format!("**/{}.java", namespace.replace('.', "/")); + let path = project.find_files(&rel, 1).ok()?.into_iter().next()?; + let java = parse_java(&project.read_file(&path).ok()?); + (java.name.as_deref() == Some(namespace)).then_some((path, java)) + } + + /// Pairs of (name in this document, target location) for `doc`. + fn links(&mut self, doc: &Document) -> Vec<(Named, Location, String)> { + let Some(project) = project_of(&doc.path) else { return Vec::new() }; + if doc.language == "xml" { + let xml = parse_xml(&doc.text); + let Some(ns) = xml.namespace else { return Vec::new() }; + let Some((path, java)) = Self::java_for(&project, &ns) else { return Vec::new() }; + let simple = ns.rsplit('.').next().unwrap_or(&ns).to_owned(); + xml.statements + .into_iter() + .filter_map(|s| { + let (m, _) = java.methods.iter().find(|(m, _)| m.name == s.name)?; + let tip = format!("{simple}.{}()", m.name); + Some((s, Location { path: path.clone(), range: m.range }, tip)) + }) + .collect() + } else { + let java = parse_java(&doc.text); + let Some(name) = java.name else { return Vec::new() }; + let Some((path, xml)) = self.xml_for(&project, &name) else { return Vec::new() }; + let file = path.rsplit(['/', '\\']).next().unwrap_or(&path).to_owned(); + java.methods + .into_iter() + .filter_map(|(m, _)| { + let s = xml.statements.iter().find(|s| s.name == m.name)?; + Some((m, Location { path: path.clone(), range: s.range }, format!("{file}: {}", s.name))) + }) + .collect() + } + } +} + +fn contains(r: Range, p: Position) -> bool { + r.start <= p && p <= r.end +} + +impl Providers for Navigator { + fn line_markers(&mut self, doc: &Document) -> Vec { + let icon = if doc.language == "xml" { "implementing" } else { "implemented" }; + self.links(doc) + .into_iter() + .map(|(n, target, tip)| LineMarker { + line: n.range.start.line, + icon: Some(icon.into()), + tooltip: format!("Go to {tip}"), + target: Some(target), + }) + .collect() + } + + fn definition(&mut self, doc: &Document, at: Position) -> Vec { + self.links(doc).into_iter().filter(|(n, ..)| contains(n.range, at)).map(|(_, l, _)| l).collect() + } + + fn completion(&mut self, doc: &Document, at: Position, _trigger: Option<&str>) -> Vec { + if doc.language != "xml" { + return Vec::new(); + } + let Some(cursor) = offset(&doc.text, at) else { return Vec::new() }; + let before = &doc.text[..cursor]; + let xml = parse_xml(&doc.text); + let Some(ns) = xml.namespace.clone() else { return Vec::new() }; + let Some(project) = project_of(&doc.path) else { return Vec::new() }; + let Some((_, java)) = Self::java_for(&project, &ns) else { return Vec::new() }; + let line_start = before.rfind('\n').map_or(0, |i| i + 1); + let line = &before[line_start..]; + // Inside `id="…` of a statement tag: the interface's unmapped methods. + if let Some(i) = line.rfind("id=\"") + && !line[i + 4..].contains('"') + && STATEMENTS.iter().any(|t| line.contains(&format!("<{t}"))) + { + let typed = &line[i + 4..]; + let start = Position::new(at.line, at.character - typed.encode_utf16().count() as u32); + return java + .methods + .iter() + .filter(|(m, _)| m.name.starts_with(typed) && !xml.statements.iter().any(|s| s.name == m.name)) + .map(|(m, _)| CompletionItem { + replace: Some(Range::new(start, at)), + detail: Some(ns.rsplit('.').next().unwrap_or(&ns).into()), + ..CompletionItem::new(&m.name, CompletionKind::Method) + }) + .collect(); + } + // After `#{`: the enclosing statement's parameters. + if let Some(i) = before.rfind("#{") + && !before[i..].contains('}') + { + let typed = &before[i + 2..]; + let statement = + xml.statements.iter().rev().find(|s| offset(&doc.text, s.range.start).is_some_and(|o| o < cursor)); + let Some((_, params)) = statement.and_then(|s| java.methods.iter().find(|(m, _)| m.name == s.name)) else { + return Vec::new(); + }; + let start = Position::new(at.line, at.character - typed.encode_utf16().count() as u32); + return params + .iter() + .filter(|p| p.starts_with(typed)) + .map(|p| CompletionItem { + replace: Some(Range::new(start, at)), + ..CompletionItem::new(p, CompletionKind::Variable) + }) + .collect(); + } + Vec::new() + } +} + +impl Plugin for Navigator { + fn run_command(&mut self, id: &str, _ctx: &Invocation, _arg: Option<&str>) -> Result, Error> { + Err(Error::NotFound(format!("command {id}"))) + } +} + +register_plugin!(Navigator, providers); + +#[cfg(test)] +mod tests { + use super::*; + use openidea_plugin::mock::MockHost; + + const JAVA: &str = "package com.acme;\n\nimport org.apache.ibatis.annotations.Param;\n\npublic interface UserMapper {\n User findById(@Param(\"id\") long id);\n\n int insert(User user);\n\n default void helper() {}\n\n List search(String name, int limit);\n}\n"; + const XML: &str = "\n\n \n \n insert into users values (#{user})\n \n \n\n"; + + #[test] + fn parses_both_sides() { + let java = parse_java(JAVA); + assert_eq!(java.name.as_deref(), Some("com.acme.UserMapper")); + let names: Vec<_> = java.methods.iter().map(|(m, p)| (m.name.as_str(), p.clone())).collect(); + assert_eq!( + names, + [ + ("findById", vec!["id".to_owned()]), + ("insert", vec!["user".into()]), + ("search", vec!["name".into(), "limit".into()]) + ] + ); + assert_eq!(java.methods[0].0.range, Range::new(Position::new(5, 9), Position::new(5, 17))); + let xml = parse_xml(XML); + assert_eq!(xml.namespace.as_deref(), Some("com.acme.UserMapper")); + assert_eq!(xml.statements.iter().map(|s| s.name.as_str()).collect::>(), ["findById", "insert", ""]); + assert_eq!(xml.statements[0].range, Range::new(Position::new(2, 14), Position::new(2, 22))); + } + + fn setup() -> MockHost { + let host = MockHost::install(); + host.add_file("src/main/java/com/acme/UserMapper.java", JAVA); + host.add_file("src/main/resources/mapper/UserMapper.xml", XML); + host.add_file("pom.xml", ""); + host + } + + fn doc(path: &str, language: &str, text: &str) -> Document { + Document { path: path.into(), language: language.into(), version: 1, text: text.into() } + } + + #[test] + fn navigates_both_ways() { + let _host = setup(); + let mut n = Navigator::default(); + let java = doc("/project/src/main/java/com/acme/UserMapper.java", "java", JAVA); + let markers = n.line_markers(&java); + assert_eq!(markers.iter().map(|m| m.line).collect::>(), [5, 7], "search has no statement"); + assert_eq!(markers[0].tooltip, "Go to UserMapper.xml: findById"); + let target = markers[0].target.as_ref().unwrap(); + assert_eq!( + (target.path.as_str(), target.range.start), + ("/project/src/main/resources/mapper/UserMapper.xml", Position::new(2, 14)) + ); + + let xml = doc("/project/src/main/resources/mapper/UserMapper.xml", "xml", XML); + let to_java = n.definition(&xml, Position::new(5, 15)); + assert_eq!(to_java.len(), 1); + assert_eq!((to_java[0].path.ends_with("UserMapper.java"), to_java[0].range.start), (true, Position::new(7, 8))); + assert!(n.definition(&xml, Position::new(3, 5)).is_empty(), "not on an id"); + assert_eq!(n.line_markers(&xml)[0].tooltip, "Go to UserMapper.findById()"); + } + + #[test] + fn completes_ids_and_parameters() { + let _host = setup(); + let mut n = Navigator::default(); + let xml = doc("/project/src/main/resources/mapper/UserMapper.xml", "xml", XML); + let ids = n.completion(&xml, Position::new(8, 14), None); + assert_eq!(ids.iter().map(|c| c.label.as_str()).collect::>(), ["search"], "unmapped methods only"); + let text = XML.replace("#{id}", "#{"); + let xml = doc("/project/src/main/resources/mapper/UserMapper.xml", "xml", &text); + let params = n.completion(&xml, Position::new(3, 38), None); + assert_eq!(params.iter().map(|c| c.label.as_str()).collect::>(), ["id"]); + } +} diff --git a/plugins/official/regex-tester/Cargo.lock b/plugins/official/regex-tester/Cargo.lock new file mode 100644 index 00000000..5ccd74eb --- /dev/null +++ b/plugins/official/regex-tester/Cargo.lock @@ -0,0 +1,373 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "openidea-plugin-openidea-regex-tester" +version = "0.1.0" +dependencies = [ + "openidea-plugin", + "regex", + "serde_json", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[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 = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +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 = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/plugins/official/regex-tester/Cargo.toml b/plugins/official/regex-tester/Cargo.toml new file mode 100644 index 00000000..ae13c79c --- /dev/null +++ b/plugins/official/regex-tester/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "openidea-plugin-openidea-regex-tester" +version = "0.1.0" +edition = "2024" +publish = false + +# A plugin builds on its own (target wasm32-wasip2), outside any IDE workspace. +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../sdk/rust/openidea-plugin" } +regex = { version = "1", default-features = false, features = ["std", "unicode", "perf-dfa", "perf-onepass", "perf-backtrack", "perf-inline"] } +serde_json = "1" + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/plugins/official/regex-tester/dist/plugin.wasm b/plugins/official/regex-tester/dist/plugin.wasm new file mode 100644 index 00000000..9eed421b Binary files /dev/null and b/plugins/official/regex-tester/dist/plugin.wasm differ diff --git a/plugins/official/regex-tester/dist/plugin.wasm.sources b/plugins/official/regex-tester/dist/plugin.wasm.sources new file mode 100644 index 00000000..b9543105 --- /dev/null +++ b/plugins/official/regex-tester/dist/plugin.wasm.sources @@ -0,0 +1 @@ +d2e35f3e4ee6b699899ea43fdf96d5ec99f0730c502f94fd6f3246e605be99a7 diff --git a/plugins/official/regex-tester/plugin.toml b/plugins/official/regex-tester/plugin.toml new file mode 100644 index 00000000..a889b96a --- /dev/null +++ b/plugins/official/regex-tester/plugin.toml @@ -0,0 +1,32 @@ +id = "openidea.regex-tester" +name = "Regex Tester" +version = "0.1.0" +description = "Try a regular expression against sample text: matches highlighted as you type, capture groups, and a replacement preview. Takes the editor's selection as the text." +authors = ["OpenIDEA contributors"] +license = "Apache-2.0" +change-notes = "0.1.0 — first release: live matching with flags, capture groups, replacement preview, the editor's selection as test text." +engines.openidea = "^1.0" +wasm = "dist/plugin.wasm" +activation = ["on-view:regex", "on-command:*"] + +[capabilities] +required = ["editor.read"] + +[[contributes.views]] +id = "regex" +title = "Regex Tester" +icon = "regex" +location = "bottom" + +[[contributes.commands]] +id = "test-selection" +title = "Regex Tester: Test Selection" +category = "Regex Tester" + +[[contributes.menus]] +menu = "editor.context" +command = "test-selection" + +[contributes.settings] +title = "Regex Tester" +schema = "settings.schema.json" diff --git a/plugins/official/regex-tester/settings.schema.json b/plugins/official/regex-tester/settings.schema.json new file mode 100644 index 00000000..91f08045 --- /dev/null +++ b/plugins/official/regex-tester/settings.schema.json @@ -0,0 +1,14 @@ +{ + "properties": { + "ignoreCase": { + "type": "boolean", + "title": "Ignore case by default", + "default": false + }, + "multiLine": { + "type": "boolean", + "title": "^ and $ match at line breaks by default", + "default": true + } + } +} diff --git a/plugins/official/regex-tester/src/lib.rs b/plugins/official/regex-tester/src/lib.rs new file mode 100644 index 00000000..f01f2383 --- /dev/null +++ b/plugins/official/regex-tester/src/lib.rs @@ -0,0 +1,280 @@ +//! Regex Tester for OpenIDEA: a tool window whose page (an `html` body) sends +//! the pattern, flags, text and replacement as you type; the plugin matches +//! them with Rust's `regex` (linear time, so no pattern can hang it) and posts +//! the matches back, in UTF-16 offsets the page can highlight. *Use Selection* +//! takes the focused editor's selection as the text. + +use openidea_plugin::host; +use openidea_plugin::views::{Body, Button, View, ViewEvent, Viewport, Views}; +use openidea_plugin::{Error, Invocation, Plugin, register_plugin}; +use regex::RegexBuilder; +use serde_json::{Value, json}; + +pub const VIEW: &str = "regex"; +/// Longest text matched (bytes). +const MAX_TEXT: usize = 1 << 20; +/// Most matches sent back (all are counted). +const MAX_MATCHES: usize = 1000; +/// Longest replacement preview sent back (bytes). +const MAX_REPLACED: usize = 256 << 10; +const PAGE: &str = include_str!("page.html"); + +#[derive(Default)] +pub struct RegexTester; + +/// A request from the page. +#[derive(Debug, PartialEq)] +pub struct Run { + pub seq: u64, + pub pattern: String, + pub flags: String, + pub text: String, + pub replace: Option, +} + +impl Run { + pub fn parse(v: &Value) -> Option { + let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned); + Some(Run { + seq: v.get("seq").and_then(Value::as_u64).unwrap_or(0), + pattern: s("pattern")?, + flags: s("flags").unwrap_or_default(), + text: s("text").unwrap_or_default(), + replace: s("replace"), + }) + } +} + +/// UTF-16 offset of every byte offset that starts a char (and the end). +fn utf16_offsets(text: &str) -> Vec { + let mut map = vec![0u32; text.len() + 1]; + let mut at = 0u32; + for (i, c) in text.char_indices() { + map[i] = at; + at += c.len_utf16() as u32; + } + map[text.len()] = at; + map +} + +/// Matches `run` and returns the page's result message. +pub fn evaluate(run: &Run) -> Value { + let fail = |e: String| json!({ "op": "result", "seq": run.seq, "error": e, "matches": [], "count": 0 }); + if run.text.len() > MAX_TEXT { + return fail(format!("the text is longer than {} KiB", MAX_TEXT >> 10)); + } + let flag = |c: char| run.flags.contains(c); + let re = match RegexBuilder::new(&run.pattern) + .case_insensitive(flag('i')) + .multi_line(flag('m')) + .dot_matches_new_line(flag('s')) + .ignore_whitespace(flag('x')) + .size_limit(8 << 20) + .build() + { + Ok(re) => re, + // The parser's message names the position; keep it, minus the repeated pattern. + Err(e) => return fail(e.to_string()), + }; + if run.pattern.is_empty() { + return json!({ "op": "result", "seq": run.seq, "error": null, "matches": [], "count": 0, "groups": [] }); + } + let at = utf16_offsets(&run.text); + let names: Vec = re.capture_names().skip(1).map(|n| n.map_or(Value::Null, |n| json!(n))).collect(); + let mut matches = Vec::new(); + let mut count = 0usize; + for caps in re.captures_iter(&run.text) { + count += 1; + if matches.len() < MAX_MATCHES { + let groups: Vec = (1..caps.len()) + .map(|i| caps.get(i).map_or(Value::Null, |g| json!([at[g.start()], at[g.end()]]))) + .collect(); + let m = caps.get(0).expect("group 0"); + matches.push(json!({ "s": at[m.start()], "e": at[m.end()], "groups": groups })); + } + } + let replaced = run.replace.as_ref().map(|r| { + let mut out = re.replace_all(&run.text, r.as_str()).into_owned(); + if out.len() > MAX_REPLACED { + let mut cut = MAX_REPLACED; + while !out.is_char_boundary(cut) { + cut -= 1; + } + out.truncate(cut); + out.push('…'); + } + out + }); + json!({ + "op": "result", + "seq": run.seq, + "error": null, + "matches": matches, + "count": count, + "groups": names, + "replaced": replaced, + }) +} + +/// The flags the page starts with, from the settings. +fn default_flags() -> String { + let mut f = String::new(); + if host::setting_bool("ignoreCase").unwrap_or(false) { + f.push('i'); + } + if host::setting_bool("multiLine").unwrap_or(true) { + f.push('m'); + } + f +} + +/// The focused editor's first non-empty selection, else its whole text. +fn selection_text(ctx: &Invocation) -> Result { + let editor = ctx.editor().ok_or_else(|| Error::Invalid("focus an editor first".into()))?; + let doc = editor.document()?; + let selected = editor.selections()?.into_iter().filter_map(|r| doc.text_in(r)).find(|t| !t.is_empty()); + let text = selected.map(str::to_owned).unwrap_or(doc.text); + Ok(if text.len() > MAX_TEXT { + let mut cut = MAX_TEXT; + while !text.is_char_boundary(cut) { + cut -= 1; + } + text[..cut].to_owned() + } else { + text + }) +} + +fn post(message: &Value) -> Result<(), Error> { + host::post_view_message(VIEW, &message.to_string()) +} + +impl Plugin for RegexTester { + fn run_command(&mut self, id: &str, ctx: &Invocation, _arg: Option<&str>) -> Result, Error> { + match id { + // To the open tool window (its page ignores it until it has loaded). + "test-selection" => post(&json!({ "op": "text", "text": selection_text(ctx)? })).map(|()| None), + _ => Err(Error::NotFound(format!("command {id}"))), + } + } +} + +impl Views for RegexTester { + fn render(&mut self, view: &str, _viewport: Option, _ctx: &Invocation) -> Result { + if view != VIEW { + return Err(Error::NotFound(view.into())); + } + // The page keeps its own state: the plugin only answers its messages, + // and never re-renders it (that would reload the frame). + let start = json!({ "flags": default_flags() }).to_string().replace('<', "\\u003c"); + let page = PAGE.replacen(r#""__START__""#, &start, 1); + Ok(View::new(Body::Html(page)).button(Button::new("selection", "Use Selection").icon("text"))) + } + + fn handle(&mut self, view: &str, event: ViewEvent, ctx: &Invocation) -> Result<(), Error> { + if view != VIEW { + return Err(Error::NotFound(view.into())); + } + match event { + ViewEvent::Button(b) if b == "selection" => post(&json!({ "op": "text", "text": selection_text(ctx)? })), + ViewEvent::Message(text) => { + let Ok(v) = serde_json::from_str::(&text) else { return Ok(()) }; + match v.get("op").and_then(Value::as_str) { + Some("run") => match Run::parse(&v) { + Some(run) => post(&evaluate(&run)), + None => Ok(()), + }, + Some("selection") => post(&json!({ "op": "text", "text": selection_text(ctx)? })), + _ => Ok(()), + } + } + _ => Ok(()), + } + } +} + +register_plugin!(RegexTester, views); + +#[cfg(test)] +mod tests { + use super::*; + use openidea_plugin::mock::MockHost; + + fn run(pattern: &str, flags: &str, text: &str, replace: Option<&str>) -> Value { + evaluate(&Run { + seq: 7, + pattern: pattern.into(), + flags: flags.into(), + text: text.into(), + replace: replace.map(str::to_owned), + }) + } + + #[test] + fn matches_with_groups_in_utf16_offsets() { + // "é" is one UTF-16 unit but two bytes; "😀" two units, four bytes. + let r = run(r"(?P\w+)@(\d+)", "", "é😀 ab@12 cd@3", None); + assert_eq!(r["error"], Value::Null); + assert_eq!(r["count"], 2); + assert_eq!(r["seq"], 7); + assert_eq!(r["groups"], json!(["word", null])); + assert_eq!(r["matches"][0], json!({ "s": 4, "e": 9, "groups": [[4, 6], [7, 9]] })); + assert_eq!(r["matches"][1]["s"], 10); + } + + #[test] + fn flags_change_the_match() { + let text = "One\none"; + assert_eq!(run("^one$", "", text, None)["count"], 0); + assert_eq!(run("^one$", "m", text, None)["count"], 1); + assert_eq!(run("^one$", "im", text, None)["count"], 2); + assert_eq!(run("e.o", "", text, None)["count"], 0); + assert_eq!(run("e.o", "s", text, None)["count"], 1); + assert_eq!(run("o n e", "x", text, None)["count"], 1); + } + + #[test] + fn replacement_preview_and_errors() { + let r = run(r"(\w+)@(\d+)", "", "ab@12, cd@3", Some("$2:$1")); + assert_eq!(r["replaced"], "12:ab, 3:cd"); + let bad = run("(unclosed", "", "x", None); + assert!(bad["error"].as_str().unwrap().contains("unclosed"), "{bad}"); + assert_eq!(bad["count"], 0); + assert_eq!(run("", "", "x", None)["count"], 0); + } + + #[test] + fn counts_every_match_but_sends_a_bounded_number() { + let text = "a".repeat(5000); + let r = run("a", "", &text, None); + assert_eq!(r["count"], 5000); + assert_eq!(r["matches"].as_array().unwrap().len(), MAX_MATCHES); + } + + #[test] + fn answers_the_page_and_reads_the_selection() { + let host = MockHost::install().with_capabilities(&["editor.read"]); + host.set_setting("ignoreCase", "true"); + let mut p = RegexTester; + let View { body: Body::Html(page), toolbar, .. } = p.render(VIEW, None, &host.invocation()).unwrap() else { + panic!("an html body") + }; + assert!(page.contains(r#"{"flags":"im"}"#), "the settings' flags start the page"); + assert_eq!(toolbar[0].id, "selection"); + + let msg = json!({ "op": "run", "seq": 1, "pattern": "b+", "flags": "", "text": "abbc" }).to_string(); + p.handle(VIEW, ViewEvent::Message(msg), &host.invocation()).unwrap(); + let (view, reply) = host.view_messages().pop().unwrap(); + assert_eq!(view, VIEW); + let reply: Value = serde_json::from_str(&reply).unwrap(); + assert_eq!((reply["count"].clone(), reply["matches"][0]["s"].clone()), (json!(1), json!(1))); + + host.open_editor("/p/a.txt", "plaintext", "first line\nsecond", &[(1, 0, 1, 6)]); + p.handle(VIEW, ViewEvent::Button("selection".into()), &host.invocation()).unwrap(); + let reply: Value = serde_json::from_str(&host.view_messages().pop().unwrap().1).unwrap(); + assert_eq!(reply, json!({ "op": "text", "text": "second" })); + + // Garbage from the page is ignored. + p.handle(VIEW, ViewEvent::Message("not json".into()), &host.invocation()).unwrap(); + } +} diff --git a/plugins/official/regex-tester/src/page.html b/plugins/official/regex-tester/src/page.html new file mode 100644 index 00000000..4dafa5a8 --- /dev/null +++ b/plugins/official/regex-tester/src/page.html @@ -0,0 +1,377 @@ + +
+
+ +
+ +
+ + + + +
+
+
+ +
+ + +
+ + + +
+
+ +
No matches yet.
+
+
+ diff --git a/plugins/official/solidity/.gitignore b/plugins/official/solidity/.gitignore new file mode 100644 index 00000000..ea8c4bf7 --- /dev/null +++ b/plugins/official/solidity/.gitignore @@ -0,0 +1 @@ +/target diff --git a/plugins/official/solidity/Cargo.lock b/plugins/official/solidity/Cargo.lock new file mode 100644 index 00000000..d2be61fe --- /dev/null +++ b/plugins/official/solidity/Cargo.lock @@ -0,0 +1,333 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "openidea-plugin-openidea-solidity" +version = "0.1.0" +dependencies = [ + "openidea-plugin", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[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 = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +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 = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/plugins/official/solidity/Cargo.toml b/plugins/official/solidity/Cargo.toml new file mode 100644 index 00000000..697f1b60 --- /dev/null +++ b/plugins/official/solidity/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "openidea-plugin-openidea-solidity" +version = "0.1.0" +edition = "2024" +publish = false + +# A plugin builds on its own (target wasm32-wasip2), outside any IDE workspace. +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../sdk/rust/openidea-plugin" } + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/plugins/official/solidity/dist/plugin.wasm b/plugins/official/solidity/dist/plugin.wasm new file mode 100644 index 00000000..3cb17fd7 Binary files /dev/null and b/plugins/official/solidity/dist/plugin.wasm differ diff --git a/plugins/official/solidity/dist/plugin.wasm.sources b/plugins/official/solidity/dist/plugin.wasm.sources new file mode 100644 index 00000000..d7a74f4c --- /dev/null +++ b/plugins/official/solidity/dist/plugin.wasm.sources @@ -0,0 +1 @@ +3893bd8ad06d3e19c0112081c6643b3bf3c67f5a184098432a6fd338426cd682 diff --git a/plugins/official/solidity/languages/solidity.toml b/plugins/official/solidity/languages/solidity.toml new file mode 100644 index 00000000..27c519dd --- /dev/null +++ b/plugins/official/solidity/languages/solidity.toml @@ -0,0 +1,21 @@ +id = "solidity" +name = "Solidity" +extensions = ["sol"] +line-comment = "//" +block-comment = ["/*", "*/"] +indent = { tab-size = 4, insert-spaces = true } + +[[language-servers]] +name = "solidity-language-server" +command = "nomicfoundation-solidity-language-server" +args = ["--stdio"] +root-markers = ["hardhat.config.ts", "hardhat.config.js", "foundry.toml", "truffle-config.js", "remappings.txt", "package.json"] +install-hint = "npm install -g @nomicfoundation/solidity-language-server" + +[[language-servers]] +name = "solc" +command = "solc" +args = ["--lsp"] +root-markers = ["foundry.toml", "remappings.txt"] +fallback = true +install-hint = "Install solc (https://docs.soliditylang.org/en/latest/installing-solidity.html)" diff --git a/plugins/official/solidity/plugin.toml b/plugins/official/solidity/plugin.toml new file mode 100644 index 00000000..cc03892b --- /dev/null +++ b/plugins/official/solidity/plugin.toml @@ -0,0 +1,41 @@ +id = "openidea.solidity" +name = "Solidity" +version = "0.1.0" +description = "Solidity support: file detection, highlighting, structure view and folding, plus the Solidity language server when it is installed." +authors = ["OpenIDEA contributors"] +license = "Apache-2.0" +change-notes = "0.1.0 — first release: .sol detection, highlighting, structure view, folding; language server via @nomicfoundation/solidity-language-server or solc." +engines.openidea = "^1.0" +# Highlighting, structure and folding come from this component; it is loaded +# when the first Solidity file is opened. +wasm = "dist/plugin.wasm" +activation = ["on-language:solidity"] + +# The language servers in the definition need `process:` capabilities; they +# are asked for on install and can be refused (the rest keeps working). +[[contributes.languages]] +path = "languages/solidity.toml" + +# Offered in Foundry / Hardhat projects once the program is allowed. +[[contributes.runDetectors]] +id = "forge-test" +name = "forge test" +files = ["foundry.toml"] +command = "forge" +args = ["test"] +test = true + +[[contributes.runDetectors]] +id = "forge-build" +name = "forge build" +files = ["foundry.toml"] +command = "forge" +args = ["build"] + +[[contributes.runDetectors]] +id = "hardhat-test" +name = "hardhat test" +files = ["hardhat.config.ts", "hardhat.config.js"] +command = "npx" +args = ["hardhat", "test"] +test = true diff --git a/plugins/official/solidity/src/lib.rs b/plugins/official/solidity/src/lib.rs new file mode 100644 index 00000000..def94bee --- /dev/null +++ b/plugins/official/solidity/src/lib.rs @@ -0,0 +1,689 @@ +//! Solidity for OpenIDEA: highlighting, structure view and folding from a +//! small hand-written lexer (the IDE has no Solidity grammar), exported as the +//! plugin's `syntax-provider`. Detection and the language server come from +//! `languages/solidity.toml`. + +use openidea_plugin::syntax::{Fold, FoldKind, Highlight, Symbol, SymbolKind, SyntaxProvider, Token, bracket_folds}; +use openidea_plugin::{Error, Invocation, Plugin, register_plugin}; +use std::ops::Range; + +#[derive(Default)] +pub struct Solidity; + +impl Plugin for Solidity { + fn run_command(&mut self, id: &str, _ctx: &Invocation, _arg: Option<&str>) -> Result, Error> { + Err(Error::NotFound(format!("command {id}"))) + } +} + +impl SyntaxProvider for Solidity { + fn highlights(&mut self, _language: &str, text: &str) -> Vec { + highlights(text) + } + + fn outline(&mut self, _language: &str, text: &str) -> Vec { + outline(text) + } + + fn folding(&mut self, _language: &str, text: &str) -> Vec { + folding(text) + } +} + +register_plugin!(Solidity, syntax); + +// --- lexer ------------------------------------------------------------------- + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Ident, + Number, + Str, + Comment, + DocComment, + Op, + Punct, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Lexeme { + kind: Kind, + start: usize, + end: usize, +} + +impl Lexeme { + fn text<'a>(&self, src: &'a str) -> &'a str { + &src[self.start..self.end] + } + + fn is_trivia(&self) -> bool { + matches!(self.kind, Kind::Comment | Kind::DocComment) + } +} + +fn is_ident_start(b: u8) -> bool { + b.is_ascii_alphabetic() || b == b'_' || b == b'$' +} + +fn is_ident(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' || b == b'$' +} + +fn lex(text: &str) -> Vec { + let bytes = text.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < bytes.len() { + let b = bytes[i]; + let start = i; + let kind = if b.is_ascii_whitespace() { + i += 1; + continue; + } else if bytes[i..].starts_with(b"//") { + let end = text[i..].find('\n').map_or(bytes.len(), |n| i + n); + let doc = bytes[i..].starts_with(b"///") && !bytes[i..].starts_with(b"////"); + i = end; + if doc { Kind::DocComment } else { Kind::Comment } + } else if bytes[i..].starts_with(b"/*") { + let end = text[i + 2..].find("*/").map_or(bytes.len(), |n| i + 2 + n + 2); + let doc = bytes[i..].starts_with(b"/**") && !bytes[i..].starts_with(b"/**/"); + i = end; + if doc { Kind::DocComment } else { Kind::Comment } + } else if b == b'"' || b == b'\'' { + i = string_end(bytes, i); + Kind::Str + } else if b.is_ascii_digit() { + i = number_end(bytes, i); + Kind::Number + } else if is_ident_start(b) { + while i < bytes.len() && is_ident(bytes[i]) { + i += 1; + } + // hex"…", unicode"…" + let word = &text[start..i]; + if (word == "hex" || word == "unicode") && matches!(bytes.get(i), Some(b'"' | b'\'')) { + i = string_end(bytes, i); + Kind::Str + } else { + Kind::Ident + } + } else if b"(){}[];,.".contains(&b) { + i += 1; + Kind::Punct + } else if b"+-*/%=!<>&|^~?:".contains(&b) { + while i < bytes.len() && b"+-*/%=!<>&|^~?:".contains(&bytes[i]) && !bytes[i..].starts_with(b"//") { + i += 1; + } + Kind::Op + } else { + // Anything else (non-ASCII outside strings): skip the whole character. + i += text[i..].chars().next().map_or(1, char::len_utf8); + continue; + }; + out.push(Lexeme { kind, start, end: i }); + } + out +} + +fn string_end(bytes: &[u8], open: usize) -> usize { + let quote = bytes[open]; + let mut i = open + 1; + while i < bytes.len() { + match bytes[i] { + b'\\' => i += 2, + b'\n' => return i, + c if c == quote => return i + 1, + _ => i += 1, + } + } + bytes.len() +} + +fn number_end(bytes: &[u8], mut i: usize) -> usize { + if bytes[i..].starts_with(b"0x") || bytes[i..].starts_with(b"0X") { + i += 2; + while i < bytes.len() && (bytes[i].is_ascii_hexdigit() || bytes[i] == b'_') { + i += 1; + } + return i; + } + while i < bytes.len() && (bytes[i].is_ascii_digit() || bytes[i] == b'_') { + i += 1; + } + if i + 1 < bytes.len() && bytes[i] == b'.' && bytes[i + 1].is_ascii_digit() { + i += 1; + while i < bytes.len() && (bytes[i].is_ascii_digit() || bytes[i] == b'_') { + i += 1; + } + } + if i < bytes.len() && (bytes[i] == b'e' || bytes[i] == b'E') { + let mut j = i + 1; + if j < bytes.len() && (bytes[j] == b'-' || bytes[j] == b'+') { + j += 1; + } + if j < bytes.len() && bytes[j].is_ascii_digit() { + i = j; + while i < bytes.len() && bytes[i].is_ascii_digit() { + i += 1; + } + } + } + i +} + +// --- highlighting -------------------------------------------------------------- + +const KEYWORDS: &[&str] = &[ + "abstract", + "anonymous", + "as", + "assembly", + "break", + "calldata", + "catch", + "constant", + "constructor", + "continue", + "contract", + "default", + "delete", + "do", + "else", + "emit", + "enum", + "error", + "event", + "external", + "fallback", + "for", + "from", + "function", + "global", + "if", + "immutable", + "import", + "indexed", + "interface", + "internal", + "is", + "let", + "library", + "memory", + "modifier", + "new", + "override", + "payable", + "pragma", + "private", + "public", + "pure", + "receive", + "return", + "returns", + "revert", + "solidity", + "storage", + "struct", + "switch", + "case", + "transient", + "try", + "type", + "unchecked", + "using", + "view", + "virtual", + "while", + "leave", + "wei", + "gwei", + "ether", + "seconds", + "minutes", + "hours", + "days", + "weeks", + "years", +]; + +const BUILTINS: &[&str] = &[ + "msg", + "block", + "tx", + "abi", + "now", + "gasleft", + "blockhash", + "blobhash", + "keccak256", + "sha256", + "ripemd160", + "ecrecover", + "addmod", + "mulmod", + "selfdestruct", + "require", + "assert", + "this", + "super", +]; + +const ATOMS: &[&str] = &["true", "false"]; + +fn is_elementary_type(word: &str) -> bool { + if matches!( + word, + "address" | "bool" | "string" | "byte" | "bytes" | "int" | "uint" | "fixed" | "ufixed" | "mapping" | "var" + ) { + return true; + } + let sized = |prefix: &str| { + word.strip_prefix(prefix).is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit() || b == b'x')) + }; + sized("uint") || sized("int") || sized("bytes") || sized("ufixed") || sized("fixed") +} + +/// The next lexeme that is not a comment. +fn next_code(lexemes: &[Lexeme], i: usize) -> Option<&Lexeme> { + lexemes[i + 1..].iter().find(|l| !l.is_trivia()) +} + +fn prev_code(lexemes: &[Lexeme], i: usize) -> Option<&Lexeme> { + lexemes[..i].iter().rev().find(|l| !l.is_trivia()) +} + +fn highlights(text: &str) -> Vec { + let lexemes = lex(text); + let mut out = Vec::with_capacity(lexemes.len()); + for (i, l) in lexemes.iter().enumerate() { + let kind = match l.kind { + Kind::Comment => Highlight::Comment, + Kind::DocComment => Highlight::DocComment, + Kind::Str => Highlight::String, + Kind::Number => Highlight::Number, + Kind::Op => Highlight::Operator, + Kind::Punct => Highlight::Punctuation, + Kind::Ident => { + let word = l.text(text); + let prev = prev_code(&lexemes, i).map(|p| p.text(text)); + let next = next_code(&lexemes, i).map(|n| n.text(text)); + if prev == Some(".") { + if next == Some("(") { Highlight::FunctionCall } else { Highlight::Property } + } else if ATOMS.contains(&word) { + Highlight::Atom + } else if KEYWORDS.contains(&word) { + Highlight::Keyword + } else if is_elementary_type(word) { + Highlight::Type + } else if matches!(prev, Some("function" | "modifier" | "event" | "error")) { + Highlight::Function + } else if matches!(prev, Some("contract" | "interface" | "library" | "struct" | "enum" | "is" | "new")) + { + Highlight::Type + } else if BUILTINS.contains(&word) { + Highlight::Builtin + } else if next == Some("(") { + Highlight::FunctionCall + } else if word.starts_with(|c: char| c.is_ascii_uppercase()) { + if word.len() > 1 && word.bytes().all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_') + { + Highlight::Constant + } else { + Highlight::Type + } + } else { + continue; + } + } + }; + out.push(Token { range: l.start..l.end, kind }); + } + out +} + +// --- structure ------------------------------------------------------------------ + +/// An open `{`: the symbol whose body it is, and what may be declared inside. +struct Frame { + symbol: Option, + body: Body, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Body { + File, + Contract, + Struct, + Enum, + Code, +} + +const MEMBER_MODIFIERS: &[&str] = + &["public", "private", "internal", "external", "constant", "immutable", "override", "transient", "payable"]; + +fn outline(text: &str) -> Vec { + let code: Vec = lex(text).into_iter().filter(|l| !l.is_trivia()).collect(); + let word = |i: usize| code.get(i).map_or("", |l| l.text(text)); + let mut symbols: Vec = Vec::new(); + let mut frames = vec![Frame { symbol: None, body: Body::File }]; + // A declaration waiting for its body (`{`) or its end (`;`). + let mut pending: Option<(usize, Body)> = None; + let mut stmt_start = 0usize; + let mut i = 0; + while i < code.len() { + let l = code[i]; + let w = l.text(text); + let body = frames.last().map_or(Body::File, |f| f.body); + let parent = frames.iter().rev().find_map(|f| f.symbol); + let add = |symbols: &mut Vec, name_at: usize, kind: SymbolKind, detail: Option<&str>| { + let name = code[name_at]; + symbols.push(Symbol { + name: name.text(text).to_owned(), + detail: detail.map(str::to_owned), + kind, + range: l.start..name.end, + name_range: name.start..name.end, + parent, + }); + symbols.len() - 1 + }; + let declares = matches!(body, Body::File | Body::Contract) && pending.is_none(); + match (l.kind, w) { + (Kind::Punct, "{") => { + let (symbol, inner) = match pending.take() { + Some((s, b)) => (Some(s), b), + None => (None, if body == Body::Code || body == Body::Contract { Body::Code } else { body }), + }; + frames.push(Frame { symbol, body: inner }); + stmt_start = i + 1; + } + (Kind::Punct, "}") => { + if frames.len() > 1 + && let Some(frame) = frames.pop() + && let Some(s) = frame.symbol + { + symbols[s].range.end = l.end; + } + stmt_start = i + 1; + } + (Kind::Punct, ";") => { + if let Some((s, _)) = pending.take() { + symbols[s].range.end = l.end; + } else if matches!(body, Body::Contract | Body::Struct | Body::File) && stmt_start < i { + // `Type [modifiers] name [= value];`: a state variable, struct member or file constant. + let stmt = &code[stmt_start..i]; + let head = stmt[0].text(text); + let skip = matches!(head, "using" | "import" | "pragma" | "return" | "emit" | "type"); + let until = stmt.iter().position(|s| s.text(text) == "=").unwrap_or(stmt.len()); + let name = stmt[..until].iter().rposition(|s| { + s.kind == Kind::Ident + && !MEMBER_MODIFIERS.contains(&s.text(text)) + && !is_elementary_type(s.text(text)) + }); + if let (false, Some(n)) = (skip, name) + && n > 0 + { + let constant = stmt[..until].iter().any(|s| matches!(s.text(text), "constant" | "immutable")); + let kind = if constant { SymbolKind::Constant } else { SymbolKind::Field }; + if body != Body::File || constant { + let at = stmt_start + n; + let name = code[at]; + symbols.push(Symbol { + name: name.text(text).to_owned(), + detail: None, + kind, + range: code[stmt_start].start..l.end, + name_range: name.start..name.end, + parent, + }); + } + } + } + stmt_start = i + 1; + } + (Kind::Ident, "contract" | "interface" | "library") if declares && !word(i + 1).is_empty() => { + if code.get(i + 1).is_some_and(|n| n.kind == Kind::Ident) { + let kind = match w { + "interface" => SymbolKind::Interface, + "library" => SymbolKind::Module, + _ => SymbolKind::Class, + }; + let abstract_ = i > 0 && word(i - 1) == "abstract"; + let s = add(&mut symbols, i + 1, kind, abstract_.then_some("abstract")); + if abstract_ { + symbols[s].range.start = code[i - 1].start; + } + pending = Some((s, Body::Contract)); + i += 1; + } + } + (Kind::Ident, "function" | "modifier" | "event" | "error") if declares => { + if code.get(i + 1).is_some_and(|n| n.kind == Kind::Ident) { + let (kind, detail) = match w { + "function" if body == Body::Contract => (SymbolKind::Method, None), + "function" => (SymbolKind::Function, None), + "modifier" => (SymbolKind::Method, Some("modifier")), + "event" => (SymbolKind::Event, None), + _ => (SymbolKind::Event, Some("error")), + }; + let s = add(&mut symbols, i + 1, kind, detail); + pending = Some((s, Body::Code)); + i += 1; + } + } + (Kind::Ident, "constructor" | "fallback" | "receive") if declares && word(i + 1) == "(" => { + let kind = if w == "constructor" { SymbolKind::Constructor } else { SymbolKind::Method }; + let s = add(&mut symbols, i, kind, None); + pending = Some((s, Body::Code)); + } + (Kind::Ident, "struct" | "enum") if declares => { + if code.get(i + 1).is_some_and(|n| n.kind == Kind::Ident) { + let (kind, inner) = + if w == "struct" { (SymbolKind::Struct, Body::Struct) } else { (SymbolKind::Enum, Body::Enum) }; + let s = add(&mut symbols, i + 1, kind, None); + pending = Some((s, inner)); + i += 1; + } + } + (Kind::Ident, "type") if declares && word(i + 2) == "is" => { + let s = add(&mut symbols, i + 1, SymbolKind::TypeAlias, None); + pending = Some((s, Body::Code)); + i += 1; + } + (Kind::Ident, _) if body == Body::Enum && matches!(word(i + 1), "," | "}") => { + symbols.push(Symbol { + name: w.to_owned(), + detail: None, + kind: SymbolKind::EnumMember, + range: l.start..l.end, + name_range: l.start..l.end, + parent, + }); + } + _ => {} + } + i += 1; + } + symbols +} + +// --- folding ----------------------------------------------------------------------- + +fn folding(text: &str) -> Vec { + let lexemes = lex(text); + let line_of = |offset: usize| text[..offset].bytes().filter(|&b| b == b'\n').count() as u32; + let skip: Vec> = lexemes + .iter() + .filter(|l| matches!(l.kind, Kind::Str | Kind::Comment | Kind::DocComment)) + .map(|l| l.start..l.end) + .collect(); + let mut folds = bracket_folds(text, b'{', b'}', &skip); + for l in lexemes.iter().filter(|l| l.is_trivia()) { + let (start, end) = (line_of(l.start), line_of(l.end)); + if end > start { + folds.push(Fold { start_line: start, end_line: end, kind: FoldKind::Comment }); + } + } + // Consecutive `import` lines. + let mut run: Option<(u32, u32)> = None; + let flush = |run: &mut Option<(u32, u32)>, folds: &mut Vec| { + if let Some((s, e)) = run.take() + && e > s + { + folds.push(Fold { start_line: s, end_line: e, kind: FoldKind::Imports }); + } + }; + for (n, line) in text.lines().enumerate() { + let n = n as u32; + let t = line.trim_start(); + if t.starts_with("import ") || t.starts_with("import{") { + run = Some(run.map_or((n, n), |(s, _)| (s, n))); + } else if !t.is_empty() { + flush(&mut run, &mut folds); + } + } + flush(&mut run, &mut folds); + folds +} + +#[cfg(test)] +mod tests { + use super::*; + + const SAMPLE: &str = r#"// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +import "./IERC20.sol"; +import {Ownable} from "./Ownable.sol"; + +/// @title A token +abstract contract Token is IERC20, Ownable { + uint256 public constant MAX_SUPPLY = 1_000_000e18; + mapping(address => uint256) private balances; + string name = "tök"; + + enum State { Idle, Running } + struct Holder { + address who; + uint96 amount; + } + + event Transfer(address indexed from, address indexed to, uint256 value); + error Insufficient(uint256 needed); + + modifier onlyHolder() { + require(balances[msg.sender] > 0, "no"); + _; + } + + constructor(string memory n) { + name = n; + } + + function transfer(address to, uint256 value) external returns (bool) { + /* multi + line */ + if (balances[msg.sender] < value) revert Insufficient(value); + emit Transfer(msg.sender, to, value); + return true; + } + + function total() public view virtual returns (uint256); +} + +interface IThing { + function thing() external; +} + +function free(uint x) pure returns (uint) { return x; } +"#; + + fn names(symbols: &[Symbol], parent: Option) -> Vec<(&str, SymbolKind)> { + symbols.iter().filter(|s| s.parent == parent).map(|s| (s.name.as_str(), s.kind)).collect() + } + + #[test] + fn outline_lists_declarations_with_their_members() { + let symbols = outline(SAMPLE); + let top = names(&symbols, None); + assert_eq!( + top, + [("Token", SymbolKind::Class), ("IThing", SymbolKind::Interface), ("free", SymbolKind::Function)] + ); + let token = symbols.iter().position(|s| s.name == "Token").unwrap(); + assert_eq!(symbols[token].detail.as_deref(), Some("abstract")); + assert!(SAMPLE[symbols[token].range.clone()].starts_with("abstract contract Token")); + assert!(SAMPLE[symbols[token].range.clone()].ends_with('}')); + assert_eq!( + names(&symbols, Some(token)), + [ + ("MAX_SUPPLY", SymbolKind::Constant), + ("balances", SymbolKind::Field), + ("name", SymbolKind::Field), + ("State", SymbolKind::Enum), + ("Holder", SymbolKind::Struct), + ("Transfer", SymbolKind::Event), + ("Insufficient", SymbolKind::Event), + ("onlyHolder", SymbolKind::Method), + ("constructor", SymbolKind::Constructor), + ("transfer", SymbolKind::Method), + ("total", SymbolKind::Method), + ] + ); + let state = symbols.iter().position(|s| s.name == "State").unwrap(); + assert_eq!( + names(&symbols, Some(state)), + [("Idle", SymbolKind::EnumMember), ("Running", SymbolKind::EnumMember)] + ); + let holder = symbols.iter().position(|s| s.name == "Holder").unwrap(); + assert_eq!(names(&symbols, Some(holder)), [("who", SymbolKind::Field), ("amount", SymbolKind::Field)]); + let total = symbols.iter().find(|s| s.name == "total").unwrap(); + assert!(SAMPLE[total.range.clone()].ends_with("returns (uint256);")); + // Parents come first. + assert!(symbols.iter().enumerate().all(|(i, s)| s.parent.is_none_or(|p| p < i))); + } + + #[test] + fn highlights_classify_tokens() { + let tokens = highlights(SAMPLE); + let kind_of = |needle: &str| { + let at = SAMPLE.find(needle).unwrap(); + tokens.iter().find(|t| t.range.start == at).map(|t| t.kind) + }; + assert_eq!(kind_of("// SPDX"), Some(Highlight::Comment)); + assert_eq!(kind_of("/// @title"), Some(Highlight::DocComment)); + assert_eq!(kind_of("pragma"), Some(Highlight::Keyword)); + assert_eq!(kind_of("uint256 public"), Some(Highlight::Type)); + assert_eq!(kind_of("MAX_SUPPLY"), Some(Highlight::Constant)); + assert_eq!(kind_of("1_000_000e18"), Some(Highlight::Number)); + assert_eq!(kind_of("\"tök\""), Some(Highlight::String)); + assert_eq!(kind_of("Transfer(address"), Some(Highlight::Function)); + assert_eq!(kind_of("require("), Some(Highlight::Builtin)); + assert_eq!(kind_of("sender]"), Some(Highlight::Property)); + assert_eq!(kind_of("true;"), Some(Highlight::Atom)); + assert_eq!(kind_of("IERC20, Ownable"), Some(Highlight::Type)); + // Sorted and non-overlapping, on char boundaries. + assert!(tokens.windows(2).all(|w| w[0].range.end <= w[1].range.start)); + assert!(tokens.iter().all(|t| SAMPLE.is_char_boundary(t.range.start) && SAMPLE.is_char_boundary(t.range.end))); + } + + #[test] + fn folds_bodies_comments_and_imports() { + let folds = folding(SAMPLE); + let line = |needle: &str| SAMPLE[..SAMPLE.find(needle).unwrap()].matches('\n').count() as u32; + assert!(folds.contains(&Fold { start_line: 3, end_line: 4, kind: FoldKind::Imports })); + assert!(folds.iter().any(|f| f.kind == FoldKind::Comment && f.start_line == line("/* multi"))); + let contract = line("abstract contract"); + assert!(folds.iter().any(|f| f.kind == FoldKind::Region && f.start_line == contract)); + } + + #[test] + fn lexer_survives_unterminated_input() { + for text in ["\"abc", "/* open", "0x", "a.", "uint256 x = 1e", "é∑ unknown"] { + let _ = highlights(text); + let _ = outline(text); + let _ = folding(text); + } + } +} diff --git a/plugins/official/string-tools/.gitignore b/plugins/official/string-tools/.gitignore new file mode 100644 index 00000000..ea8c4bf7 --- /dev/null +++ b/plugins/official/string-tools/.gitignore @@ -0,0 +1 @@ +/target diff --git a/plugins/official/string-tools/Cargo.lock b/plugins/official/string-tools/Cargo.lock new file mode 100644 index 00000000..8f0807fe --- /dev/null +++ b/plugins/official/string-tools/Cargo.lock @@ -0,0 +1,333 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "openidea-plugin-openidea-string-tools" +version = "0.1.0" +dependencies = [ + "openidea-plugin", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[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 = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +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 = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/plugins/official/string-tools/Cargo.toml b/plugins/official/string-tools/Cargo.toml new file mode 100644 index 00000000..559b812e --- /dev/null +++ b/plugins/official/string-tools/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "openidea-plugin-openidea-string-tools" +version = "0.1.0" +edition = "2024" +publish = false + +# A plugin builds on its own (target wasm32-wasip2), outside any IDE workspace. +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../sdk/rust/openidea-plugin" } + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/plugins/official/string-tools/dist/plugin.wasm b/plugins/official/string-tools/dist/plugin.wasm new file mode 100644 index 00000000..1c33e3e4 Binary files /dev/null and b/plugins/official/string-tools/dist/plugin.wasm differ diff --git a/plugins/official/string-tools/dist/plugin.wasm.sources b/plugins/official/string-tools/dist/plugin.wasm.sources new file mode 100644 index 00000000..2dbf488f --- /dev/null +++ b/plugins/official/string-tools/dist/plugin.wasm.sources @@ -0,0 +1 @@ +a88c39d5782369329efa55b12330daa906e5c8d91252bd57c7343648840bac79 diff --git a/plugins/official/string-tools/plugin.toml b/plugins/official/string-tools/plugin.toml new file mode 100644 index 00000000..18ff2bb5 --- /dev/null +++ b/plugins/official/string-tools/plugin.toml @@ -0,0 +1,171 @@ +id = "openidea.string-tools" +name = "String Tools" +version = "0.1.0" +description = "Case conversion (camelCase, snake_case, kebab-case…), encoding (Base64, URL, HTML, JSON), line sorting and more, on every selection at once." +authors = ["OpenIDEA contributors"] +license = "Apache-2.0" +change-notes = "0.1.0 — first release: 26 commands in four groups." +engines.openidea = "^1.0" +wasm = "dist/plugin.wasm" +# The commands are declared below, so Find Action and the keymap list them +# before the code is ever loaded; it loads on the first one run. +activation = ["on-command:*"] + +[capabilities] +required = ["editor.read", "editor.write"] + +[[contributes.commands]] +id = "camel-case" +title = "String Tools: To camelCase" +category = "String Tools › Case" +when = "editorFocus" + +[[contributes.commands]] +id = "pascal-case" +title = "String Tools: To PascalCase" +category = "String Tools › Case" +when = "editorFocus" + +[[contributes.commands]] +id = "snake-case" +title = "String Tools: To snake_case" +category = "String Tools › Case" +when = "editorFocus" + +[[contributes.commands]] +id = "screaming-snake-case" +title = "String Tools: To SCREAMING_SNAKE_CASE" +category = "String Tools › Case" +when = "editorFocus" + +[[contributes.commands]] +id = "kebab-case" +title = "String Tools: To kebab-case" +category = "String Tools › Case" +when = "editorFocus" + +[[contributes.commands]] +id = "dot-case" +title = "String Tools: To dot.case" +category = "String Tools › Case" +when = "editorFocus" + +[[contributes.commands]] +id = "title-case" +title = "String Tools: To Title Case" +category = "String Tools › Case" +when = "editorFocus" + +[[contributes.commands]] +id = "upper-case" +title = "String Tools: To UPPER CASE" +category = "String Tools › Case" +when = "editorFocus" + +[[contributes.commands]] +id = "lower-case" +title = "String Tools: To lower case" +category = "String Tools › Case" +when = "editorFocus" + +[[contributes.commands]] +id = "toggle-case" +title = "String Tools: Toggle Case" +category = "String Tools › Case" +when = "editorFocus" + +[[contributes.commands]] +id = "base64-encode" +title = "String Tools: Encode Base64" +category = "String Tools › Encode" +when = "editorFocus" + +[[contributes.commands]] +id = "base64-decode" +title = "String Tools: Decode Base64" +category = "String Tools › Encode" +when = "editorFocus" + +[[contributes.commands]] +id = "url-encode" +title = "String Tools: URL-Encode" +category = "String Tools › Encode" +when = "editorFocus" + +[[contributes.commands]] +id = "url-decode" +title = "String Tools: URL-Decode" +category = "String Tools › Encode" +when = "editorFocus" + +[[contributes.commands]] +id = "html-escape" +title = "String Tools: Escape HTML" +category = "String Tools › Encode" +when = "editorFocus" + +[[contributes.commands]] +id = "html-unescape" +title = "String Tools: Unescape HTML" +category = "String Tools › Encode" +when = "editorFocus" + +[[contributes.commands]] +id = "json-escape" +title = "String Tools: Escape as JSON String" +category = "String Tools › Encode" +when = "editorFocus" + +[[contributes.commands]] +id = "sort-lines" +title = "String Tools: Sort Lines" +category = "String Tools › Lines" +when = "editorFocus" + +[[contributes.commands]] +id = "sort-lines-desc" +title = "String Tools: Sort Lines Descending" +category = "String Tools › Lines" +when = "editorFocus" + +[[contributes.commands]] +id = "reverse-lines" +title = "String Tools: Reverse Lines" +category = "String Tools › Lines" +when = "editorFocus" + +[[contributes.commands]] +id = "unique-lines" +title = "String Tools: Remove Duplicate Lines" +category = "String Tools › Lines" +when = "editorFocus" + +[[contributes.commands]] +id = "trim-lines" +title = "String Tools: Trim Lines" +category = "String Tools › Lines" +when = "editorFocus" + +[[contributes.commands]] +id = "reverse" +title = "String Tools: Reverse Text" +category = "String Tools › Other" +when = "editorFocus" + +[[contributes.commands]] +id = "swap-quotes" +title = "String Tools: Swap Quotes (' ↔ \")" +category = "String Tools › Other" +when = "editorFocus" + +[[contributes.commands]] +id = "increment" +title = "String Tools: Increment Numbers" +category = "String Tools › Other" +when = "editorFocus" + +[[contributes.commands]] +id = "decrement" +title = "String Tools: Decrement Numbers" +category = "String Tools › Other" +when = "editorFocus" diff --git a/plugins/official/string-tools/src/lib.rs b/plugins/official/string-tools/src/lib.rs new file mode 100644 index 00000000..805b78eb --- /dev/null +++ b/plugins/official/string-tools/src/lib.rs @@ -0,0 +1,460 @@ +//! String Tools for OpenIDEA: text transformations on every selection of the +//! focused editor, applied as one undoable change. An empty selection +//! (a cursor) works on the word under it; line commands on whole lines. + +use openidea_plugin::text::{offset, position}; +use openidea_plugin::{Error, Invocation, Plugin, Range, TextEdit, TextEditor, register_plugin}; + +#[derive(Default)] +pub struct StringTools; + +impl Plugin for StringTools { + fn run_command(&mut self, id: &str, ctx: &Invocation, _arg: Option<&str>) -> Result, Error> { + let transform = transform(id).ok_or_else(|| Error::NotFound(format!("command {id}")))?; + let editor = ctx.editor().ok_or("String Tools works on the focused editor")?; + apply(&editor, transform, lines_command(id))?; + Ok(None) + } +} + +register_plugin!(StringTools); + +type Transform = fn(&str) -> String; + +fn lines_command(id: &str) -> bool { + matches!(id, "sort-lines" | "sort-lines-desc" | "reverse-lines" | "unique-lines" | "trim-lines") +} + +fn transform(id: &str) -> Option { + Some(match id { + "camel-case" => |s| join_words(s, Style::Camel), + "pascal-case" => |s| join_words(s, Style::Pascal), + "snake-case" => |s| join_words(s, Style::Snake), + "screaming-snake-case" => |s| join_words(s, Style::ScreamingSnake), + "kebab-case" => |s| join_words(s, Style::Kebab), + "dot-case" => |s| join_words(s, Style::Dot), + "title-case" => title_case, + "upper-case" => |s| s.to_uppercase(), + "lower-case" => |s| s.to_lowercase(), + "toggle-case" => toggle_case, + "base64-encode" => |s| base64_encode(s.as_bytes()), + "base64-decode" => { + |s| base64_decode(s).map_or_else(|| s.to_owned(), |b| String::from_utf8_lossy(&b).into_owned()) + } + "url-encode" => url_encode, + "url-decode" => url_decode, + "html-escape" => html_escape, + "html-unescape" => html_unescape, + "json-escape" => json_escape, + "sort-lines" => |s| map_lines(s, |l| l.sort()), + "sort-lines-desc" => |s| map_lines(s, |l| l.sort_by(|a, b| b.cmp(a))), + "reverse-lines" => |s| map_lines(s, |l| l.reverse()), + "unique-lines" => |s| { + map_lines(s, |l| { + let mut seen = std::collections::HashSet::new(); + l.retain(|x| seen.insert(x.to_owned())); + }) + }, + "trim-lines" => |s| s.split('\n').map(str::trim).collect::>().join("\n"), + "reverse" => |s| s.chars().rev().collect(), + "swap-quotes" => |s| { + s.chars() + .map(|c| match c { + '"' => '\'', + '\'' => '"', + c => c, + }) + .collect() + }, + "increment" => |s| step_numbers(s, 1), + "decrement" => |s| step_numbers(s, -1), + _ => return None, + }) +} + +/// Replaces each selection with `f(text)`: an empty one expands to the word +/// under the cursor, or (`lines`) every selection to its whole lines. +/// Retried once if the user typed meanwhile. +fn apply(editor: &TextEditor, f: Transform, lines: bool) -> Result { + let selections = editor.selections()?; + for _ in 0..2 { + let doc = editor.document()?; + let mut edits = Vec::with_capacity(selections.len()); + for r in &selections { + let range = if lines { line_range(&doc.text, *r) } else { word_range(&doc.text, *r) }; + let Some(old) = doc.text_in(range) else { continue }; + let new = f(old); + if new != old { + edits.push(TextEdit { range, text: new }); + } + } + // Overlapping selections (two cursors in one word) edit once. + edits.sort_by_key(|e| e.range); + edits.dedup_by(|b, a| b.range.start < a.range.end); + match editor.apply_edits(doc.version, &edits) { + Err(Error::Stale) => continue, + other => return other, + } + } + Err(Error::Stale) +} + +fn word_range(text: &str, r: Range) -> Range { + if !r.is_empty() { + return r; + } + let Some(at) = offset(text, r.start) else { return r }; + let word = |c: char| c.is_alphanumeric() || c == '_' || c == '-' || c == '.'; + let start = text[..at].char_indices().rev().take_while(|(_, c)| word(*c)).last().map_or(at, |(i, _)| i); + let end = text[at..].char_indices().find(|(_, c)| !word(*c)).map_or(text.len(), |(i, _)| at + i); + Range::new(position(text, start), position(text, end)) +} + +fn line_range(text: &str, r: Range) -> Range { + let start = openidea_plugin::Position::new(r.start.line, 0); + let end_line = if r.end.character == 0 && r.end.line > r.start.line { r.end.line - 1 } else { r.end.line }; + let line_end = text.split('\n').nth(end_line as usize).map_or(0, |l| l.encode_utf16().count() as u32); + Range::new(start, openidea_plugin::Position::new(end_line, line_end)) +} + +#[derive(Clone, Copy)] +enum Style { + Camel, + Pascal, + Snake, + ScreamingSnake, + Kebab, + Dot, +} + +/// Splits identifiers on separators and case changes: `fooBar_baz-qux` → +/// [foo, Bar, baz, qux]; `HTTPServer` → [HTTP, Server]. +fn words(s: &str) -> Vec { + let chars: Vec = s.chars().collect(); + let mut out = Vec::new(); + let mut cur = String::new(); + for (i, &c) in chars.iter().enumerate() { + if !c.is_alphanumeric() { + if !cur.is_empty() { + out.push(std::mem::take(&mut cur)); + } + continue; + } + let prev = i.checked_sub(1).map(|j| chars[j]); + let next = chars.get(i + 1).copied(); + let boundary = c.is_uppercase() + && prev.is_some_and(|p| { + p.is_lowercase() || p.is_ascii_digit() || (p.is_uppercase() && next.is_some_and(char::is_lowercase)) + }); + if boundary && !cur.is_empty() { + out.push(std::mem::take(&mut cur)); + } + cur.push(c); + } + if !cur.is_empty() { + out.push(cur); + } + out +} + +fn capitalize(w: &str) -> String { + let mut c = w.chars(); + c.next().map(|f| f.to_uppercase().chain(c.flat_map(char::to_lowercase)).collect()).unwrap_or_default() +} + +fn join_words(s: &str, style: Style) -> String { + // Keep surrounding whitespace (a whole-line selection). + let lead = &s[..s.len() - s.trim_start().len()]; + let trail = &s[s.trim_end().len()..]; + let w = words(s); + let body = match style { + Style::Camel => { + w.iter().enumerate().map(|(i, x)| if i == 0 { x.to_lowercase() } else { capitalize(x) }).collect() + } + Style::Pascal => w.iter().map(|x| capitalize(x)).collect(), + Style::Snake => w.iter().map(|x| x.to_lowercase()).collect::>().join("_"), + Style::ScreamingSnake => w.iter().map(|x| x.to_uppercase()).collect::>().join("_"), + Style::Kebab => w.iter().map(|x| x.to_lowercase()).collect::>().join("-"), + Style::Dot => w.iter().map(|x| x.to_lowercase()).collect::>().join("."), + }; + if body.is_empty() { s.to_owned() } else { format!("{lead}{body}{trail}") } +} + +fn title_case(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut start = true; + for c in s.chars() { + if start && c.is_alphabetic() { + out.extend(c.to_uppercase()); + start = false; + } else { + out.extend(c.to_lowercase()); + start = c.is_whitespace(); + } + } + out +} + +fn toggle_case(s: &str) -> String { + s.chars() + .flat_map(|c| -> Box> { + if c.is_uppercase() { Box::new(c.to_lowercase()) } else { Box::new(c.to_uppercase()) } + }) + .collect() +} + +fn map_lines(s: &str, f: impl FnOnce(&mut Vec<&str>)) -> String { + let mut lines: Vec<&str> = s.split('\n').collect(); + f(&mut lines); + lines.join("\n") +} + +/// Adds `by` to every integer in `s` (keeping zero padding). +fn step_numbers(s: &str, by: i64) -> String { + let mut out = String::with_capacity(s.len()); + let chars: Vec = s.chars().collect(); + let mut i = 0; + while i < chars.len() { + if chars[i].is_ascii_digit() { + let start = i; + while i < chars.len() && chars[i].is_ascii_digit() { + i += 1; + } + let neg = start > 0 && chars[start - 1] == '-' && (start < 2 || !chars[start - 2].is_alphanumeric()); + let digits: String = chars[start..i].iter().collect(); + match digits.parse::() { + Ok(n) => { + let n = if neg { -n } else { n }; + let next = n.saturating_add(by); + if neg { + out.pop(); // the minus sign + } + let width = digits.len(); + let text = if next < 0 { format!("-{:0width$}", -next) } else { format!("{next:0width$}") }; + out.push_str(&text); + } + Err(_) => out.push_str(&digits), + } + } else { + out.push(chars[i]); + i += 1; + } + } + out +} + +const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +fn base64_encode(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let n = chunk.iter().enumerate().fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i)); + for i in 0..4 { + if i <= chunk.len() { + out.push(B64[(n >> (18 - 6 * i) & 63) as usize] as char); + } else { + out.push('='); + } + } + } + out +} + +fn base64_decode(s: &str) -> Option> { + let clean: Vec = s.bytes().filter(|b| !b.is_ascii_whitespace()).collect(); + let clean = clean.strip_suffix(b"==").or_else(|| clean.strip_suffix(b"=")).unwrap_or(&clean); + let mut out = Vec::with_capacity(clean.len() * 3 / 4); + for chunk in clean.chunks(4) { + if chunk.len() == 1 { + return None; + } + let mut n = 0u32; + for (i, b) in chunk.iter().enumerate() { + let v = B64.iter().position(|x| x == b).or(match b { + b'-' => Some(62), + b'_' => Some(63), + _ => None, + })?; + n |= (v as u32) << (18 - 6 * i); + } + for i in 0..chunk.len() - 1 { + out.push((n >> (16 - 8 * i)) as u8); + } + } + Some(out) +} + +fn url_encode(s: &str) -> String { + s.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(), + _ => format!("%{b:02X}"), + }) + .collect() +} + +fn url_decode(s: &str) -> String { + let bytes = s.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + let hex = |j: usize| bytes.get(j).and_then(|b| (*b as char).to_digit(16)); + match bytes[i] { + b'%' if hex(i + 1).is_some() && hex(i + 2).is_some() => { + out.push((hex(i + 1).unwrap() * 16 + hex(i + 2).unwrap()) as u8); + i += 3; + } + b'+' => { + out.push(b' '); + i += 1; + } + b => { + out.push(b); + i += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +fn html_escape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c => out.push(c), + } + } + out +} + +fn html_unescape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut rest = s; + while let Some(i) = rest.find('&') { + out.push_str(&rest[..i]); + rest = &rest[i..]; + let Some(end) = rest[..rest.len().min(12)].find(';') else { + out.push('&'); + rest = &rest[1..]; + continue; + }; + let entity = &rest[1..end]; + let decoded = match entity { + "amp" => Some('&'), + "lt" => Some('<'), + "gt" => Some('>'), + "quot" => Some('"'), + "apos" => Some('\''), + "nbsp" => Some('\u{a0}'), + e if e.starts_with("#x") || e.starts_with("#X") => { + u32::from_str_radix(&e[2..], 16).ok().and_then(char::from_u32) + } + e if e.starts_with('#') => e[1..].parse().ok().and_then(char::from_u32), + _ => None, + }; + match decoded { + Some(c) => { + out.push(c); + rest = &rest[end + 1..]; + } + None => { + out.push('&'); + rest = &rest[1..]; + } + } + } + out.push_str(rest); + out +} + +fn json_escape(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use openidea_plugin::mock::MockHost; + + #[test] + fn cases() { + let t = |id: &str, s: &str| transform(id).unwrap()(s); + assert_eq!(t("camel-case", "hello_world-again"), "helloWorldAgain"); + assert_eq!(t("pascal-case", "HTTPServer error"), "HttpServerError"); + assert_eq!(t("snake-case", "parseHTTPResponse2Fast"), "parse_http_response2_fast"); + assert_eq!(t("screaming-snake-case", "maxValue"), "MAX_VALUE"); + assert_eq!(t("kebab-case", " FooBar "), " foo-bar "); + assert_eq!(t("dot-case", "a_b"), "a.b"); + assert_eq!(t("title-case", "the QUICK fox"), "The Quick Fox"); + assert_eq!(t("toggle-case", "aBc"), "AbC"); + } + + #[test] + fn encodings_round_trip() { + for s in ["", "f", "fo", "foo", "héllo wörld ✓"] { + assert_eq!(base64_decode(&base64_encode(s.as_bytes())).unwrap(), s.as_bytes()); + assert_eq!(url_decode(&url_encode(s)), s); + assert_eq!(html_unescape(&html_escape(s)), s); + } + assert_eq!(base64_encode(b"Man"), "TWFu"); + assert_eq!(url_encode("a b&c"), "a%20b%26c"); + assert_eq!(html_unescape("<a> AB &bogus; &"), " AB &bogus; &"); + assert_eq!(json_escape("a\"b\n"), "a\\\"b\\n"); + } + + #[test] + fn lines_and_numbers() { + let t = |id: &str, s: &str| transform(id).unwrap()(s); + assert_eq!(t("sort-lines", "b\na\nc"), "a\nb\nc"); + assert_eq!(t("unique-lines", "a\nb\na"), "a\nb"); + assert_eq!(t("increment", "v1.09 and -1"), "v2.10 and 0"); + assert_eq!(t("decrement", "x0"), "x-1"); + } + + #[test] + fn every_selection_and_cursor_in_one_undoable_change() { + let host = MockHost::install(); + host.open_editor("/p/a.rs", "rust", "let fooBar = baz_qux;\n", &[(0, 6, 0, 6), (0, 13, 0, 20)]); + StringTools.run_command("snake-case", &host.invocation(), None).unwrap(); + assert_eq!(host.editor_text(), "let foo_bar = baz_qux;\n"); + assert_eq!(host.editor_version(), 2, "one change for both"); + // The editor sends the (moved) selections with the next command. + host.open_editor("/p/a.rs", "rust", &host.editor_text(), &[(0, 4, 0, 11), (0, 14, 0, 21)]); + StringTools.run_command("upper-case", &host.invocation(), None).unwrap(); + assert_eq!(host.editor_text(), "let FOO_BAR = BAZ_QUX;\n"); + } + + #[test] + fn line_commands_take_whole_lines() { + let host = MockHost::install(); + host.open_editor("/p/a.txt", "text", "c\nb\na\nz", &[(0, 0, 3, 0)]); + StringTools.run_command("sort-lines", &host.invocation(), None).unwrap(); + assert_eq!(host.editor_text(), "a\nb\nc\nz"); + } + + #[test] + fn degrades_without_write_access() { + let host = MockHost::install().with_capabilities(&["editor.read"]); + host.open_editor("/p/a.txt", "text", "abc", &[(0, 0, 0, 3)]); + let err = StringTools.run_command("upper-case", &host.invocation(), None).unwrap_err(); + assert_eq!(err, Error::Denied("editor.write".into())); + assert_eq!(host.editor_text(), "abc"); + } +} diff --git a/scripts/theme/theme.test.ts b/scripts/theme/theme.test.ts index 8224b5c4..bf533329 100644 --- a/scripts/theme/theme.test.ts +++ b/scripts/theme/theme.test.ts @@ -14,7 +14,8 @@ const read = (p: string) => readFileSync(p, "utf8"); const css = read("src/styles/tokens.css"); const groups = themeTokenGroups(css); const sets = tokenSets(groups); -const TEMPLATE = "templates/theme-plugin"; +// The official Harbor Night theme, where new themes start (`openidea-plugin new --template theme`). +const TEMPLATE = "plugins/official/harbor-night"; const themeSrc = read(`${TEMPLATE}/themes/harbor-night.theme.json`); const schemeSrc = read(`${TEMPLATE}/themes/harbor-night.scheme.json`); const theme = JSON.parse(stripJsonComments(themeSrc)) as { id: string; kind: string; tokens: Record }; @@ -47,7 +48,7 @@ describe("theme token reference", () => { describe("theme plugin template", () => { it("sets every UI token in the theme file and every editor token in the scheme file", () => { // A failure here means tokens.css gained (or lost) a themeable token: - // add it to templates/theme-plugin/themes/*.json, then run pnpm gen:theme-docs. + // add it to plugins/official/harbor-night/themes/*.json, then run pnpm gen:theme-docs. expect(sorted(Object.keys(theme.tokens))).toEqual(sorted(sets.ui)); expect(sorted(Object.keys(scheme.tokens))).toEqual(sorted(sets.scheme)); }); diff --git a/sdk/rust/openidea-plugin/Cargo.lock b/sdk/rust/openidea-plugin/Cargo.lock new file mode 100644 index 00000000..9629fb20 --- /dev/null +++ b/sdk/rust/openidea-plugin/Cargo.lock @@ -0,0 +1,327 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "wit-bindgen", + "wit-parser", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[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 = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +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 = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/sdk/rust/openidea-plugin/Cargo.toml b/sdk/rust/openidea-plugin/Cargo.toml new file mode 100644 index 00000000..3f36703f --- /dev/null +++ b/sdk/rust/openidea-plugin/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "openidea-plugin" +version = "0.1.0" +edition = "2024" +description = "SDK for OpenIDEA plugins: typed host API, plugin trait, and a mock host for `cargo test`" +license = "Apache-2.0" +publish = false + +# Standalone: plugins depend on it by path or version; not part of the IDE workspace. +[workspace] + +[lib] +path = "src/lib.rs" + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wit-bindgen = "0.63" + +[dev-dependencies] +# Reads the WIT in tests/wit_coverage.rs (the version wit-bindgen already uses). +wit-parser = "0.262" diff --git a/sdk/rust/openidea-plugin/src/host.rs b/sdk/rust/openidea-plugin/src/host.rs new file mode 100644 index 00000000..187c5f8b --- /dev/null +++ b/sdk/rust/openidea-plugin/src/host.rs @@ -0,0 +1,560 @@ +//! The IDE functions and handles a plugin may use. Gated ones need the +//! capability in `plugin.toml` (`[capabilities] required = [...]`) and the +//! user's grant; without it they return [`Error::Denied`]. + +use crate::types::*; + +#[cfg(target_arch = "wasm32")] +mod imp { + //! Calls through the `openidea:plugin@1.0.0` world. + use crate::bindings::openidea::plugin as wit; + use crate::types::*; + + pub type InvocationRef<'a> = &'a wit::invocation::Invocation; + pub type ProjectRes = wit::workspace::Project; + pub type EditorRes = wit::editor::TextEditor; + pub type TaskRes = wit::tasks::Task; + + pub fn error(e: wit::types::Error) -> Error { + use wit::types::Error as E; + match e { + E::Denied(c) => Error::Denied(c), + E::Stale => Error::Stale, + E::NotFound(m) => Error::NotFound(m), + E::Invalid(m) => Error::Invalid(m), + E::Cancelled => Error::Cancelled, + E::Failed(m) => Error::Failed(m), + } + } + + fn range_in(r: wit::types::Range) -> Range { + Range::new(Position::new(r.start.line, r.start.character), Position::new(r.end.line, r.end.character)) + } + + fn range_out(r: Range) -> wit::types::Range { + wit::types::Range { + start: wit::types::Position { line: r.start.line, character: r.start.character }, + end: wit::types::Position { line: r.end.line, character: r.end.character }, + } + } + + pub fn log(level: LogLevel, message: &str) { + use wit::types::LogLevel as L; + let level = match level { + LogLevel::Trace => L::Trace, + LogLevel::Debug => L::Debug, + LogLevel::Info => L::Info, + LogLevel::Warn => L::Warn, + LogLevel::Error => L::Error, + }; + wit::log::log(level, message) + } + + pub fn notify(level: NotificationLevel, title: &str, body: &str) { + use wit::types::NotificationLevel as N; + let level = match level { + NotificationLevel::Info => N::Info, + NotificationLevel::Warning => N::Warning, + NotificationLevel::Error => N::Error, + }; + wit::ui::show_notification(level, title, body) + } + + pub fn set_status_item(id: &str, item: &StatusItem) { + let item = wit::ui::StatusItem { + text: item.text.clone(), + tooltip: item.tooltip.clone(), + command: item.command.clone(), + }; + wit::ui::set_status_item(id, &item) + } + + pub fn remove_status_item(id: &str) { + wit::ui::remove_status_item(id) + } + + pub fn storage_get(key: &str) -> Result, Error> { + wit::storage::get(key).map_err(error) + } + + pub fn storage_set(key: &str, value: &str) -> Result<(), Error> { + wit::storage::set(key, value).map_err(error) + } + + pub fn storage_delete(key: &str) -> Result<(), Error> { + wit::storage::delete(key).map_err(error) + } + + pub fn storage_keys(prefix: &str) -> Result, Error> { + wit::storage::keys(prefix).map_err(error) + } + + pub fn projects() -> Result, Error> { + wit::workspace::projects().map_err(error) + } + + pub fn project_root(p: &ProjectRes) -> Result { + p.root().map_err(error) + } + + pub fn project_read(p: &ProjectRes, path: &str) -> Result { + p.read_file(path).map_err(error) + } + + pub fn invocation_project(i: InvocationRef<'_>) -> Option { + i.project() + } + + pub fn invocation_editor(i: InvocationRef<'_>) -> Option { + i.editor() + } + + pub fn editor_path(e: &EditorRes) -> String { + e.path() + } + + pub fn editor_language(e: &EditorRes) -> String { + e.language() + } + + pub fn editor_document(e: &EditorRes) -> Result { + e.document().map(|d| Document { version: d.version, text: d.text }).map_err(error) + } + + pub fn editor_selections(e: &EditorRes) -> Result, Error> { + e.selections().map(|s| s.into_iter().map(range_in).collect()).map_err(error) + } + + pub fn editor_apply(e: &EditorRes, version: u64, edits: &[TextEdit]) -> Result { + let edits: Vec = + edits.iter().map(|t| wit::types::TextEdit { range: range_out(t.range), text: t.text.clone() }).collect(); + e.apply_edits(version, &edits).map_err(error) + } + + pub fn vcs_status(p: &ProjectRes) -> Result, Error> { + wit::vcs::status(p) + .map(|s| { + s.map(|s| RepositoryStatus { + root: s.root, + branch: s.branch, + commit: s.commit, + upstream: s.upstream, + ahead: s.ahead, + behind: s.behind, + operation: s.operation, + changed_files: s.changed_files, + }) + }) + .map_err(error) + } + + pub fn vcs_fetch(p: &ProjectRes) -> Result<(), Error> { + wit::vcs::fetch(p).map_err(error) + } + + fn kind(k: EventKind) -> wit::events::EventKind { + use wit::events::EventKind as K; + match k { + EventKind::FileOpened => K::FileOpened, + EventKind::FileSaved => K::FileSaved, + EventKind::EditorFocused => K::EditorFocused, + EventKind::ActionPerformed => K::ActionPerformed, + EventKind::VcsChanged => K::VcsChanged, + EventKind::Scheduled => K::Scheduled, + } + } + + pub fn subscribe(k: EventKind) -> Result<(), Error> { + wit::events::subscribe(kind(k)).map_err(error) + } + + pub fn unsubscribe(k: EventKind) { + wit::events::unsubscribe(kind(k)) + } + + pub fn begin_task(title: &str, cancellable: bool) -> TaskRes { + wit::tasks::begin(title, cancellable) + } + + pub fn task_report(t: &TaskRes, done: u32, total: Option, message: Option<&str>) { + t.report(done, total, message) + } + + pub fn task_cancelled(t: &TaskRes) -> bool { + t.is_cancelled() + } + + pub fn project_find(p: &ProjectRes, glob: &str, limit: u32) -> Result, Error> { + p.find_files(glob, limit).map_err(error) + } + + pub fn publish_diagnostics(path: &str, items: &[Diagnostic]) -> Result<(), Error> { + use wit::diagnostics::{Diagnostic as D, Severity as S}; + let items: Vec = items + .iter() + .map(|d| D { + range: range_out(d.range), + severity: match d.severity { + Severity::Error => S::Error, + Severity::Warning => S::Warning, + Severity::Info => S::Info, + Severity::Hint => S::Hint, + }, + message: d.message.clone(), + code: d.code.clone(), + }) + .collect(); + wit::diagnostics::publish(path, &items).map_err(error) + } + + pub fn fetch(req: &HttpRequest) -> Result { + let r = wit::net::Request { + method: req.method.clone(), + url: req.url.clone(), + headers: req.headers.iter().map(|(n, v)| wit::net::Header { name: n.clone(), value: v.clone() }).collect(), + body: req.body.clone(), + timeout_ms: req.timeout_ms, + }; + wit::net::fetch(&r) + .map(|r| HttpResponse { + status: r.status, + headers: r.headers.into_iter().map(|h| (h.name, h.value)).collect(), + body: r.body, + }) + .map_err(error) + } + + pub fn secret_is_set(name: &str) -> bool { + wit::secrets::is_set(name) + } + + pub fn refresh_view(view: &str) { + wit::views::refresh(view) + } + + pub fn post_view_message(view: &str, message: &str) -> Result<(), Error> { + wit::views::post_message(view, message).map_err(error) + } + + pub fn open_terminal(title: &str, program: &str, args: &[String]) -> Result<(), Error> { + wit::views::open_terminal(title, program, args).map_err(error) + } + + pub fn setting(key: &str) -> Option { + wit::settings::get(key) + } + + pub fn run_process( + program: &str, + args: &[String], + cwd: Option<&ProjectRes>, + stdin: Option<&str>, + ) -> Result { + wit::process::run(program, args, cwd, stdin) + .map(|o| ProcessOutput { status: o.status, stdout: o.stdout, stderr: o.stderr }) + .map_err(error) + } + + pub fn range_from(r: wit::types::Range) -> Range { + range_in(r) + } + + pub fn range_to(r: Range) -> wit::types::Range { + range_out(r) + } + + pub fn event(e: wit::events::Event) -> Event { + use wit::events::{ActionSource as S, Event as E}; + match e { + E::FileOpened(p) => Event::FileOpened(p), + E::FileSaved(p) => Event::FileSaved(p), + E::EditorFocused(p) => Event::EditorFocused(p), + E::VcsChanged(p) => Event::VcsChanged(p), + E::Scheduled => Event::Scheduled, + E::ActionPerformed(a) => Event::ActionPerformed(ActionPerformed { + action: a.action, + title: a.title, + source: match a.source { + S::Keyboard => ActionSource::Keyboard, + S::Menu => ActionSource::Menu, + S::Toolbar => ActionSource::Toolbar, + S::ContextMenu => ActionSource::ContextMenu, + S::Search => ActionSource::Search, + S::Other => ActionSource::Other, + }, + shortcut: a.shortcut, + }), + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +use crate::mock::current as imp; + +/// Where a command or event batch comes from: the window's project and +/// focused editor. +pub struct Invocation<'a> { + inner: imp::InvocationRef<'a>, +} + +impl<'a> Invocation<'a> { + #[doc(hidden)] + pub fn __new(inner: imp::InvocationRef<'a>) -> Self { + Self { inner } + } + + /// The window's project. + pub fn project(&self) -> Option { + imp::invocation_project(self.inner).map(|inner| Project { inner }) + } + + /// The window's focused editor. + pub fn editor(&self) -> Option { + imp::invocation_editor(self.inner).map(|inner| TextEditor { inner }) + } +} + +/// A project open in the IDE. +pub struct Project { + inner: imp::ProjectRes, +} + +impl Project { + /// Absolute path of the root. Needs `project.read`. + pub fn root(&self) -> Result { + imp::project_root(&self.inner) + } + + /// Reads a UTF-8 file inside the project (absolute or root-relative); + /// unsaved editor contents win. Needs `project.read`. + pub fn read_file(&self, path: &str) -> Result { + imp::project_read(&self.inner, path) + } + + /// The repository containing the project (`None`: not under git). Needs `vcs.read`. + pub fn vcs_status(&self) -> Result, Error> { + imp::vcs_status(&self.inner) + } + + /// Fetches all remotes. Needs `vcs.write`; long-running, so call it in a [`Task`]. + pub fn vcs_fetch(&self) -> Result<(), Error> { + imp::vcs_fetch(&self.inner) + } + + /// Project files whose root-relative path matches `glob` (`**/*Mapper.xml`), + /// at most `limit`, as absolute paths; ignored files are skipped. Needs `project.read`. + pub fn find_files(&self, glob: &str, limit: u32) -> Result, Error> { + imp::project_find(&self.inner, glob, limit) + } + + /// Runs the approved `process:` in this project's root. + pub fn run_process(&self, program: &str, args: &[String], stdin: Option<&str>) -> Result { + imp::run_process(program, args, Some(&self.inner), stdin) + } +} + +/// Replaces the plugin's diagnostics for `path` (absolute, in an open +/// project); an empty slice clears them. Needs `project.read`. +pub fn publish_diagnostics(path: &str, items: &[Diagnostic]) -> Result<(), Error> { + imp::publish_diagnostics(path, items) +} + +/// HTTP(S) to a host granted with `net:` (plain http only to +/// localhost). `{{secret:}}` in a header is filled in by the IDE (needs +/// `secrets`). `Error::Cancelled` when the call was superseded. +pub fn fetch(request: &HttpRequest) -> Result { + imp::fetch(request) +} + +/// Whether the user stored secret `name` (declared under `[[contributes.secrets]]`). +pub fn secret_is_set(name: &str) -> bool { + imp::secret_is_set(name) +} + +/// The content of view (or custom editor) `view` changed: the IDE renders it again. +pub fn refresh_view(view: &str) { + imp::refresh_view(view) +} + +/// Sends `message` to the script of view `view`'s HTML body. +pub fn post_view_message(view: &str, message: &str) -> Result<(), Error> { + imp::post_view_message(view, message) +} + +/// Opens a terminal tab in the invoking window running the approved +/// `process:` in the project root: logs that keep coming, +/// interactive sessions (`kubectl exec -it …`). +pub fn open_terminal(title: &str, program: &str, args: &[String]) -> Result<(), Error> { + imp::open_terminal(title, program, args) +} + +/// One of the plugin's settings (`[contributes.settings]`) as JSON: the +/// user's value (project over global) or the schema's default. +pub fn setting(key: &str) -> Option { + imp::setting(key) +} + +/// A boolean setting. +pub fn setting_bool(key: &str) -> Option { + setting(key).and_then(|v| v.parse().ok()) +} + +/// A string setting. +pub fn setting_string(key: &str) -> Option { + let v = setting(key)?; + let inner = v.strip_prefix('"')?.strip_suffix('"')?; + Some(crate::text::unescape_json(inner)) +} + +/// A number setting. +pub fn setting_number(key: &str) -> Option { + setting(key).and_then(|v| v.parse().ok()) +} + +/// Runs the approved `process:` in the plugin's data directory +/// (see [`Project::run_process`] to run it in a project). +pub fn run_process(program: &str, args: &[String], stdin: Option<&str>) -> Result { + imp::run_process(program, args, None, stdin) +} + +/// Projects open in any window. Needs `project.read`. +pub fn projects() -> Result, Error> { + Ok(imp::projects()?.into_iter().map(|inner| Project { inner }).collect()) +} + +/// A file open in an editor. +pub struct TextEditor { + inner: imp::EditorRes, +} + +impl TextEditor { + pub fn path(&self) -> String { + imp::editor_path(&self.inner) + } + + pub fn language(&self) -> String { + imp::editor_language(&self.inner) + } + + /// Current version and text. Needs `editor.read`. + pub fn document(&self) -> Result { + imp::editor_document(&self.inner) + } + + /// Selections when the command was invoked. Needs `editor.read`. + pub fn selections(&self) -> Result, Error> { + imp::editor_selections(&self.inner) + } + + /// Applies `edits` (in `version`'s coordinates, not overlapping) as one + /// undoable change; [`Error::Stale`] if the document changed meanwhile. + /// Returns the new version. Needs `editor.write`. + pub fn apply_edits(&self, version: u64, edits: &[TextEdit]) -> Result { + imp::editor_apply(&self.inner, version, edits) + } + + /// Replaces every selection with `f(selected text)` in one undoable + /// change, retrying once if the user typed in between. Cursors get + /// `f("")` inserted. Needs `editor.read` and `editor.write`. + pub fn transform_selections(&self, mut f: impl FnMut(&str) -> String) -> Result { + let selections = self.selections()?; + let mut last = Error::Stale; + for _ in 0..2 { + let doc = self.document()?; + let mut edits = Vec::with_capacity(selections.len()); + for r in &selections { + let old = doc.text_in(*r).ok_or_else(|| Error::Invalid("selection outside the document".into()))?; + let new = f(old); + if new != old { + edits.push(TextEdit { range: *r, text: new }); + } + } + match self.apply_edits(doc.version, &edits) { + Err(Error::Stale) => last = Error::Stale, + other => return other, + } + } + Err(last) + } +} + +/// Long-running work shown in the status bar; dropping it ends it. While a +/// task is open, the current call may run for up to 60 s instead of 5 s. +pub struct Task { + inner: imp::TaskRes, +} + +impl Task { + /// `done` of `total` units (`None`: indeterminate), with a short status. + pub fn report(&self, done: u32, total: Option, message: Option<&str>) { + imp::task_report(&self.inner, done, total, message) + } + + /// The user cancelled it: stop soon and return. + pub fn is_cancelled(&self) -> bool { + imp::task_cancelled(&self.inner) + } +} + +/// Starts a task (see [`Task`]). +pub fn begin_task(title: &str, cancellable: bool) -> Task { + Task { inner: imp::begin_task(title, cancellable) } +} + +/// Writes to the IDE log, tagged with the plugin id. +pub fn log(level: LogLevel, message: &str) { + imp::log(level, message) +} + +/// Shows a notification balloon in the window the command or events came +/// from (every window when there is none). +pub fn notify(level: NotificationLevel, title: &str, body: &str) { + imp::notify(level, title, body) +} + +/// Shows or updates the plugin's status bar item `id` (at most 8). +pub fn set_status_item(id: &str, item: &StatusItem) { + imp::set_status_item(id, item) +} + +pub fn remove_status_item(id: &str) { + imp::remove_status_item(id) +} + +/// Delivers `kind` events to [`crate::Plugin::handle_events`] for the rest of +/// the session (also after the instance is reclaimed: an event activates the +/// plugin again). Needs `events` (`events.input` for `ActionPerformed`). +pub fn subscribe(kind: EventKind) -> Result<(), Error> { + imp::subscribe(kind) +} + +pub fn unsubscribe(kind: EventKind) { + imp::unsubscribe(kind) +} + +/// The plugin's persistent key-value store (≤ 1 MiB). Needs `storage`. +pub mod storage { + use super::imp; + use crate::types::Error; + + pub fn get(key: &str) -> Result, Error> { + imp::storage_get(key) + } + + pub fn set(key: &str, value: &str) -> Result<(), Error> { + imp::storage_set(key, value) + } + + pub fn delete(key: &str) -> Result<(), Error> { + imp::storage_delete(key) + } + + /// Keys starting with `prefix`, sorted. + pub fn keys(prefix: &str) -> Result, Error> { + imp::storage_keys(prefix) + } +} + +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] +pub use imp::{event as __event, range_from as __range_from, range_to as __range_to}; diff --git a/sdk/rust/openidea-plugin/src/lib.rs b/sdk/rust/openidea-plugin/src/lib.rs new file mode 100644 index 00000000..f59d728c --- /dev/null +++ b/sdk/rust/openidea-plugin/src/lib.rs @@ -0,0 +1,637 @@ +//! SDK for OpenIDEA plugins written in Rust (plugin API 1.0). +//! +//! ```ignore +//! use openidea_plugin::{Error, Invocation, Plugin, register_plugin}; +//! +//! #[derive(Default)] +//! struct Shout; +//! +//! impl Plugin for Shout { +//! fn run_command(&mut self, id: &str, ctx: &Invocation, _arg: Option<&str>) -> Result, Error> { +//! match id { +//! "shout" => { +//! let editor = ctx.editor().ok_or("no editor is focused")?; +//! editor.transform_selections(|s| s.to_uppercase())?; +//! Ok(None) +//! } +//! _ => Err(Error::NotFound(format!("command {id}"))), +//! } +//! } +//! } +//! +//! register_plugin!(Shout); +//! ``` +//! +//! On `wasm32-wasip2` the [`host`] functions and handles call the IDE through +//! the `openidea:plugin@1.0.0` WIT world. On any other target they call the +//! [`mock`] host, so plugin logic is tested with plain `cargo test`: +//! +//! ```ignore +//! let host = openidea_plugin::mock::MockHost::install(); +//! host.open_editor("/project/a.txt", "rust", "hi there", &[(0, 0, 0, 2)]); +//! Shout.run_command("shout", &host.invocation(), None).unwrap(); +//! assert_eq!(host.editor_text(), "HI there"); +//! ``` +//! +//! Instance memory is a cache: the instance is dropped after a crash or when +//! idle. Keep what must survive in [`host::storage`]. +//! +//! Build with `openidea-plugin build` (or `cargo build --release --target +//! wasm32-wasip2`); see `plugins/README.md`. + +pub mod host; +#[cfg(not(target_arch = "wasm32"))] +pub mod mock; +pub mod providers; +pub mod syntax; +pub mod text; +mod types; +pub mod views; + +pub use host::{Invocation, Project, Task, TextEditor}; +pub use types::*; + +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] +pub mod bindings { + wit_bindgen::generate!({ + world: "plugin", + path: "wit", + pub_export_macro: true, + export_macro_name: "__export_plugin_world", + default_bindings_module: "openidea_plugin::bindings", + }); +} + +/// The `syntax` world: only the `syntax-provider` export, merged with +/// `plugin` into one component (world `plugin-syntax`). +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] +pub mod syntax_bindings { + wit_bindgen::generate!({ + world: "syntax", + path: "wit", + pub_export_macro: true, + export_macro_name: "__export_syntax_world", + default_bindings_module: "openidea_plugin::syntax_bindings", + }); +} + +/// The `editor-providers` world: only the `providers` export, merged with +/// `plugin` (world `plugin-providers`). +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] +pub mod providers_bindings { + wit_bindgen::generate!({ + world: "editor-providers", + path: "wit", + pub_export_macro: true, + export_macro_name: "__export_editor_providers_world", + default_bindings_module: "openidea_plugin::providers_bindings", + with: { + "openidea:plugin/types@1.0.0": crate::bindings::openidea::plugin::types, + }, + }); +} + +/// The `views-provider` world: only the `view-provider` export, merged with +/// `plugin` (world `plugin-views`). +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] +pub mod views_bindings { + wit_bindgen::generate!({ + world: "views-provider", + path: "wit", + pub_export_macro: true, + export_macro_name: "__export_views_world", + default_bindings_module: "openidea_plugin::views_bindings", + with: { + "openidea:plugin/types@1.0.0": crate::bindings::openidea::plugin::types, + "openidea:plugin/workspace@1.0.0": crate::bindings::openidea::plugin::workspace, + "openidea:plugin/editor@1.0.0": crate::bindings::openidea::plugin::editor, + "openidea:plugin/invocation@1.0.0": crate::bindings::openidea::plugin::invocation, + }, + }); +} + +/// The plugin API version this SDK targets. +pub const API_VERSION: &str = "1.0"; + +/// A plugin. One instance lives as long as the plugin's Wasm instance (until +/// it is disabled, crashes or is reclaimed when idle). +pub trait Plugin: 'static { + /// Called once when the instance is created: subscribe to events and + /// restore state from [`host::storage`]. An error fails the activation. + fn activate(&mut self, _ctx: &Context) -> Result<(), Error> { + Ok(()) + } + + /// Called before the instance is dropped. + fn deactivate(&mut self) {} + + /// Runs one of the plugin's commands; `Ok(Some(text))` is shown to the user. + /// A plain message (`Err("…".into())`, or `?` on a `String` error) is + /// [`Error::Failed`]; return [`Error::Cancelled`] when the user gave up. + fn run_command(&mut self, id: &str, ctx: &Invocation, arg: Option<&str>) -> Result, Error>; + + /// A batch of subscribed events (see [`host::subscribe`]), oldest first. + fn handle_events(&mut self, _events: &[Event], _ctx: &Invocation) {} +} + +/// Exports `T` (a [`Plugin`] + `Default`) as the plugin's component. With +/// `syntax`, `T` is also a [`syntax::SyntaxProvider`] for its languages. +#[macro_export] +macro_rules! register_plugin { + ($plugin:ty) => { + // Natively (tests) nothing is exported; keep the type "used". + #[cfg(not(target_arch = "wasm32"))] + const _: fn() -> $plugin = <$plugin as ::core::default::Default>::default; + #[cfg(target_arch = "wasm32")] + const _: () = { + struct __OpenideaComponent; + $crate::__plugin_exports!($plugin, __OpenideaComponent, $crate::bindings); + $crate::bindings::__export_plugin_world!(__OpenideaComponent with_types_in $crate::bindings); + }; + }; + ($plugin:ty, providers) => { + #[cfg(not(target_arch = "wasm32"))] + const _: fn() -> $plugin = <$plugin as ::core::default::Default>::default; + #[cfg(target_arch = "wasm32")] + const _: () = { + struct __OpenideaComponent; + $crate::__plugin_exports!($plugin, __OpenideaComponent, $crate::bindings); + $crate::__providers_exports!($plugin, __OpenideaComponent); + $crate::bindings::__export_plugin_world!(__OpenideaComponent with_types_in $crate::bindings); + }; + }; + ($plugin:ty, views) => { + #[cfg(not(target_arch = "wasm32"))] + const _: fn() -> $plugin = <$plugin as ::core::default::Default>::default; + #[cfg(target_arch = "wasm32")] + const _: () = { + struct __OpenideaComponent; + $crate::__plugin_exports!($plugin, __OpenideaComponent, $crate::bindings); + $crate::__views_exports!($plugin, __OpenideaComponent); + $crate::bindings::__export_plugin_world!(__OpenideaComponent with_types_in $crate::bindings); + }; + }; + ($plugin:ty, providers, views) => { + #[cfg(not(target_arch = "wasm32"))] + const _: fn() -> $plugin = <$plugin as ::core::default::Default>::default; + #[cfg(target_arch = "wasm32")] + const _: () = { + struct __OpenideaComponent; + $crate::__plugin_exports!($plugin, __OpenideaComponent, $crate::bindings); + $crate::__providers_exports!($plugin, __OpenideaComponent); + $crate::__views_exports!($plugin, __OpenideaComponent); + $crate::bindings::__export_plugin_world!(__OpenideaComponent with_types_in $crate::bindings); + }; + }; + ($plugin:ty, syntax) => { + #[cfg(not(target_arch = "wasm32"))] + const _: fn() -> $plugin = <$plugin as ::core::default::Default>::default; + #[cfg(target_arch = "wasm32")] + const _: () = { + struct __OpenideaComponent; + $crate::__plugin_exports!($plugin, __OpenideaComponent, $crate::bindings); + + impl $crate::syntax_bindings::exports::openidea::plugin::syntax_provider::Guest for __OpenideaComponent { + fn highlights( + language: ::std::string::String, + text: ::std::string::String, + ) -> ::std::vec::Vec<$crate::syntax_bindings::exports::openidea::plugin::syntax_provider::Token> + { + $crate::__rt::highlights::<$plugin>(&language, &text) + } + + fn outline( + language: ::std::string::String, + text: ::std::string::String, + ) -> ::std::vec::Vec<$crate::syntax_bindings::exports::openidea::plugin::syntax_provider::Symbol> + { + $crate::__rt::outline::<$plugin>(&language, &text) + } + + fn folding( + language: ::std::string::String, + text: ::std::string::String, + ) -> ::std::vec::Vec<$crate::syntax_bindings::exports::openidea::plugin::syntax_provider::Fold> + { + $crate::__rt::folding::<$plugin>(&language, &text) + } + } + + $crate::bindings::__export_plugin_world!(__OpenideaComponent with_types_in $crate::bindings); + $crate::syntax_bindings::__export_syntax_world!(__OpenideaComponent with_types_in $crate::syntax_bindings); + }; + }; +} + +/// `register_plugin!(T, providers)`: `T` is also a [`providers::Providers`]. +#[doc(hidden)] +#[macro_export] +macro_rules! __providers_exports { + ($plugin:ty, $component:ident) => { + impl $crate::providers_bindings::exports::openidea::plugin::providers::Guest for $component { + fn completion( + doc: $crate::providers_bindings::exports::openidea::plugin::providers::Document, + at: $crate::bindings::openidea::plugin::types::Position, + trigger: ::core::option::Option<::std::string::String>, + ) -> ::std::vec::Vec<$crate::providers_bindings::exports::openidea::plugin::providers::CompletionItem> { + $crate::__rt::completion::<$plugin>(doc, at, trigger) + } + + fn inline_completion( + doc: $crate::providers_bindings::exports::openidea::plugin::providers::Document, + at: $crate::bindings::openidea::plugin::types::Position, + ) -> ::core::option::Option<$crate::providers_bindings::exports::openidea::plugin::providers::InlineSuggestion> { + $crate::__rt::inline_completion::<$plugin>(doc, at) + } + + fn code_actions( + doc: $crate::providers_bindings::exports::openidea::plugin::providers::Document, + selection: $crate::bindings::openidea::plugin::types::Range, + ) -> ::std::vec::Vec<$crate::providers_bindings::exports::openidea::plugin::providers::CodeAction> { + $crate::__rt::code_actions::<$plugin>(doc, selection) + } + + fn definition( + doc: $crate::providers_bindings::exports::openidea::plugin::providers::Document, + at: $crate::bindings::openidea::plugin::types::Position, + ) -> ::std::vec::Vec<$crate::bindings::openidea::plugin::types::Location> { + $crate::__rt::definition::<$plugin>(doc, at) + } + + fn line_markers( + doc: $crate::providers_bindings::exports::openidea::plugin::providers::Document, + ) -> ::std::vec::Vec<$crate::providers_bindings::exports::openidea::plugin::providers::LineMarker> { + $crate::__rt::line_markers::<$plugin>(doc) + } + } + + $crate::providers_bindings::__export_editor_providers_world!($component with_types_in $crate::providers_bindings); + }; +} + +/// `register_plugin!(T, views)`: `T` is also a [`views::Views`]. +#[doc(hidden)] +#[macro_export] +macro_rules! __views_exports { + ($plugin:ty, $component:ident) => { + impl $crate::views_bindings::exports::openidea::plugin::view_provider::Guest for $component { + fn render( + view: ::std::string::String, + viewport: ::core::option::Option<$crate::views_bindings::openidea::plugin::view_types::Viewport>, + ctx: &$crate::bindings::openidea::plugin::invocation::Invocation, + ) -> ::core::result::Result< + $crate::views_bindings::openidea::plugin::view_types::View, + $crate::bindings::openidea::plugin::types::Error, + > { + $crate::__rt::render_view::<$plugin>(view, viewport, ctx) + } + + fn handle( + view: ::std::string::String, + event: $crate::views_bindings::openidea::plugin::view_types::ViewEvent, + ctx: &$crate::bindings::openidea::plugin::invocation::Invocation, + ) -> ::core::result::Result<(), $crate::bindings::openidea::plugin::types::Error> { + $crate::__rt::view_event::<$plugin>(view, event, ctx) + } + } + + $crate::views_bindings::__export_views_world!($component with_types_in $crate::views_bindings); + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __plugin_exports { + ($plugin:ty, $component:ident, $b:path) => { + impl $crate::bindings::exports::openidea::plugin::lifecycle::Guest for $component { + fn activate( + ctx: $crate::bindings::openidea::plugin::types::Context, + ) -> ::core::result::Result<(), $crate::bindings::openidea::plugin::types::Error> { + $crate::__rt::activate::<$plugin>(ctx) + } + + fn deactivate() { + $crate::__rt::deactivate::<$plugin>() + } + } + + impl $crate::bindings::exports::openidea::plugin::commands::Guest for $component { + fn run( + id: ::std::string::String, + ctx: &$crate::bindings::openidea::plugin::invocation::Invocation, + arg: ::core::option::Option<::std::string::String>, + ) -> ::core::result::Result< + ::core::option::Option<::std::string::String>, + $crate::bindings::openidea::plugin::types::Error, + > { + $crate::__rt::run_command::<$plugin>(id, ctx, arg) + } + } + + impl $crate::bindings::exports::openidea::plugin::event_handler::Guest for $component { + fn handle( + events: ::std::vec::Vec<$crate::bindings::openidea::plugin::events::Event>, + ctx: &$crate::bindings::openidea::plugin::invocation::Invocation, + ) { + $crate::__rt::handle_events::<$plugin>(events, ctx) + } + } + }; +} + +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] +pub mod __rt { + //! The single plugin instance behind the exports. + use super::syntax::SyntaxProvider; + use super::{Context, Invocation, Plugin}; + use crate::bindings::openidea::plugin as b; + use crate::syntax_bindings::exports::openidea::plugin::syntax_provider as wit; + use std::any::Any; + use std::cell::RefCell; + + thread_local! { + static INSTANCE: RefCell>> = const { RefCell::new(None) }; + } + + fn with(f: impl FnOnce(&mut T) -> R) -> R { + INSTANCE.with(|cell| { + let mut slot = cell.borrow_mut(); + let plugin = slot.get_or_insert_with(|| Box::new(T::default())); + f(plugin.downcast_mut::().expect("one plugin type per component")) + }) + } + + pub fn activate(ctx: b::types::Context) -> Result<(), b::types::Error> { + let ctx = Context { + plugin_id: ctx.plugin_id, + plugin_version: ctx.plugin_version, + api_version: ctx.api_version, + capabilities: ctx.capabilities, + }; + with::(|p| p.activate(&ctx)).map_err(error_out) + } + + pub fn deactivate() { + with::(|p| p.deactivate()); + INSTANCE.with(|cell| cell.borrow_mut().take()); + } + + pub fn run_command( + id: String, + ctx: &b::invocation::Invocation, + arg: Option, + ) -> Result, b::types::Error> { + let ctx = Invocation::__new(ctx); + with::(|p| p.run_command(&id, &ctx, arg.as_deref())).map_err(error_out) + } + + // ---- providers ---- + + use crate::providers as p; + use crate::providers_bindings::exports::openidea::plugin::providers as w; + + fn doc(d: w::Document) -> p::Document { + p::Document { path: d.path, language: d.language, version: d.version, text: d.text } + } + + fn at(p: b::types::Position) -> crate::Position { + crate::Position::new(p.line, p.character) + } + + fn loc(l: crate::Location) -> b::types::Location { + b::types::Location { path: l.path, range: crate::host::__range_to(l.range) } + } + + pub fn completion( + d: w::Document, + pos: b::types::Position, + trigger: Option, + ) -> Vec { + let d = doc(d); + with::(|x| x.completion(&d, at(pos), trigger.as_deref())) + .into_iter() + .map(|i| w::CompletionItem { + label: i.label, + detail: i.detail, + kind: i.kind.map(|k| k.as_str().to_owned()), + insert_text: i.insert_text, + replace: i.replace.map(crate::host::__range_to), + sort_text: i.sort_text, + documentation: i.documentation, + }) + .collect() + } + + pub fn inline_completion( + d: w::Document, + pos: b::types::Position, + ) -> Option { + let d = doc(d); + with::(|x| x.inline_completion(&d, at(pos))).map(|s| w::InlineSuggestion { + insert_text: s.insert_text, + replace: s.replace.map(crate::host::__range_to), + }) + } + + pub fn code_actions( + d: w::Document, + sel: b::types::Range, + ) -> Vec { + let d = doc(d); + with::(|x| x.code_actions(&d, crate::host::__range_from(sel))) + .into_iter() + .map(|a| w::CodeAction { + title: a.title, + kind: a.kind, + preferred: a.preferred, + edits: a + .edits + .into_iter() + .map(|(path, edits)| w::FileEdit { + path, + edits: edits + .into_iter() + .map(|e| b::types::TextEdit { range: crate::host::__range_to(e.range), text: e.text }) + .collect(), + }) + .collect(), + }) + .collect() + } + + pub fn definition( + d: w::Document, + pos: b::types::Position, + ) -> Vec { + let d = doc(d); + with::(|x| x.definition(&d, at(pos))).into_iter().map(loc).collect() + } + + pub fn line_markers(d: w::Document) -> Vec { + let d = doc(d); + with::(|x| x.line_markers(&d)) + .into_iter() + .map(|m| w::LineMarker { line: m.line, icon: m.icon, tooltip: m.tooltip, target: m.target.map(loc) }) + .collect() + } + + // ---- views ---- + + use crate::views as v; + use crate::views_bindings::openidea::plugin::view_types as vt; + + fn error_out(e: crate::Error) -> b::types::Error { + use b::types::Error as E; + match e { + crate::Error::Denied(c) => E::Denied(c), + crate::Error::Stale => E::Stale, + crate::Error::NotFound(m) => E::NotFound(m), + crate::Error::Invalid(m) => E::Invalid(m), + crate::Error::Cancelled => E::Cancelled, + crate::Error::Failed(m) => E::Failed(m), + } + } + + fn view_out(view: v::View) -> vt::View { + let body = match view.body { + v::Body::Message(m) => vt::Body::Message(m), + v::Body::Tree(items) => vt::Body::Tree( + items + .into_iter() + .map(|i| vt::TreeItem { + key: i.key, + parent: i.parent, + label: i.label, + icon: i.icon, + detail: i.detail, + expandable: i.expandable, + expanded: i.expanded, + }) + .collect(), + ), + v::Body::List(items) => vt::Body::List( + items + .into_iter() + .map(|i| vt::ListItem { key: i.key, label: i.label, icon: i.icon, detail: i.detail }) + .collect(), + ), + v::Body::Form(fields) => vt::Body::Form( + fields + .into_iter() + .map(|f| vt::Field { + key: f.key, + label: f.label, + value: match f.value { + v::FieldValue::Text(t) => vt::FieldValue::Text(t), + v::FieldValue::Multiline(t) => vt::FieldValue::Multiline(t), + v::FieldValue::Checkbox(c) => vt::FieldValue::Checkbox(c), + v::FieldValue::Choice(o, s) => vt::FieldValue::Choice((o, s)), + }, + }) + .collect(), + ), + v::Body::Table(t) => vt::Body::Table(vt::Table { + columns: t.columns, + total_rows: t.total_rows, + first_row: t.first_row, + rows: t.rows, + editable: t.editable, + }), + v::Body::Html(h) => vt::Body::Html(h), + }; + vt::View { + toolbar: view + .toolbar + .into_iter() + .map(|b| vt::Button { id: b.id, label: b.label, icon: b.icon, enabled: b.enabled }) + .collect(), + body, + status: view.status, + } + } + + pub fn render_view( + view: String, + viewport: Option, + ctx: &b::invocation::Invocation, + ) -> Result { + let ctx = Invocation::__new(ctx); + let viewport = viewport.map(|v| v::Viewport { first_row: v.first_row, rows: v.rows }); + with::(|p| p.render(&view, viewport, &ctx)).map(view_out).map_err(error_out) + } + + pub fn view_event( + view: String, + event: vt::ViewEvent, + ctx: &b::invocation::Invocation, + ) -> Result<(), b::types::Error> { + let ctx = Invocation::__new(ctx); + let event = match event { + vt::ViewEvent::Button(id) => v::ViewEvent::Button(id), + vt::ViewEvent::Activate(k) => v::ViewEvent::Activate(k), + vt::ViewEvent::Select(k) => v::ViewEvent::Select(k), + vt::ViewEvent::Expand(k) => v::ViewEvent::Expand(k), + vt::ViewEvent::Collapse(k) => v::ViewEvent::Collapse(k), + vt::ViewEvent::Field((k, value)) => v::ViewEvent::Field(k, value), + vt::ViewEvent::Cell(c) => v::ViewEvent::Cell { row: c.row, column: c.column, value: c.value }, + vt::ViewEvent::InsertRow(r) => v::ViewEvent::InsertRow(r), + vt::ViewEvent::DeleteRows(r) => v::ViewEvent::DeleteRows(r), + vt::ViewEvent::Message(m) => v::ViewEvent::Message(m), + }; + with::(|p| p.handle(&view, event, &ctx)).map_err(error_out) + } + + pub fn handle_events(events: Vec, ctx: &b::invocation::Invocation) { + let events: Vec = events.into_iter().map(crate::host::__event).collect(); + let ctx = Invocation::__new(ctx); + with::(|p| p.handle_events(&events, &ctx)) + } + + fn offset(n: usize) -> u32 { + u32::try_from(n).unwrap_or(u32::MAX) + } + + pub fn highlights(language: &str, text: &str) -> Vec { + with::(|p| p.highlights(language, text)) + .into_iter() + .map(|t| wit::Token { start: offset(t.range.start), end: offset(t.range.end), kind: t.kind.name().into() }) + .collect() + } + + pub fn outline(language: &str, text: &str) -> Vec { + with::(|p| p.outline(language, text)) + .into_iter() + .map(|s| wit::Symbol { + name: s.name, + detail: s.detail, + kind: s.kind.name().into(), + start: offset(s.range.start), + end: offset(s.range.end), + name_start: offset(s.name_range.start), + name_end: offset(s.name_range.end), + parent: s.parent.map(offset), + }) + .collect() + } + + pub fn folding(language: &str, text: &str) -> Vec { + with::(|p| p.folding(language, text)) + .into_iter() + .map(|f| wit::Fold { + start_line: f.start_line, + end_line: f.end_line, + kind: match f.kind { + super::syntax::FoldKind::Region => "region", + super::syntax::FoldKind::Comment => "comment", + super::syntax::FoldKind::Imports => "imports", + } + .into(), + }) + .collect() + } +} diff --git a/sdk/rust/openidea-plugin/src/mock.rs b/sdk/rust/openidea-plugin/src/mock.rs new file mode 100644 index 00000000..33ce121d --- /dev/null +++ b/sdk/rust/openidea-plugin/src/mock.rs @@ -0,0 +1,732 @@ +//! A mock IDE for testing plugins with `cargo test` on the host target. +//! +//! [`MockHost::install`] makes the [`crate::host`] functions of the current +//! thread talk to a fresh mock: it records what the plugin did, keeps one +//! editor with a versioned document, and enforces the capabilities you give +//! it like the real host (a missing one returns [`Error::Denied`]). + +use crate::host::Invocation; +use crate::types::*; +use std::cell::RefCell; +use std::collections::{BTreeMap, BTreeSet}; +use std::marker::PhantomData; +use std::rc::Rc; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Notification { + pub level: NotificationLevel, + pub title: String, + pub body: String, +} + +/// A task the plugin began. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct MockTask { + pub title: String, + /// `(done, total, message)` reports, in order. + pub reports: Vec<(u32, Option, Option)>, + pub cancelled: bool, + pub ended: bool, +} + +type NetHandler = Box Result>; +type ProcessHandler = Box) -> Result>; + +/// A process run the plugin made. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ProcessRun { + pub program: String, + pub args: Vec, + /// The project root it ran in (`None`: the data directory). + pub cwd: Option, +} + +struct Editor { + path: String, + language: String, + text: String, + version: u64, + selections: Vec, +} + +#[derive(Default)] +struct State { + capabilities: Vec, + root: Option, + other_projects: Vec, + files: BTreeMap, + editor: Option, + notifications: Vec, + logs: Vec<(LogLevel, String)>, + status: BTreeMap, + storage: BTreeMap, + subscriptions: BTreeSet, + tasks: Vec, + vcs: Option, + fetches: u32, + fetch_error: Option, + diagnostics: BTreeMap>, + secrets: BTreeMap, + net: Option, + requests: Vec, + processes: BTreeMap, + runs: Vec, + refreshed: Vec, + view_messages: Vec<(String, String)>, + terminals: Vec, + settings: BTreeMap, +} + +/// A terminal the plugin opened. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MockTerminal { + pub title: String, + pub program: String, + pub args: Vec, +} + +thread_local! { + static CURRENT: RefCell>>> = const { RefCell::new(None) }; +} + +/// Handle to the mock installed for this thread. Dropping it uninstalls it. +pub struct MockHost { + state: Rc>, +} + +/// Every capability a plugin can hold, except `process:`/`net:`/`fs.read:`. +const ALL: &[&str] = + &["project.read", "editor.read", "editor.write", "vcs.read", "vcs.write", "storage", "events", "events.input"]; + +impl MockHost { + /// Installs a mock granting the usual capabilities, with project `/project`. + pub fn install() -> Self { + let state = Rc::new(RefCell::new(State { + capabilities: ALL.iter().map(|s| (*s).to_owned()).collect(), + root: Some("/project".into()), + ..State::default() + })); + CURRENT.with(|c| *c.borrow_mut() = Some(state.clone())); + Self { state } + } + + /// Grants exactly these capabilities. + pub fn with_capabilities(self, caps: &[&str]) -> Self { + self.state.borrow_mut().capabilities = caps.iter().map(|s| (*s).to_owned()).collect(); + self + } + + /// The invoking window's project (`None`: no project). + pub fn set_project_root(&self, root: Option<&str>) { + self.state.borrow_mut().root = root.map(str::to_owned); + } + + /// More open projects (for [`crate::host::projects`]). + pub fn add_project(&self, root: &str) { + self.state.borrow_mut().other_projects.push(root.to_owned()); + } + + /// A project file `read_file` can return (project-relative or absolute path). + pub fn add_file(&self, path: &str, text: &str) { + self.state.borrow_mut().files.insert(path.to_owned(), text.to_owned()); + } + + /// Focuses an editor on `text` with selections `(line, col, line, col)`. + pub fn open_editor(&self, path: &str, language: &str, text: &str, selections: &[(u32, u32, u32, u32)]) { + let selections = + selections.iter().map(|&(a, b, c, d)| Range::new(Position::new(a, b), Position::new(c, d))).collect(); + self.state.borrow_mut().editor = + Some(Editor { path: path.into(), language: language.into(), text: text.into(), version: 1, selections }); + } + + pub fn editor_text(&self) -> String { + self.state.borrow().editor.as_ref().map(|e| e.text.clone()).unwrap_or_default() + } + + pub fn editor_version(&self) -> u64 { + self.state.borrow().editor.as_ref().map_or(0, |e| e.version) + } + + /// The user edits the document (its version moves on). + pub fn type_in_editor(&self, text: &str) { + if let Some(e) = self.state.borrow_mut().editor.as_mut() { + e.text.push_str(text); + e.version += 1; + } + } + + /// The invocation a command from the focused window gets. + pub fn invocation(&self) -> Invocation<'static> { + Invocation::__new(MockInvocation(PhantomData)) + } + + pub fn notifications(&self) -> Vec { + self.state.borrow().notifications.clone() + } + + pub fn logs(&self) -> Vec<(LogLevel, String)> { + self.state.borrow().logs.clone() + } + + pub fn status_items(&self) -> BTreeMap { + self.state.borrow().status.clone() + } + + pub fn storage(&self) -> BTreeMap { + self.state.borrow().storage.clone() + } + + pub fn subscriptions(&self) -> BTreeSet { + self.state.borrow().subscriptions.clone() + } + + pub fn tasks(&self) -> Vec { + self.state.borrow().tasks.clone() + } + + /// The user cancels every open task. + pub fn cancel_tasks(&self) { + for t in &mut self.state.borrow_mut().tasks { + t.cancelled = true; + } + } + + /// What `vcs-status` returns for every project (`None`: not under git). + pub fn set_vcs_status(&self, status: Option) { + self.state.borrow_mut().vcs = status; + } + + /// Makes `vcs-fetch` fail. + pub fn fail_fetch(&self, error: Option) { + self.state.borrow_mut().fetch_error = error; + } + + pub fn fetches(&self) -> u32 { + self.state.borrow().fetches + } + + /// Diagnostics the plugin published, per path. + pub fn diagnostics(&self) -> BTreeMap> { + self.state.borrow().diagnostics.clone() + } + + /// Views the plugin asked to refresh, in order. + pub fn refreshed_views(&self) -> Vec { + self.state.borrow().refreshed.clone() + } + + /// `(view, message)` the plugin posted to its views' frames. + pub fn view_messages(&self) -> Vec<(String, String)> { + self.state.borrow().view_messages.clone() + } + + /// Terminals the plugin opened. + pub fn terminals(&self) -> Vec { + self.state.borrow().terminals.clone() + } + + /// The value of one of the plugin's settings, as JSON (`true`, `"text"`). + pub fn set_setting(&self, key: &str, json: &str) { + self.state.borrow_mut().settings.insert(key.into(), json.into()); + } + + /// A secret the user stored. + pub fn set_secret(&self, name: &str, value: &str) { + self.state.borrow_mut().secrets.insert(name.into(), value.into()); + } + + /// Answers the plugin's HTTP requests (secrets already filled in). + pub fn on_fetch(&self, handler: impl Fn(&HttpRequest) -> Result + 'static) { + self.state.borrow_mut().net = Some(Box::new(handler)); + } + + /// Requests the plugin made, as sent (secrets filled in). + pub fn requests(&self) -> Vec { + self.state.borrow().requests.clone() + } + + /// What running `process:` does: `(args, stdin) → output`. + pub fn on_process( + &self, + program: &str, + handler: impl Fn(&[String], Option<&str>) -> Result + 'static, + ) { + self.state.borrow_mut().processes.insert(program.into(), Box::new(handler)); + } + + pub fn process_runs(&self) -> Vec { + self.state.borrow().runs.clone() + } + + /// A context as `activate` receives it. + pub fn context(&self, plugin_id: &str) -> Context { + Context { + plugin_id: plugin_id.into(), + plugin_version: "0.0.0".into(), + api_version: crate::API_VERSION.into(), + capabilities: self.state.borrow().capabilities.clone(), + } + } +} + +impl Drop for MockHost { + fn drop(&mut self) { + CURRENT.with(|c| { + let mut cur = c.borrow_mut(); + if cur.as_ref().is_some_and(|s| Rc::ptr_eq(s, &self.state)) { + *cur = None; + } + }); + } +} + +#[doc(hidden)] +#[derive(Clone, Copy)] +pub struct MockInvocation<'a>(PhantomData<&'a ()>); + +#[doc(hidden)] +pub struct MockProject { + root: String, +} + +#[doc(hidden)] +pub struct MockEditor; + +#[doc(hidden)] +pub struct MockTaskRes { + index: usize, +} + +impl Drop for MockTaskRes { + fn drop(&mut self) { + current::with(|s| { + if let Some(t) = s.tasks.get_mut(self.index) { + t.ended = true; + } + }) + } +} + +#[doc(hidden)] +pub mod current { + //! The host functions, backed by the installed mock. + use super::*; + + pub type InvocationRef<'a> = MockInvocation<'a>; + pub type ProjectRes = MockProject; + pub type EditorRes = MockEditor; + pub type TaskRes = MockTaskRes; + + pub(super) fn with(f: impl FnOnce(&mut State) -> R) -> R { + CURRENT.with(|c| { + let cur = c.borrow(); + let state = cur.as_ref().expect("no mock host: call openidea_plugin::mock::MockHost::install() first"); + f(&mut state.borrow_mut()) + }) + } + + fn require(s: &State, cap: &str) -> Result<(), Error> { + if s.capabilities.iter().any(|c| c == cap) { Ok(()) } else { Err(Error::Denied(cap.to_owned())) } + } + + pub fn log(level: LogLevel, message: &str) { + with(|s| s.logs.push((level, message.to_owned()))) + } + + pub fn notify(level: NotificationLevel, title: &str, body: &str) { + with(|s| s.notifications.push(Notification { level, title: title.into(), body: body.into() })) + } + + pub fn set_status_item(id: &str, item: &StatusItem) { + with(|s| s.status.insert(id.to_owned(), item.clone())); + } + + pub fn remove_status_item(id: &str) { + with(|s| s.status.remove(id)); + } + + pub fn storage_get(key: &str) -> Result, Error> { + with(|s| { + require(s, "storage")?; + Ok(s.storage.get(key).cloned()) + }) + } + + pub fn storage_set(key: &str, value: &str) -> Result<(), Error> { + with(|s| { + require(s, "storage")?; + s.storage.insert(key.to_owned(), value.to_owned()); + Ok(()) + }) + } + + pub fn storage_delete(key: &str) -> Result<(), Error> { + with(|s| { + require(s, "storage")?; + s.storage.remove(key); + Ok(()) + }) + } + + pub fn storage_keys(prefix: &str) -> Result, Error> { + with(|s| { + require(s, "storage")?; + Ok(s.storage.keys().filter(|k| k.starts_with(prefix)).cloned().collect()) + }) + } + + pub fn projects() -> Result, Error> { + with(|s| { + require(s, "project.read")?; + Ok(s.root.iter().chain(&s.other_projects).map(|root| MockProject { root: root.clone() }).collect()) + }) + } + + pub fn project_root(p: &ProjectRes) -> Result { + with(|s| { + require(s, "project.read")?; + Ok(p.root.clone()) + }) + } + + pub fn project_read(p: &ProjectRes, path: &str) -> Result { + with(|s| { + require(s, "project.read")?; + let root = p.root.as_str(); + let rel = path.strip_prefix(root).map(|p| p.trim_start_matches('/')).unwrap_or(path); + if rel.starts_with('/') || rel.split('/').any(|seg| seg == "..") { + return Err(Error::Invalid(format!("{path}: access outside the project root is not allowed"))); + } + let open = s.editor.as_ref().filter(|e| e.path == path || e.path == format!("{root}/{rel}")); + if let Some(e) = open { + return Ok(e.text.clone()); + } + s.files.get(rel).or_else(|| s.files.get(path)).cloned().ok_or_else(|| Error::NotFound(path.into())) + }) + } + + pub fn invocation_project(_: InvocationRef<'_>) -> Option { + with(|s| s.root.clone().map(|root| MockProject { root })) + } + + pub fn invocation_editor(_: InvocationRef<'_>) -> Option { + with(|s| s.editor.as_ref().map(|_| MockEditor)) + } + + fn editor(f: impl FnOnce(&mut State, &mut Editor) -> R) -> R { + with(|s| { + let mut e = s.editor.take().expect("the editor was closed"); + let r = f(s, &mut e); + s.editor = Some(e); + r + }) + } + + pub fn editor_path(_: &EditorRes) -> String { + editor(|_, e| e.path.clone()) + } + + pub fn editor_language(_: &EditorRes) -> String { + editor(|_, e| e.language.clone()) + } + + pub fn editor_document(_: &EditorRes) -> Result { + editor(|s, e| { + require(s, "editor.read")?; + Ok(Document { version: e.version, text: e.text.clone() }) + }) + } + + pub fn editor_selections(_: &EditorRes) -> Result, Error> { + editor(|s, e| { + require(s, "editor.read")?; + Ok(e.selections.clone()) + }) + } + + pub fn editor_apply(_: &EditorRes, version: u64, edits: &[TextEdit]) -> Result { + editor(|s, e| { + require(s, "editor.write")?; + if version != e.version { + return Err(Error::Stale); + } + let mut spans = Vec::with_capacity(edits.len()); + for edit in edits { + let start = crate::text::offset(&e.text, edit.range.start); + let end = crate::text::offset(&e.text, edit.range.end); + match (start, end) { + (Some(a), Some(b)) if a <= b => spans.push((a, b, edit.text.as_str())), + _ => return Err(Error::Invalid("edit outside the document".into())), + } + } + spans.sort_by_key(|(a, b, _)| (*a, *b)); + if spans.windows(2).any(|w| w[0].1 > w[1].0) { + return Err(Error::Invalid("overlapping edits".into())); + } + for (a, b, text) in spans.into_iter().rev() { + e.text.replace_range(a..b, text); + } + if !edits.is_empty() { + e.version += 1; + } + Ok(e.version) + }) + } + + pub fn vcs_status(_: &ProjectRes) -> Result, Error> { + with(|s| { + require(s, "vcs.read")?; + Ok(s.vcs.clone()) + }) + } + + pub fn vcs_fetch(_: &ProjectRes) -> Result<(), Error> { + with(|s| { + require(s, "vcs.write")?; + if let Some(e) = s.fetch_error.clone() { + return Err(e); + } + s.fetches += 1; + Ok(()) + }) + } + + pub fn subscribe(kind: EventKind) -> Result<(), Error> { + with(|s| { + let cap = match kind { + EventKind::ActionPerformed => Some("events.input"), + EventKind::Scheduled => None, + _ => Some("events"), + }; + if let Some(cap) = cap { + require(s, cap)?; + } + s.subscriptions.insert(kind); + Ok(()) + }) + } + + pub fn unsubscribe(kind: EventKind) { + with(|s| s.subscriptions.remove(&kind)); + } + + pub fn project_find(p: &ProjectRes, glob: &str, limit: u32) -> Result, Error> { + with(|s| { + require(s, "project.read")?; + let root = p.root.trim_end_matches('/'); + let mut out: Vec = s + .files + .keys() + .map(|k| if k.starts_with('/') { k.clone() } else { format!("{root}/{k}") }) + .chain(s.editor.as_ref().map(|e| e.path.clone())) + .filter(|path| { + path.strip_prefix(root).map(|r| r.trim_start_matches('/')).is_some_and(|rel| glob_match(glob, rel)) + }) + .collect(); + out.sort(); + out.dedup(); + out.truncate(limit as usize); + Ok(out) + }) + } + + pub fn publish_diagnostics(path: &str, items: &[Diagnostic]) -> Result<(), Error> { + with(|s| { + require(s, "project.read")?; + if items.is_empty() { + s.diagnostics.remove(path); + } else { + s.diagnostics.insert(path.to_owned(), items.to_vec()); + } + Ok(()) + }) + } + + fn net_host(url: &str) -> Option { + let rest = url.split_once("://")?.1; + let host = rest.split(['/', ':', '?']).next()?; + Some(host.to_ascii_lowercase()) + } + + pub fn fetch(req: &HttpRequest) -> Result { + with(|s| { + let host = net_host(&req.url).ok_or_else(|| Error::Invalid(format!("{:?} is not a URL", req.url)))?; + let cap = format!("net:{host}"); + if !s.capabilities.iter().any(|c| *c == cap || c == "net:*") { + return Err(Error::Denied(cap)); + } + let mut sent = req.clone(); + for (_, value) in &mut sent.headers { + while let Some(i) = value.find("{{secret:") { + require(s, "secrets")?; + let end = value[i..].find("}}").ok_or_else(|| Error::Invalid("unterminated secret".into()))? + i; + let name = value[i + 9..end].to_owned(); + let secret = + s.secrets.get(&name).cloned().ok_or_else(|| Error::NotFound(format!("secret {name:?}")))?; + value.replace_range(i..end + 2, &secret); + } + } + s.requests.push(sent.clone()); + match &s.net { + Some(handler) => handler(&sent), + None => Err(Error::Failed("no network in the mock (MockHost::on_fetch)".into())), + } + }) + } + + pub fn secret_is_set(name: &str) -> bool { + with(|s| s.capabilities.iter().any(|c| c == "secrets") && s.secrets.contains_key(name)) + } + + pub fn refresh_view(view: &str) { + with(|s| s.refreshed.push(view.into())) + } + + pub fn post_view_message(view: &str, message: &str) -> Result<(), Error> { + with(|s| s.view_messages.push((view.into(), message.into()))); + Ok(()) + } + + pub fn open_terminal(title: &str, program: &str, args: &[String]) -> Result<(), Error> { + with(|s| { + require(s, &format!("process:{program}"))?; + s.terminals.push(MockTerminal { title: title.into(), program: program.into(), args: args.to_vec() }); + Ok(()) + }) + } + + pub fn setting(key: &str) -> Option { + with(|s| s.settings.get(key).cloned()) + } + + pub fn run_process( + program: &str, + args: &[String], + cwd: Option<&ProjectRes>, + stdin: Option<&str>, + ) -> Result { + with(|s| { + require(s, &format!("process:{program}"))?; + s.runs.push(ProcessRun { program: program.into(), args: args.to_vec(), cwd: cwd.map(|p| p.root.clone()) }); + match s.processes.get(program) { + Some(handler) => handler(args, stdin), + None => Err(Error::NotFound(format!("{program} (MockHost::on_process)"))), + } + }) + } + + pub fn begin_task(title: &str, _cancellable: bool) -> TaskRes { + with(|s| { + s.tasks.push(MockTask { title: title.into(), ..MockTask::default() }); + MockTaskRes { index: s.tasks.len() - 1 } + }) + } + + pub fn task_report(t: &TaskRes, done: u32, total: Option, message: Option<&str>) { + with(|s| s.tasks[t.index].reports.push((done, total, message.map(str::to_owned)))) + } + + pub fn task_cancelled(t: &TaskRes) -> bool { + with(|s| s.tasks[t.index].cancelled) + } +} + +/// `*` within a segment, `**` across segments, `?` one character. +fn glob_match(glob: &str, path: &str) -> bool { + fn go(p: &[u8], s: &[u8]) -> bool { + match p { + [] => s.is_empty(), + [b'*', b'*', b'/', rest @ ..] => go(rest, s) || (!s.is_empty() && go(p, &s[1..])), + [b'*', b'*', rest @ ..] => (0..=s.len()).any(|i| go(rest, &s[i..])), + [b'*', rest @ ..] => (0..=s.len()).take_while(|&i| i == 0 || s[i - 1] != b'/').any(|i| go(rest, &s[i..])), + [b'?', rest @ ..] => !s.is_empty() && s[0] != b'/' && go(rest, &s[1..]), + [c, rest @ ..] => s.first() == Some(c) && go(rest, &s[1..]), + } + } + go(glob.as_bytes(), path.as_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::host; + + #[test] + fn records_and_enforces() { + let mock = MockHost::install(); + mock.add_file("src/a.txt", "hello"); + let ctx = mock.invocation(); + let project = ctx.project().unwrap(); + assert_eq!(project.read_file("/project/src/a.txt").unwrap(), "hello"); + assert_eq!(project.read_file("src/a.txt").unwrap(), "hello"); + assert!(matches!(project.read_file("../etc/passwd"), Err(Error::Invalid(_)))); + host::notify(NotificationLevel::Info, "t", "b"); + assert_eq!(mock.notifications()[0].title, "t"); + host::storage::set("k", "v").unwrap(); + assert_eq!(host::storage::get("k").unwrap().as_deref(), Some("v")); + assert_eq!(host::storage::keys("").unwrap(), ["k"]); + host::set_status_item("s", &StatusItem { text: "x".into(), tooltip: None, command: None }); + assert_eq!(mock.status_items()["s"].text, "x"); + { + let task = host::begin_task("Work", true); + task.report(1, Some(2), None); + mock.cancel_tasks(); + assert!(task.is_cancelled()); + } + assert!(mock.tasks()[0].ended); + } + + #[test] + fn versioned_edits() { + let mock = MockHost::install(); + mock.open_editor("/project/a.txt", "text", "one two", &[(0, 0, 0, 3), (0, 4, 0, 7)]); + let editor = mock.invocation().editor().unwrap(); + let v = editor.transform_selections(|s| s.to_uppercase()).unwrap(); + assert_eq!((mock.editor_text().as_str(), v), ("ONE TWO", 2)); + assert_eq!(editor.apply_edits(1, &[]), Err(Error::Stale)); + mock.type_in_editor("!"); + assert_eq!(mock.editor_version(), 3); + } + + #[test] + fn missing_capabilities_are_denied() { + let mock = MockHost::install().with_capabilities(&["project.read"]); + mock.open_editor("/project/a.txt", "text", "x", &[]); + let editor = mock.invocation().editor().unwrap(); + assert_eq!(editor.apply_edits(1, &[]), Err(Error::Denied("editor.write".into()))); + assert_eq!(host::storage::get("k"), Err(Error::Denied("storage".into()))); + assert_eq!(host::subscribe(EventKind::ActionPerformed), Err(Error::Denied("events.input".into()))); + } + + #[test] + fn network_secrets_processes_and_files() { + let mock = MockHost::install(); + mock.add_file("src/a/UserMapper.xml", ""); + mock.add_file("src/B.java", "class B {}"); + let project = mock.invocation().project().unwrap(); + assert_eq!(project.find_files("**/*Mapper.xml", 10).unwrap(), ["/project/src/a/UserMapper.xml"]); + assert!( + matches!(host::fetch(&HttpRequest::get("https://api.x.io/v1")), Err(Error::Denied(c)) if c == "net:api.x.io") + ); + + let mock = MockHost::install().with_capabilities(&["net:api.x.io", "secrets", "project.read", "process:java"]); + mock.set_secret("key", "s3cr3t"); + mock.on_fetch(|r| Ok(HttpResponse { status: 200, headers: vec![], body: r.headers[0].1.clone().into_bytes() })); + let r = host::fetch(&HttpRequest::get("https://api.x.io/v1").header("Authorization", "Bearer {{secret:key}}")) + .unwrap(); + assert_eq!(r.text(), "Bearer s3cr3t"); + assert!(host::secret_is_set("key")); + mock.on_process("java", |args, _| { + Ok(ProcessOutput { status: Some(0), stdout: args.join(" "), stderr: String::new() }) + }); + let out = mock.invocation().project().unwrap().run_process("java", &["-version".into()], None).unwrap(); + assert_eq!(out.stdout, "-version"); + assert_eq!(mock.process_runs()[0].cwd.as_deref(), Some("/project")); + host::publish_diagnostics( + "/project/a.java", + &[Diagnostic { range: Range::default(), severity: Severity::Warning, message: "m".into(), code: None }], + ) + .unwrap(); + assert_eq!(mock.diagnostics()["/project/a.java"].len(), 1); + } +} diff --git a/sdk/rust/openidea-plugin/src/providers.rs b/sdk/rust/openidea-plugin/src/providers.rs new file mode 100644 index 00000000..c10f75cf --- /dev/null +++ b/sdk/rust/openidea-plugin/src/providers.rs @@ -0,0 +1,167 @@ +//! Editor providers: implement [`Providers`] and register with +//! `register_plugin!(T, providers)`, then declare the kinds and languages in +//! `plugin.toml`: +//! +//! ```toml +//! [[contributes.providers]] +//! kinds = ["completion", "definition"] # also inline-completion, code-actions, line-markers +//! languages = ["xml"] +//! ``` +//! +//! They run on the editing path: answer within ~50 ms (later results are +//! dropped; at 500 ms the call is interrupted). Inline completion may take +//! longer (it may use the network) but is cancelled when the user types on. + +use crate::types::{Location, Position, Range, TextEdit}; + +/// The document a request is about. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Document { + pub path: String, + pub language: String, + pub version: u64, + pub text: String, +} + +/// Icon and sort group of a completion item. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum CompletionKind { + Text, + Method, + Function, + Constructor, + Field, + Variable, + Class, + Interface, + Module, + Property, + Unit, + Value, + Enum, + Keyword, + Snippet, + Color, + File, + Reference, + Folder, + EnumMember, + Constant, + Struct, + Event, + Operator, + TypeParameter, +} + +impl CompletionKind { + /// The name the plugin API uses (`completion-item.kind`). + pub fn as_str(self) -> &'static str { + match self { + Self::Text => "text", + Self::Method => "method", + Self::Function => "function", + Self::Constructor => "constructor", + Self::Field => "field", + Self::Variable => "variable", + Self::Class => "class", + Self::Interface => "interface", + Self::Module => "module", + Self::Property => "property", + Self::Unit => "unit", + Self::Value => "value", + Self::Enum => "enum", + Self::Keyword => "keyword", + Self::Snippet => "snippet", + Self::Color => "color", + Self::File => "file", + Self::Reference => "reference", + Self::Folder => "folder", + Self::EnumMember => "enum-member", + Self::Constant => "constant", + Self::Struct => "struct", + Self::Event => "event", + Self::Operator => "operator", + Self::TypeParameter => "type-parameter", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CompletionItem { + pub label: String, + pub detail: Option, + pub kind: Option, + pub insert_text: String, + /// Replaced on accept; `None`: the word at the caret. + pub replace: Option, + pub sort_text: Option, + /// Markdown. + pub documentation: Option, +} + +impl CompletionItem { + pub fn new(label: &str, kind: CompletionKind) -> Self { + Self { + label: label.into(), + detail: None, + kind: Some(kind), + insert_text: label.into(), + replace: None, + sort_text: None, + documentation: None, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InlineSuggestion { + pub insert_text: String, + /// Replaced range; `None` inserts at the caret. + pub replace: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CodeAction { + pub title: String, + /// `quickfix`, `refactor`, … + pub kind: Option, + pub preferred: bool, + /// (absolute path, edits) per file. + pub edits: Vec<(String, Vec)>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LineMarker { + /// 0-based. + pub line: u32, + /// `navigate` (default), `implemented`, `implementing`, `run`. + pub icon: Option, + pub tooltip: String, + /// Opened on click. + pub target: Option, +} + +/// What a plugin provides in the editor. Only the kinds declared in +/// `plugin.toml` are ever called; the defaults return nothing. +pub trait Providers { + fn completion(&mut self, _doc: &Document, _at: Position, _trigger: Option<&str>) -> Vec { + Vec::new() + } + + fn inline_completion(&mut self, _doc: &Document, _at: Position) -> Option { + None + } + + fn code_actions(&mut self, _doc: &Document, _selection: Range) -> Vec { + Vec::new() + } + + fn definition(&mut self, _doc: &Document, _at: Position) -> Vec { + Vec::new() + } + + fn line_markers(&mut self, _doc: &Document) -> Vec { + Vec::new() + } +} diff --git a/sdk/rust/openidea-plugin/src/syntax.rs b/sdk/rust/openidea-plugin/src/syntax.rs new file mode 100644 index 00000000..74e860a9 --- /dev/null +++ b/sdk/rust/openidea-plugin/src/syntax.rs @@ -0,0 +1,224 @@ +//! Syntax for the plugin's own languages (highlighting, structure view, +//! folding) when the IDE has no grammar for them. Implement [`SyntaxProvider`] +//! and register with `register_plugin!(MyPlugin, syntax)`. +//! +//! The IDE calls these with the whole document on the editing path, so keep +//! them fast (a hand-written lexer is typical). Offsets are UTF-8 byte offsets +//! into `text`; lines are 0-based. + +use std::ops::Range; + +/// Highlight categories; the theme decides the colours. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Highlight { + Keyword, + String, + StringSpecial, + Escape, + Regexp, + Atom, + Number, + Constant, + Comment, + DocComment, + Function, + FunctionCall, + Builtin, + Type, + Namespace, + Variable, + SelfVariable, + Property, + Attribute, + Macro, + Label, + Tag, + Operator, + Punctuation, +} + +impl Highlight { + pub fn name(self) -> &'static str { + match self { + Self::Keyword => "keyword", + Self::String => "string", + Self::StringSpecial => "string-special", + Self::Escape => "escape", + Self::Regexp => "regexp", + Self::Atom => "atom", + Self::Number => "number", + Self::Constant => "constant", + Self::Comment => "comment", + Self::DocComment => "doc-comment", + Self::Function => "function", + Self::FunctionCall => "function-call", + Self::Builtin => "builtin", + Self::Type => "type", + Self::Namespace => "namespace", + Self::Variable => "variable", + Self::SelfVariable => "self-variable", + Self::Property => "property", + Self::Attribute => "attribute", + Self::Macro => "macro", + Self::Label => "label", + Self::Tag => "tag", + Self::Operator => "operator", + Self::Punctuation => "punctuation", + } + } +} + +/// A highlighted range. Tokens must not overlap; the IDE sorts them. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Token { + pub range: Range, + pub kind: Highlight, +} + +/// Kinds of structure-view symbols. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum SymbolKind { + Module, + Namespace, + Package, + Class, + Interface, + Struct, + Enum, + EnumMember, + Trait, + Function, + Method, + Constructor, + Field, + Property, + Variable, + Constant, + TypeParameter, + TypeAlias, + Macro, + Event, + Operator, + Key, +} + +impl SymbolKind { + pub fn name(self) -> &'static str { + match self { + Self::Module => "module", + Self::Namespace => "namespace", + Self::Package => "package", + Self::Class => "class", + Self::Interface => "interface", + Self::Struct => "struct", + Self::Enum => "enum", + Self::EnumMember => "enum-member", + Self::Trait => "trait", + Self::Function => "function", + Self::Method => "method", + Self::Constructor => "constructor", + Self::Field => "field", + Self::Property => "property", + Self::Variable => "variable", + Self::Constant => "constant", + Self::TypeParameter => "type-parameter", + Self::TypeAlias => "type-alias", + Self::Macro => "macro", + Self::Event => "event", + Self::Operator => "operator", + Self::Key => "key", + } + } +} + +/// A symbol of the structure view. `parent` is the index of the enclosing +/// symbol in the same list, which must come before it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Symbol { + pub name: String, + pub detail: Option, + pub kind: SymbolKind, + /// The whole declaration. + pub range: Range, + /// The name; where navigation lands. + pub name_range: Range, + pub parent: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FoldKind { + Region, + Comment, + Imports, +} + +/// A foldable range of lines (the first stays visible). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Fold { + pub start_line: u32, + pub end_line: u32, + pub kind: FoldKind, +} + +/// Syntax of the languages the plugin contributes. `language` is the +/// language id from the plugin's definition. +pub trait SyntaxProvider { + fn highlights(&mut self, language: &str, text: &str) -> Vec; + + fn outline(&mut self, _language: &str, _text: &str) -> Vec { + Vec::new() + } + + fn folding(&mut self, _language: &str, _text: &str) -> Vec { + Vec::new() + } +} + +/// Folds for every multi-line `open` … `close` pair (braces, brackets), +/// skipping the ones inside the given non-code ranges (strings, comments). +pub fn bracket_folds(text: &str, open: u8, close: u8, skip: &[Range]) -> Vec { + let mut folds = Vec::new(); + let mut stack: Vec = Vec::new(); + let mut line = 0u32; + let mut skip = skip.iter().peekable(); + for (i, b) in text.bytes().enumerate() { + while skip.peek().is_some_and(|r| r.end <= i) { + skip.next(); + } + if b == b'\n' { + line += 1; + continue; + } + if skip.peek().is_some_and(|r| r.start <= i) { + continue; + } + if b == open { + stack.push(line); + } else if b == close + && let Some(start) = stack.pop() + && line > start + { + folds.push(Fold { start_line: start, end_line: line, kind: FoldKind::Region }); + } + } + folds +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bracket_folds_skip_strings() { + let text = "a {\n \"{\"\n b {\n }\n}\n"; + let s = text.find('"').unwrap(); + let folds = bracket_folds(text, b'{', b'}', std::slice::from_ref(&(s..s + 3))); + assert_eq!( + folds, + [ + Fold { start_line: 2, end_line: 3, kind: FoldKind::Region }, + Fold { start_line: 0, end_line: 4, kind: FoldKind::Region }, + ] + ); + } +} diff --git a/sdk/rust/openidea-plugin/src/text.rs b/sdk/rust/openidea-plugin/src/text.rs new file mode 100644 index 00000000..7f34e968 --- /dev/null +++ b/sdk/rust/openidea-plugin/src/text.rs @@ -0,0 +1,82 @@ +//! Helpers for the editor's coordinates (0-based lines, UTF-16 columns). + +use crate::types::Position; + +/// Byte offset of `pos` in `text`, if it exists (a column past the end of +/// the line is clamped to it). +pub fn offset(text: &str, pos: Position) -> Option { + let mut line_start = 0; + for _ in 0..pos.line { + line_start += text[line_start..].find('\n')? + 1; + } + let line_end = text[line_start..].find('\n').map_or(text.len(), |i| line_start + i); + let mut units = 0u32; + for (i, ch) in text[line_start..line_end].char_indices() { + if units >= pos.character { + return Some(line_start + i); + } + units += ch.len_utf16() as u32; + } + Some(line_end) +} + +/// Position of the byte offset `at` in `text` (clamped to the text). +pub fn position(text: &str, at: usize) -> Position { + let at = at.min(text.len()); + let before = &text[..at]; + let line = before.matches('\n').count() as u32; + let line_start = before.rfind('\n').map_or(0, |i| i + 1); + let character = text[line_start..at].chars().map(|c| c.len_utf16() as u32).sum(); + Position { line, character } +} + +/// The text of a JSON string literal's contents (`\"`, `\\`, `\n`, `\uXXXX`). +pub fn unescape_json(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some('r') => out.push('\r'), + Some('b') => out.push('\u{8}'), + Some('f') => out.push('\u{c}'), + Some('u') => { + let hex: String = chars.by_ref().take(4).collect(); + let mut code = u32::from_str_radix(&hex, 16).unwrap_or(0xfffd); + // A surrogate pair: `\ud83d\ude00`. + if (0xd800..0xdc00).contains(&code) { + let rest: String = chars.clone().take(6).collect(); + if let Some(low) = rest.strip_prefix("\\u").and_then(|h| u32::from_str_radix(h, 16).ok()) { + chars.by_ref().nth(5); + code = 0x10000 + ((code - 0xd800) << 10) + (low - 0xdc00); + } + } + out.push(char::from_u32(code).unwrap_or('\u{fffd}')); + } + Some(other) => out.push(other), + None => {} + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trips_utf16_columns() { + let text = "ab\n😀x\nlast"; + for at in [0, 1, 2, 3, 7, 8, 9, text.len()] { + assert_eq!(offset(text, position(text, at)), Some(at), "{at}"); + } + assert_eq!(position(text, 7), Position::new(1, 2)); + assert_eq!(offset(text, Position::new(0, 99)), Some(2), "clamped to the line"); + assert_eq!(offset(text, Position::new(5, 0)), None); + } +} diff --git a/sdk/rust/openidea-plugin/src/types.rs b/sdk/rust/openidea-plugin/src/types.rs new file mode 100644 index 00000000..5a74f67d --- /dev/null +++ b/sdk/rust/openidea-plugin/src/types.rs @@ -0,0 +1,278 @@ +//! Plain data types of the API (independent of the target). + +/// Why a host call failed. A capability that is not granted is `Denied`: +/// degrade gracefully (show what you can) instead of failing the command. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Error { + /// Not granted; names the capability (`editor.write`). + Denied(String), + /// The document changed since the version the edit was made for. + Stale, + NotFound(String), + Invalid(String), + Cancelled, + Failed(String), +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Denied(c) => write!(f, "permission denied: {c} is not granted"), + Self::Stale => f.write_str("the document changed in the meantime"), + Self::NotFound(m) => write!(f, "not found: {m}"), + Self::Invalid(m) => write!(f, "invalid: {m}"), + Self::Cancelled => f.write_str("cancelled"), + Self::Failed(m) => f.write_str(m), + } + } +} + +impl std::error::Error for Error {} + +impl From for String { + fn from(e: Error) -> Self { + e.to_string() + } +} + +/// A plain message is [`Error::Failed`]. +impl From for Error { + fn from(message: String) -> Self { + Self::Failed(message) + } +} + +impl From<&str> for Error { + fn from(message: &str) -> Self { + Self::Failed(message.to_owned()) + } +} + +/// Log level of [`crate::host::log`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LogLevel { + Trace, + Debug, + Info, + Warn, + Error, +} + +/// Severity of [`crate::host::notify`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NotificationLevel { + Info, + Warning, + Error, +} + +/// 0-based line and UTF-16 code unit column (as in the editor and LSP). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Position { + pub line: u32, + pub character: u32, +} + +impl Position { + pub const fn new(line: u32, character: u32) -> Self { + Self { line, character } + } +} + +/// Half-open range; a cursor is an empty range. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Range { + pub start: Position, + pub end: Position, +} + +impl Range { + pub const fn new(start: Position, end: Position) -> Self { + Self { start, end } + } + + pub fn is_empty(&self) -> bool { + self.start == self.end + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TextEdit { + pub range: Range, + pub text: String, +} + +/// An editor's document at one version. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Document { + pub version: u64, + pub text: String, +} + +impl Document { + /// The text of `range` (UTF-16 columns), if it lies inside the document. + pub fn text_in(&self, range: Range) -> Option<&str> { + let start = crate::text::offset(&self.text, range.start)?; + let end = crate::text::offset(&self.text, range.end)?; + self.text.get(start.min(end)..end.max(start)) + } +} + +/// What `activate` receives. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Context { + pub plugin_id: String, + pub plugin_version: String, + /// Plugin API version the host implements. + pub api_version: String, + /// Capabilities granted to the plugin (`project.read`, …). + pub capabilities: Vec, +} + +impl Context { + pub fn has(&self, capability: &str) -> bool { + self.capabilities.iter().any(|c| c == capability) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StatusItem { + pub text: String, + pub tooltip: Option, + /// One of the plugin's commands, run on click. + pub command: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum EventKind { + FileOpened, + FileSaved, + EditorFocused, + /// Needs `events.input`. + ActionPerformed, + VcsChanged, + Scheduled, +} + +/// How the user started an action. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ActionSource { + Keyboard, + Menu, + Toolbar, + ContextMenu, + Search, + Other, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ActionPerformed { + /// Action id (`editor.duplicate-line`). + pub action: String, + pub title: String, + pub source: ActionSource, + /// Its keyboard shortcut, if it has one. + pub shortcut: Option, +} + +/// A workbench event (see [`crate::host::subscribe`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Event { + FileOpened(String), + FileSaved(String), + EditorFocused(Option), + ActionPerformed(ActionPerformed), + /// A repository (its root) changed. + VcsChanged(String), + /// The `on-schedule` period elapsed. + Scheduled, +} + +/// The repository containing a project. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RepositoryStatus { + pub root: String, + /// `None` when HEAD is detached. + pub branch: Option, + pub commit: Option, + pub upstream: Option, + pub ahead: u32, + pub behind: u32, + /// Merge / rebase / cherry-pick in progress. + pub operation: Option, + pub changed_files: u32, +} + +/// A range in a file. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Location { + /// Absolute path. + pub path: String, + pub range: Range, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Severity { + Error, + Warning, + Info, + Hint, +} + +/// A problem in a file (see [`crate::host::publish_diagnostics`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Diagnostic { + pub range: Range, + pub severity: Severity, + pub message: String, + /// Rule or check id. + pub code: Option, +} + +/// An HTTP request (see [`crate::host::fetch`]). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct HttpRequest { + pub method: String, + pub url: String, + /// `{{secret:}}` in a value is filled in by the IDE. + pub headers: Vec<(String, String)>, + pub body: Option>, + pub timeout_ms: Option, +} + +impl HttpRequest { + pub fn get(url: &str) -> Self { + Self { method: "GET".into(), url: url.into(), ..Self::default() } + } + + pub fn post(url: &str, body: impl Into>) -> Self { + Self { method: "POST".into(), url: url.into(), body: Some(body.into()), ..Self::default() } + } + + pub fn header(mut self, name: &str, value: &str) -> Self { + self.headers.push((name.into(), value.into())); + self + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct HttpResponse { + pub status: u16, + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +impl HttpResponse { + pub fn text(&self) -> String { + String::from_utf8_lossy(&self.body).into_owned() + } +} + +/// What a process printed (see [`crate::host::run_process`]). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ProcessOutput { + /// `None` when killed by a signal. + pub status: Option, + pub stdout: String, + pub stderr: String, +} diff --git a/sdk/rust/openidea-plugin/src/views.rs b/sdk/rust/openidea-plugin/src/views.rs new file mode 100644 index 00000000..3da8e506 --- /dev/null +++ b/sdk/rust/openidea-plugin/src/views.rs @@ -0,0 +1,225 @@ +//! Views and custom editors (`[[contributes.views]]`, +//! `[[contributes.customEditors]]`): implement [`Views`] and register with +//! `register_plugin!(MyPlugin, views)`. +//! +//! A view is data — a toolbar, a body (tree, list, form, table, message or +//! sandboxed HTML) and a status line. The IDE renders it and calls +//! [`Views::handle`] with what the user did; call [`crate::host::refresh_view`] +//! when the content changes. For a custom editor, `ctx.editor()` is its +//! document: read it with `document()` and change it with `apply_edits`, so +//! the text editor of the same file follows and undo is shared. + +use crate::{Error, Invocation}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Button { + pub id: String, + pub label: String, + /// An IDE icon (`refresh`, `add`, `remove`, `run`, `stop`, `settings`…). + pub icon: Option, + pub enabled: bool, +} + +impl Button { + pub fn new(id: &str, label: &str) -> Self { + Self { id: id.into(), label: label.into(), icon: None, enabled: true } + } + + pub fn icon(mut self, icon: &str) -> Self { + self.icon = Some(icon.into()); + self + } + + pub fn enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } +} + +/// A tree node; `parent` is the key of an item listed before it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TreeItem { + pub key: String, + pub parent: Option, + pub label: String, + pub icon: Option, + pub detail: Option, + /// Shows an expander before the children are known ([`ViewEvent::Expand`]). + pub expandable: bool, + pub expanded: bool, +} + +impl TreeItem { + pub fn new(key: &str, label: &str) -> Self { + Self { + key: key.into(), + parent: None, + label: label.into(), + icon: None, + detail: None, + expandable: false, + expanded: false, + } + } + + pub fn parent(mut self, parent: &str) -> Self { + self.parent = Some(parent.into()); + self + } + + pub fn icon(mut self, icon: &str) -> Self { + self.icon = Some(icon.into()); + self + } + + pub fn detail(mut self, detail: &str) -> Self { + self.detail = Some(detail.into()); + self + } + + /// Has (or may have) children; `expanded` shows them. + pub fn expandable(mut self, expanded: bool) -> Self { + self.expandable = true; + self.expanded = expanded; + self + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ListItem { + pub key: String, + pub label: String, + pub icon: Option, + pub detail: Option, +} + +impl ListItem { + pub fn new(key: &str, label: &str) -> Self { + Self { key: key.into(), label: label.into(), icon: None, detail: None } + } + + pub fn icon(mut self, icon: &str) -> Self { + self.icon = Some(icon.into()); + self + } + + pub fn detail(mut self, detail: &str) -> Self { + self.detail = Some(detail.into()); + self + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum FieldValue { + Text(String), + Multiline(String), + Checkbox(bool), + /// Options and the chosen one. + Choice(Vec, String), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Field { + pub key: String, + pub label: String, + pub value: FieldValue, +} + +impl Field { + pub fn new(key: &str, label: &str, value: FieldValue) -> Self { + Self { key: key.into(), label: label.into(), value } + } +} + +/// Rows `first_row..first_row + rows.len()` of `total_rows`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Table { + pub columns: Vec, + pub total_rows: u32, + pub first_row: u32, + pub rows: Vec>, + pub editable: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Body { + Message(String), + Tree(Vec), + List(Vec), + Form(Vec), + Table(Table), + /// Shown in a sandboxed frame; its script talks to the plugin with + /// `openidea.postMessage(text)` and `openidea.onMessage(fn)`. + Html(String), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct View { + pub toolbar: Vec