diff --git a/crates/ide-extension/src/manifest.rs b/crates/ide-extension/src/manifest.rs index 4c100fd0e1..2dcec4e821 100644 --- a/crates/ide-extension/src/manifest.rs +++ b/crates/ide-extension/src/manifest.rs @@ -49,11 +49,15 @@ pub struct Manifest { pub name: String, pub version: String, pub description: String, + /// Markdown file for Settings › Plugins › Overview (`description-file`). + pub description_file: Option, pub authors: Vec, pub homepage: Option, pub license: Option, /// Release notes of this version (Settings › Plugins › What's New). pub change_notes: Option, + /// Markdown file for Settings › Plugins › What's New (`change-notes-file`). + pub change_notes_file: Option, /// Marketplace categories as declared (see [`Manifest::categories`]). pub declared_categories: Vec, /// SVG shown in Settings › Plugins and the marketplace. @@ -195,6 +199,8 @@ struct Raw { #[serde(default)] description: String, #[serde(default)] + description_file: Option, + #[serde(default)] authors: Vec, #[serde(default)] homepage: Option, @@ -203,6 +209,8 @@ struct Raw { #[serde(default)] change_notes: Option, #[serde(default)] + change_notes_file: Option, + #[serde(default)] categories: Vec, #[serde(default)] icon: Option, @@ -286,10 +294,12 @@ impl Manifest { name: raw.name, version: raw.version, description: raw.description, + description_file: raw.description_file, authors: raw.authors, homepage: raw.homepage, license: raw.license, change_notes: raw.change_notes, + change_notes_file: raw.change_notes_file, declared_categories: raw.categories, icon: raw.icon, icon_dark: raw.icon_dark, @@ -347,6 +357,14 @@ impl Manifest { self.needs_api("`icon`", 2)?; check_relative(icon, "icon")?; } + if let Some(path) = &self.description_file { + self.needs_api("`description-file`", 18)?; + check_relative(path, "description-file")?; + } + if let Some(path) = &self.change_notes_file { + self.needs_api("`change-notes-file`", 18)?; + check_relative(path, "change-notes-file")?; + } for cap in self.capabilities.required.iter().chain(&self.capabilities.optional) { if matches!( cap, @@ -1005,4 +1023,27 @@ mod net_ask_api_tests { } } } + + #[test] + fn doc_files_require_api_1_18_and_relative_paths() { + for field in ["description-file", "change-notes-file"] { + for engine in ["^1.17", "^1.18"] { + let manifest = format!( + "id = 'test'\nname = 'Test'\nversion = '0.1.0'\nengines.openidea = '{engine}'\n{field} = 'docs.md'\n" + ); + let parsed = Manifest::parse(&manifest); + if engine == "^1.18" { + parsed.unwrap(); + } else { + assert!(parsed.unwrap_err().contains("new in plugin API 1.18"), "{field} {engine}"); + } + } + for bad in ["../escape.md", "/abs/path.md"] { + let manifest = format!( + "id = 'test'\nname = 'Test'\nversion = '0.1.0'\nengines.openidea = '^1.18'\n{field} = '{bad}'\n" + ); + assert!(Manifest::parse(&manifest).unwrap_err().contains("relative path"), "{field} {bad}"); + } + } + } } diff --git a/crates/ide-extension/src/package.rs b/crates/ide-extension/src/package.rs index 37ed1faafc..7ab9bb746c 100644 --- a/crates/ide-extension/src/package.rs +++ b/crates/ide-extension/src/package.rs @@ -27,6 +27,7 @@ use crate::MANIFEST_FILE; use base64::Engine as _; use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; use std::io::{Read, Write}; use std::path::{Component, Path, PathBuf}; @@ -331,6 +332,9 @@ pub struct IndexEntry { pub version: String, #[serde(default)] pub description: String, + /// Localized descriptions keyed by BCP 47 language tag (e.g. `zh-CN`). + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub description_locales: BTreeMap, #[serde(default)] pub authors: Vec, pub publisher: String, @@ -358,6 +362,9 @@ pub struct IndexEntry { /// This version's release notes (the manifest's `change-notes`). #[serde(default)] pub notes: Option, + /// Localized release notes keyed by BCP 47 language tag (e.g. `zh-CN`). + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub notes_locales: BTreeMap, /// Downloads of the plugin's packages, as counted by whoever serves them. #[serde(default)] pub downloads: Option, @@ -715,6 +722,7 @@ mod tests { name: id.into(), version: "1.0.0".into(), description: String::new(), + description_locales: BTreeMap::new(), authors: Vec::new(), publisher: publisher.into(), download: format!("https://example.com/{id}.oiplugin"), @@ -725,6 +733,7 @@ mod tests { icon: None, homepage: None, notes: None, + notes_locales: BTreeMap::new(), downloads: None, featured: false, suggest: Vec::new(), diff --git a/crates/ide-host/src/bin/openidea-plugin/main.rs b/crates/ide-host/src/bin/openidea-plugin/main.rs index 3a740886cd..d696a1e9ab 100644 --- a/crates/ide-host/src/bin/openidea-plugin/main.rs +++ b/crates/ide-host/src/bin/openidea-plugin/main.rs @@ -22,7 +22,9 @@ mod templates; use ide_extension::{Manifest, validate_plugin_id}; -use ide_host::plugins::{PluginHost, market_href_reachable_from, plugin_icon, read_market_url, resolve_market_href}; +use ide_host::plugins::{ + PluginHost, market_href_reachable_from, plugin_docs, plugin_icon, read_market_url, resolve_market_href, +}; use ide_plugin::{Limits, PluginEngine}; use std::path::{Path, PathBuf}; use std::process::{Command, ExitCode}; @@ -641,12 +643,15 @@ fn cmd_index(args: &[String]) -> Result<(), String> { Some(wasm) => engine.check_component(&engine.compile(&scratch.join(wasm))?)?, None => None, }; + let pkg = ide_extension::Package::new(m.clone(), scratch.clone()); + let docs = plugin_docs(&pkg)?; let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); Ok::<_, String>(IndexEntry { id: m.id.clone(), name: m.name.clone(), version: m.version.clone(), - description: m.description.clone(), + description: docs.description, + description_locales: docs.description_locales, authors: m.authors.clone(), publisher: signer, download: base.map_or_else(|| file.clone(), |b| format!("{b}/{file}")), @@ -654,9 +659,10 @@ fn cmd_index(args: &[String]) -> Result<(), String> { capabilities: m.capabilities.all().map(|c| c.to_string()).collect(), engine: package::engine_requirement(&m.engine, built_for.as_ref()), categories: m.categories(), - icon: plugin_icon(&ide_extension::Package::new(m.clone(), scratch.clone()))?, + icon: plugin_icon(&pkg)?, homepage: m.homepage.clone().filter(|h| !h.trim().is_empty()), - notes: m.change_notes.clone().filter(|n| !n.trim().is_empty()), + notes: docs.change_notes.filter(|n| !n.trim().is_empty()), + notes_locales: docs.change_notes_locales, downloads: None, featured: false, suggest: Vec::new(), @@ -1078,6 +1084,62 @@ mod tests { assert!(index.plugins[0].icon.as_ref().expect("icon").light.contains(".json` and sibling `..` files. + +use ide_extension::{LOCALES_DIR, Manifest, Package, check_relative}; +use serde_json::Value; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +/// Maximum size of a single Markdown documentation file referenced by a manifest. +pub const MAX_PLUGIN_DOC: usize = 256 << 10; + +/// Resolved Overview and What's New texts of a plugin package, plus the package +/// files they reference. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PluginDocs { + pub description: String, + pub change_notes: Option, + pub description_locales: BTreeMap, + pub change_notes_locales: BTreeMap, + /// Package-relative Markdown files referenced (base + localized siblings). + pub files: Vec, +} + +impl PluginDocs { + pub fn from_manifest(manifest: &Manifest) -> Self { + Self { + description: manifest.description.clone(), + change_notes: manifest.change_notes.clone(), + description_locales: BTreeMap::new(), + change_notes_locales: BTreeMap::new(), + files: Vec::new(), + } + } +} + +pub(super) fn locale_tag_ok(tag: &str) -> bool { + let mut parts = tag.split('-'); + let language = parts.next().unwrap_or_default(); + (2..=3).contains(&language.len()) + && language.chars().all(|c| c.is_ascii_alphabetic()) + && parts.all(|p| (1..=8).contains(&p.len()) && p.chars().all(|c| c.is_ascii_alphanumeric())) +} + +fn is_markdown_path(path: &Path) -> bool { + path.extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case("md") || e.eq_ignore_ascii_case("markdown")) +} + +fn read_markdown_file(pkg: &Package, path: &Path, what: &str) -> Result { + check_relative(path, what)?; + if !is_markdown_path(path) { + return Err(format!("{what} {:?}: must be a .md or .markdown file", path.display())); + } + let text = pkg.read_text(path)?; + if text.len() > MAX_PLUGIN_DOC { + return Err(format!("{}: larger than {} KiB", path.display(), MAX_PLUGIN_DOC >> 10)); + } + Ok(text) +} + +/// Discovers sibling `..` Markdown files next to `base` (e.g. +/// `description.zh-CN.md` next to `description.md`), validates each one, and +/// returns `(tag -> text, relative_files)`. +fn discover_localized_markdown( + pkg: &Package, + base: &Path, + what: &str, +) -> Result<(BTreeMap, Vec), String> { + let Some(stem) = base.file_stem().and_then(|s| s.to_str()) else { + return Ok((BTreeMap::new(), Vec::new())); + }; + let Some(ext) = base.extension().and_then(|e| e.to_str()) else { + return Ok((BTreeMap::new(), Vec::new())); + }; + let parent_rel = base.parent().unwrap_or_else(|| Path::new("")); + let parent_dir = pkg.dir.join(parent_rel); + let Ok(entries) = std::fs::read_dir(&parent_dir) else { + return Ok((BTreeMap::new(), Vec::new())); + }; + let mut names: Vec = entries.filter_map(|e| e.ok()?.file_name().into_string().ok()).collect(); + names.sort(); + + let prefix = format!("{stem}."); + let suffix_len = ext.len() + 1; // "." + let mut localized = BTreeMap::new(); + let mut files = Vec::new(); + for name in names { + if name.len() <= prefix.len() + suffix_len || !name.starts_with(&prefix) { + continue; + } + let Some((before_ext, file_ext)) = name.rsplit_once('.') else { + continue; + }; + if !file_ext.eq_ignore_ascii_case(ext) { + continue; + } + let Some(tag) = before_ext.strip_prefix(&prefix) else { + continue; + }; + if !locale_tag_ok(tag) { + continue; + } + let rel = if parent_rel.as_os_str().is_empty() { PathBuf::from(&name) } else { parent_rel.join(&name) }; + let text = read_markdown_file(pkg, &rel, what)?; + localized.insert(tag.to_owned(), text); + files.push(rel); + } + Ok((localized, files)) +} + +/// Reads valid `locales/.json` catalogs from `pkg` (malformed catalogs are +/// ignored here and reported by `ui_points::locales` during `prepare`). +fn read_locale_catalogs(pkg: &Package) -> BTreeMap> { + let dir = Path::new(LOCALES_DIR); + let Ok(entries) = std::fs::read_dir(pkg.dir.join(dir)) else { + return BTreeMap::new(); + }; + let mut out = BTreeMap::new(); + for entry in entries.flatten() { + let Ok(name) = entry.file_name().into_string() else { continue }; + let Some(tag) = name.strip_suffix(".json") else { continue }; + if !locale_tag_ok(tag) { + continue; + } + let Ok(text) = pkg.read_text(&dir.join(&name)) else { continue }; + let Ok(raw) = serde_json::from_str::>(&text) else { continue }; + let catalog: BTreeMap = + raw.into_iter().filter_map(|(k, v)| v.as_str().map(|s| (k, s.to_owned()))).collect(); + out.insert(tag.to_owned(), catalog); + } + out +} + +fn lookup_translation<'a>(catalog: &'a BTreeMap, source: &str) -> Option<&'a str> { + if let Some(v) = catalog.get(source) { + return Some(v.as_str()); + } + let trimmed = source.trim(); + if trimmed != source { + return catalog.get(trimmed).map(String::as_str); + } + None +} + +/// Reads and validates a plugin package's Overview (`description` / `description-file`) +/// and What's New (`change-notes` / `change-notes-file`), along with their +/// per-locale translations from `locales/.json` and localized Markdown siblings. +pub fn plugin_docs(pkg: &Package) -> Result { + let mut files = Vec::new(); + let description = match &pkg.manifest.description_file { + Some(path) => { + let text = read_markdown_file(pkg, path, "description-file")?; + files.push(path.clone()); + text + } + None => pkg.manifest.description.clone(), + }; + let change_notes = match &pkg.manifest.change_notes_file { + Some(path) => { + let text = read_markdown_file(pkg, path, "change-notes-file")?; + files.push(path.clone()); + Some(text).filter(|s| !s.trim().is_empty()) + } + None => pkg.manifest.change_notes.clone(), + }; + + let mut description_locales = BTreeMap::new(); + let mut change_notes_locales = BTreeMap::new(); + + for (tag, catalog) in read_locale_catalogs(pkg) { + if !description.trim().is_empty() + && let Some(tr) = lookup_translation(&catalog, &description) + { + description_locales.insert(tag.clone(), tr.to_owned()); + } + if let Some(notes) = &change_notes + && !notes.trim().is_empty() + && let Some(tr) = lookup_translation(&catalog, notes) + { + change_notes_locales.insert(tag.clone(), tr.to_owned()); + } + } + + if let Some(path) = &pkg.manifest.description_file { + let (localized, extra_files) = discover_localized_markdown(pkg, path, "description-file")?; + description_locales.extend(localized); + files.extend(extra_files); + } + if let Some(path) = &pkg.manifest.change_notes_file { + let (localized, extra_files) = discover_localized_markdown(pkg, path, "change-notes-file")?; + change_notes_locales.extend(localized); + files.extend(extra_files); + } + + files.sort(); + files.dedup(); + Ok(PluginDocs { description, change_notes, description_locales, change_notes_locales, files }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pkg_with(dir: &Path, extra_toml: &str) -> Package { + let src = format!( + "id = \"acme.docs\"\nname = \"Docs\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.18\"\n{extra_toml}" + ); + let manifest = Manifest::parse(&src).unwrap(); + Package::new(manifest, dir.to_path_buf()) + } + + #[test] + fn inline_fields_and_locale_catalog_translations() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(tmp.path().join("locales")).unwrap(); + std::fs::write( + tmp.path().join("locales/zh-CN.json"), + r#"{ + "Plain description.": "纯文本描述。", + "0.2.0 — fixes\n0.1.0 — init": "0.2.0 — 修复\n0.1.0 — 初始版本" + }"#, + ) + .unwrap(); + let pkg = pkg_with( + tmp.path(), + "description = \"Plain description.\"\nchange-notes = \"\"\"\n0.2.0 — fixes\n0.1.0 — init\n\"\"\"\n", + ); + let docs = plugin_docs(&pkg).unwrap(); + assert_eq!(docs.description, "Plain description."); + assert_eq!(docs.description_locales.get("zh-CN").map(String::as_str), Some("纯文本描述。")); + assert_eq!(docs.change_notes_locales.get("zh-CN").map(String::as_str), Some("0.2.0 — 修复\n0.1.0 — 初始版本")); + assert!(docs.files.is_empty()); + } + + #[test] + fn markdown_files_and_localized_siblings_are_loaded_and_tracked() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(tmp.path().join("docs")).unwrap(); + std::fs::create_dir_all(tmp.path().join("locales")).unwrap(); + std::fs::write(tmp.path().join("docs/overview.md"), "# English Overview\n\n- Item 1\n").unwrap(); + std::fs::write(tmp.path().join("docs/overview.zh-CN.md"), "# 中文概览\n\n- 条目 1\n").unwrap(); + std::fs::write(tmp.path().join("docs/overview.fr.md"), "# Aperçu\n").unwrap(); + std::fs::write(tmp.path().join("CHANGELOG.md"), "## 1.0.0\n\n- Initial\n").unwrap(); + std::fs::write(tmp.path().join("CHANGELOG.zh-CN.md"), "## 1.0.0\n\n- 首发\n").unwrap(); + // Sibling localized .md takes precedence over locales/.json for the same tag. + std::fs::write(tmp.path().join("locales/zh-CN.json"), r##"{ "# English Overview\n\n- Item 1": "from json" }"##) + .unwrap(); + + let pkg = + pkg_with(tmp.path(), "description-file = \"docs/overview.md\"\nchange-notes-file = \"CHANGELOG.md\"\n"); + let docs = plugin_docs(&pkg).unwrap(); + assert_eq!(docs.description, "# English Overview\n\n- Item 1\n"); + assert_eq!(docs.description_locales.get("zh-CN").map(String::as_str), Some("# 中文概览\n\n- 条目 1\n")); + assert_eq!(docs.description_locales.get("fr").map(String::as_str), Some("# Aperçu\n")); + assert_eq!(docs.change_notes.as_deref(), Some("## 1.0.0\n\n- Initial\n")); + assert_eq!(docs.change_notes_locales.get("zh-CN").map(String::as_str), Some("## 1.0.0\n\n- 首发\n")); + assert_eq!( + docs.files, + vec![ + PathBuf::from("CHANGELOG.md"), + PathBuf::from("CHANGELOG.zh-CN.md"), + PathBuf::from("docs/overview.fr.md"), + PathBuf::from("docs/overview.md"), + PathBuf::from("docs/overview.zh-CN.md"), + ] + ); + } + + #[test] + fn rejects_missing_non_markdown_non_utf8_and_oversized_files() { + let tmp = tempfile::tempdir().unwrap(); + + // Missing file + let missing = pkg_with(tmp.path(), "description-file = \"missing.md\"\n"); + assert!(plugin_docs(&missing).unwrap_err().contains("no such file")); + + // Non-markdown extension + std::fs::write(tmp.path().join("notes.txt"), "hello").unwrap(); + let bad_ext = pkg_with(tmp.path(), "change-notes-file = \"notes.txt\"\n"); + assert!(plugin_docs(&bad_ext).unwrap_err().contains(".md or .markdown")); + + // Invalid UTF-8 in localized sibling + std::fs::write(tmp.path().join("description.md"), "# OK\n").unwrap(); + std::fs::write(tmp.path().join("description.zh-CN.md"), [0xff, 0xfe, 0xfd]).unwrap(); + let bad_utf8 = pkg_with(tmp.path(), "description-file = \"description.md\"\n"); + assert!(plugin_docs(&bad_utf8).unwrap_err().contains("not UTF-8")); + std::fs::remove_file(tmp.path().join("description.zh-CN.md")).unwrap(); + + // Oversized file + let huge = "a".repeat(MAX_PLUGIN_DOC + 1); + std::fs::write(tmp.path().join("CHANGELOG.md"), huge).unwrap(); + let oversized = pkg_with(tmp.path(), "change-notes-file = \"CHANGELOG.md\"\n"); + assert!(plugin_docs(&oversized).unwrap_err().contains("larger than")); + } +} diff --git a/crates/ide-host/src/plugins/mod.rs b/crates/ide-host/src/plugins/mod.rs index 00d78e5097..9f8a0e5a11 100644 --- a/crates/ide-host/src/plugins/mod.rs +++ b/crates/ide-host/src/plugins/mod.rs @@ -24,7 +24,8 @@ mod console_rules; mod database; mod dependencies; pub(crate) mod diagnostics; -pub mod endpoints; +pub mod docs; +mod endpoints; mod event_paths; mod execution; mod external_watch; @@ -65,6 +66,7 @@ mod websocket; pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore}; pub use build_graph::{BuildGraph, GradleModule}; +pub use docs::{MAX_PLUGIN_DOC, PluginDocs, plugin_docs}; pub(crate) use hover::merge as merge_hover; pub use icons::{ MAX_PLUGIN_ICON, map_asset as icon_theme_map_asset, plugin_icon, sanitize_svg, svg_prefix as icon_theme_svg_prefix, @@ -229,6 +231,8 @@ struct LoadedPlugin { pkg: Package, /// Read at load so disabled and failed plugins show it too. icon: Option, + /// Resolved Overview / What's New docs and their locale variants. + docs: PluginDocs, /// The manifest failed to parse: `pkg` is a placeholder. invalid: bool, source: PluginSource, @@ -594,6 +598,7 @@ impl PluginHost { self.plugins.write().insert( pending.id, Arc::new(LoadedPlugin { + docs: PluginDocs::from_manifest(&manifest), pkg: Package::new(manifest, dir), icon: None, invalid: false, @@ -952,11 +957,12 @@ impl PluginHost { }; let needs_consent = grant.is_none() || publisher.is_none() || signer_changed || !capabilities.iter().all(answered); + let docs = plugin_docs(&pkg).unwrap_or_else(|_| PluginDocs::from_manifest(m)); Ok(InstallPreview { id: m.id.clone(), name: m.name.clone(), version: m.version.clone(), - description: m.description.clone(), + description: docs.description, authors: m.authors.clone(), has_code: m.wasm.is_some(), capabilities, @@ -2758,6 +2764,7 @@ impl PluginHost { .filter(|w| !dir.join(w).is_file()) .map(|w| format!("{} is missing; build the plugin first", w.display())), }; + let docs = plugin_docs(&pkg).unwrap_or_else(|_| PluginDocs::from_manifest(&m)); out.push(CatalogPlugin { has_code: m.wasm.is_some(), capabilities: m @@ -2769,10 +2776,12 @@ impl PluginHost { id: m.id, name: m.name, version: m.version, - description: m.description, + description: docs.description, + description_locales: docs.description_locales, authors: m.authors, homepage: m.homepage, - change_notes: m.change_notes, + change_notes: docs.change_notes, + change_notes_locales: docs.change_notes_locales, icon: plugin_icon(&pkg).ok().flatten(), path: dir.into(), problem, @@ -2881,15 +2890,16 @@ impl PluginHost { self.plugins.read().values().any(|p| p.dir() == dir) } - /// Validates the manifest's icon and every declaration of `pkg`; the - /// icon files join the package files the declarations reference. + /// Validates the manifest's icon, docs and every declaration of `pkg`; the + /// icon and doc files join the package files the declarations reference. fn prepare(&self, pkg: &Package) -> Result { plugin_icon(pkg)?; + let docs = plugin_docs(pkg)?; let mut set = self.registry.prepare(pkg)?; check_setting_grants(pkg)?; - for icon in [&pkg.manifest.icon, &pkg.manifest.icon_dark].into_iter().flatten() { - if !set.files.contains(icon) { - set.files.push(icon.clone()); + for file in [&pkg.manifest.icon, &pkg.manifest.icon_dark].into_iter().flatten().chain(&docs.files) { + if !set.files.contains(file) { + set.files.push(file.clone()); } } Ok(set) @@ -2956,8 +2966,10 @@ impl PluginHost { // Installed copies don't change: their validated UI declarations are indexed. pkg = pkg.with_digest(digest.trim()); } + let docs = plugin_docs(&pkg).unwrap_or_else(|_| PluginDocs::from_manifest(&pkg.manifest)); let plugin = Arc::new(LoadedPlugin { icon: plugin_icon(&pkg).ok().flatten(), + docs, pkg, invalid, source, @@ -3571,10 +3583,12 @@ impl PluginHost { id: m.id.clone(), name: m.name.clone(), version: m.version.clone(), - description: m.description.clone(), + description: p.docs.description.clone(), + description_locales: p.docs.description_locales.clone(), authors: m.authors.clone(), homepage: m.homepage.clone(), - change_notes: m.change_notes.clone(), + change_notes: p.docs.change_notes.clone(), + change_notes_locales: p.docs.change_notes_locales.clone(), icon: p.icon.clone(), java_agent: self.java_agents.for_plugin(&m.id).map(|agent| { let pin = self @@ -3760,10 +3774,12 @@ fn placeholder_manifest(dir: &Path) -> Manifest { name, version: "0.0.0".into(), description: String::new(), + description_file: None, authors: Vec::new(), homepage: None, license: None, change_notes: None, + change_notes_file: None, declared_categories: Vec::new(), icon: None, icon_dark: None, diff --git a/crates/ide-host/src/plugins/types.rs b/crates/ide-host/src/plugins/types.rs index 0095c62ec8..ae79f56b67 100644 --- a/crates/ide-host/src/plugins/types.rs +++ b/crates/ide-host/src/plugins/types.rs @@ -97,9 +97,13 @@ pub struct PluginInfo { pub name: String, pub version: String, pub description: String, + #[serde(default)] + pub description_locales: BTreeMap, pub authors: Vec, pub homepage: Option, pub change_notes: Option, + #[serde(default)] + pub change_notes_locales: BTreeMap, pub icon: Option, /// The Java agent this plugin declares, and whether it is still approved. pub java_agent: Option, @@ -207,9 +211,13 @@ pub struct CatalogPlugin { pub name: String, pub version: String, pub description: String, + #[serde(default)] + pub description_locales: BTreeMap, pub authors: Vec, pub homepage: Option, pub change_notes: Option, + #[serde(default)] + pub change_notes_locales: BTreeMap, pub icon: Option, /// Package directory; install with `install_from_dir(path)`. pub path: ide_core::IpcPath, diff --git a/crates/ide-host/tests/distribution.rs b/crates/ide-host/tests/distribution.rs index ea82cd6250..e809125c25 100644 --- a/crates/ide-host/tests/distribution.rs +++ b/crates/ide-host/tests/distribution.rs @@ -169,6 +169,7 @@ fn signed( name: "Hello".into(), version: version.into(), description: String::new(), + description_locales: Default::default(), authors: vec![], publisher: publisher.into(), download: out.file_name().unwrap().to_string_lossy().into_owned(), @@ -179,6 +180,7 @@ fn signed( icon: None, homepage: None, notes: None, + notes_locales: Default::default(), downloads: None, featured: false, suggest: vec![], diff --git a/docs/en/plugins/manifest.mdx b/docs/en/plugins/manifest.mdx index 0a8466c0cc..c911fdbbf2 100644 --- a/docs/en/plugins/manifest.mdx +++ b/docs/en/plugins/manifest.mdx @@ -41,24 +41,26 @@ mac = "Meta+Alt+C" ## Top-level fields -| Field | Required | Description | -| ------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `id` | Yes | Segments of `[a-z0-9][a-z0-9_-]*` joined by `.`, at most 64 characters. The part before the first `.` is the publisher namespace (`acme` in `acme.word-tools`); a signed package must use its publisher's prefix. | -| `name` | Yes | Display name. Must not be empty. | -| `version` | Yes | A semantic version such as `1.2.0`. | -| `description` | No | One or two sentences shown in Settings › Plugins and the marketplace. | -| `authors` | No | List of strings. | -| `homepage` | No | URL shown in the plugin's details. | -| `license` | No | License name, for example an SPDX id. | -| `change-notes` | No | Release notes shown under **What's New** in the plugin's details. | -| `categories` | No | Up to 3 marketplace categories (see below). | -| `icon` | No | Package SVG for Settings › Plugins and the marketplace. At most 16 KiB, sanitised (no scripts, external references or `foreignObject`); an invalid icon fails the package. Needs `engines.openidea = "^1.2"`. | -| `icon-dark` | No | Variant used with dark themes. Needs `icon`. | -| `engines.openidea` | Yes | A semver requirement on the plugin API, for example `"^1.4"`. The IDE refuses a package whose requirement doesn't match its API. See [API versions](/en/plugins/versioning). | -| `wasm` | No | Path of the component. Omit it for data-only plugins. | -| `activation` | No | Events that load the code (see below). Needs `wasm`. | -| `[capabilities]` | No | `required` and `optional` lists of capability strings. See [Permissions and capabilities](/en/plugins/capabilities). | -| `[contributes]` | No | Contribution points (see below). | +| Field | Required | Description | +| ------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `id` | Yes | Segments of `[a-z0-9][a-z0-9_-]*` joined by `.`, at most 64 characters. The part before the first `.` is the publisher namespace (`acme` in `acme.word-tools`); a signed package must use its publisher's prefix. | +| `name` | Yes | Display name. Must not be empty. | +| `version` | Yes | A semantic version such as `1.2.0`. | +| `description` | No | Plain text or Markdown shown under **Overview** in Settings › Plugins and the marketplace. | +| `description-file` | No | Package Markdown file (`.md` / `.markdown`, up to 256 KiB) for **Overview**. Sibling `..` files (e.g. `description.zh-CN.md`) provide per-language versions. Needs `engines.openidea = "^1.18"`. | +| `authors` | No | List of strings. | +| `homepage` | No | URL shown in the plugin's details. | +| `license` | No | License name, for example an SPDX id. | +| `change-notes` | No | Plain text or Markdown release notes shown under **What's New** in the plugin's details. | +| `change-notes-file` | No | Package Markdown file (`.md` / `.markdown`, up to 256 KiB) for **What's New**. Sibling `..` files (e.g. `CHANGELOG.zh-CN.md`) provide per-language versions. Needs `engines.openidea = "^1.18"`. | +| `categories` | No | Up to 3 marketplace categories (see below). | +| `icon` | No | Package SVG for Settings › Plugins and the marketplace. At most 16 KiB, sanitised (no scripts, external references or `foreignObject`); an invalid icon fails the package. Needs `engines.openidea = "^1.2"`. | +| `icon-dark` | No | Variant used with dark themes. Needs `icon`. | +| `engines.openidea` | Yes | A semver requirement on the plugin API, for example `"^1.4"`. The IDE refuses a package whose requirement doesn't match its API. See [API versions](/en/plugins/versioning). | +| `wasm` | No | Path of the component. Omit it for data-only plugins. | +| `activation` | No | Events that load the code (see below). Needs `wasm`. | +| `[capabilities]` | No | `required` and `optional` lists of capability strings. See [Permissions and capabilities](/en/plugins/capabilities). | +| `[contributes]` | No | Contribution points (see below). | Unknown top-level fields are an error. @@ -143,7 +145,7 @@ A package translates its own text with `locales/.json` files (`fr.json`, `z { "Count Words": "Compter les mots", "Refresh": "Actualiser" } ``` -The IDE applies the catalog of the selected UI language (the exact tag, then the language, then a variant such as `zh-TW` for `zh`) to the titles, categories, labels and tooltips the manifest declares, and to the text views show. Text the plugin builds itself (notifications, error messages, `html` bodies) is not translated: read `host::locale()` when building it. `openidea-plugin check` refuses a catalog that is not a JSON object of strings. +The IDE applies the catalog of the selected UI language (the exact tag, then the language, then a variant such as `zh-TW` for `zh`) to `description`, `change-notes`, the titles, categories, labels and tooltips the manifest declares, and to the text views show. For longer Overview and What's New documents referenced via `description-file` or `change-notes-file`, add sibling Markdown files such as `description.zh-CN.md` or `CHANGELOG.zh-CN.md` alongside the English file. Text the plugin builds itself (notifications, error messages, `html` bodies) is not translated: read `host::locale()` when building it. `openidea-plugin check` refuses a catalog that is not a JSON object of strings. ## The 0.1 format diff --git a/docs/zh/plugins/manifest.mdx b/docs/zh/plugins/manifest.mdx index adcaddfbe3..fc680d860d 100644 --- a/docs/zh/plugins/manifest.mdx +++ b/docs/zh/plugins/manifest.mdx @@ -41,24 +41,26 @@ mac = "Meta+Alt+C" ## 顶层字段 -| 字段 | 必填 | 说明 | -| ------------------ | ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `id` | 是 | 由 `.` 连接的若干段,每段匹配 `[a-z0-9][a-z0-9_-]*`,总长不超过 64。第一个 `.` 之前是发布者命名空间(`acme.word-tools` 中的 `acme`);签名的包必须使用其发布者的前缀。 | -| `name` | 是 | 显示名称,不能为空。 | -| `version` | 是 | 语义化版本,如 `1.2.0`。 | -| `description` | 否 | 一两句话,显示在 设置 › 插件 和插件市场中。 | -| `authors` | 否 | 字符串列表。 | -| `homepage` | 否 | 显示在插件详情中的 URL。 | -| `license` | 否 | 许可证名称,例如 SPDX 标识。 | -| `change-notes` | 否 | 发布说明,显示在插件详情的 **新功能** 中。 | -| `categories` | 否 | 最多 3 个插件市场分类(见下文)。 | -| `icon` | 否 | 插件包的 SVG 图标,用于 设置 › 插件 和插件市场。不超过 16 KiB,会被净化(不允许脚本、外部引用和 `foreignObject`);图标无效时整个包被拒绝。需要 `engines.openidea = "^1.2"`。 | -| `icon-dark` | 否 | 深色主题下使用的图标变体,需要同时有 `icon`。 | -| `engines.openidea` | 是 | 对插件 API 的 semver 版本要求,例如 `"^1.4"`。要求与 IDE 的 API 不匹配时,IDE 拒绝这个包。见 [API 版本与兼容](/zh/plugins/versioning)。 | -| `wasm` | 否 | 组件路径。纯数据插件不写。 | -| `activation` | 否 | 触发加载代码的事件(见下文),需要有 `wasm`。 | -| `[capabilities]` | 否 | `required` 和 `optional` 两个能力字符串列表。见 [权限与能力](/zh/plugins/capabilities)。 | -| `[contributes]` | 否 | 贡献点(见下文)。 | +| 字段 | 必填 | 说明 | +| ------------------- | ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `id` | 是 | 由 `.` 连接的若干段,每段匹配 `[a-z0-9][a-z0-9_-]*`,总长不超过 64。第一个 `.` 之前是发布者命名空间(`acme.word-tools` 中的 `acme`);签名的包必须使用其发布者的前缀。 | +| `name` | 是 | 显示名称,不能为空。 | +| `version` | 是 | 语义化版本,如 `1.2.0`。 | +| `description` | 否 | 纯文本或 Markdown,显示在 设置 › 插件 的 **概览** 和插件市场中。 | +| `description-file` | 否 | 包内 Markdown 文件(`.md` / `.markdown`,不超过 256 KiB),用于 **概览**。同目录的 `..` 文件(如 `description.zh-CN.md`)提供对应语言版本。需要 `engines.openidea = "^1.18"`。 | +| `authors` | 否 | 字符串列表。 | +| `homepage` | 否 | 显示在插件详情中的 URL。 | +| `license` | 否 | 许可证名称,例如 SPDX 标识。 | +| `change-notes` | 否 | 纯文本或 Markdown 发布说明,显示在插件详情的 **新功能** 中。 | +| `change-notes-file` | 否 | 包内 Markdown 文件(`.md` / `.markdown`,不超过 256 KiB),用于 **新功能**。同目录的 `..` 文件(如 `CHANGELOG.zh-CN.md`)提供对应语言版本。需要 `engines.openidea = "^1.18"`。 | +| `categories` | 否 | 最多 3 个插件市场分类(见下文)。 | +| `icon` | 否 | 插件包的 SVG 图标,用于 设置 › 插件 和插件市场。不超过 16 KiB,会被净化(不允许脚本、外部引用和 `foreignObject`);图标无效时整个包被拒绝。需要 `engines.openidea = "^1.2"`。 | +| `icon-dark` | 否 | 深色主题下使用的图标变体,需要同时有 `icon`。 | +| `engines.openidea` | 是 | 对插件 API 的 semver 版本要求,例如 `"^1.4"`。要求与 IDE 的 API 不匹配时,IDE 拒绝这个包。见 [API 版本与兼容](/zh/plugins/versioning)。 | +| `wasm` | 否 | 组件路径。纯数据插件不写。 | +| `activation` | 否 | 触发加载代码的事件(见下文),需要有 `wasm`。 | +| `[capabilities]` | 否 | `required` 和 `optional` 两个能力字符串列表。见 [权限与能力](/zh/plugins/capabilities)。 | +| `[contributes]` | 否 | 贡献点(见下文)。 | 未知的顶层字段会报错。 @@ -143,7 +145,7 @@ optional = ["net:api.openai.com", "secrets"] { "Count Words": "Compter les mots", "Refresh": "Actualiser" } ``` -IDE 根据当前界面语言选用目录(先精确匹配 tag,再匹配语言,再匹配变体,例如 `zh` 可以用 `zh-TW`),应用到清单声明的标题、分类、标签、提示,以及视图显示的文本。插件自己拼出来的文本(通知、错误信息、`html` 内容)不会被翻译:生成这些文本时读取 `host::locale()`。如果目录不是“字符串到字符串”的 JSON 对象,`openidea-plugin check` 会拒绝它。 +IDE 根据当前界面语言选用目录(先精确匹配 tag,再匹配语言,再匹配变体,例如 `zh` 可以用 `zh-TW`),应用到 `description`、`change-notes`、清单声明的标题、分类、标签、提示,以及视图显示的文本。对于通过 `description-file` 或 `change-notes-file` 引用的长文档,可在英文文件同目录放置对应语言的 Markdown 文件(如 `description.zh-CN.md`、`CHANGELOG.zh-CN.md`)。插件自己拼出来的文本(通知、错误信息、`html` 内容)不会被翻译:生成这些文本时读取 `host::locale()`。如果目录不是“字符串到字符串”的 JSON 对象,`openidea-plugin check` 会拒绝它。 ## 0.1 格式 diff --git a/src/bindings.ts b/src/bindings.ts index cbcda8f292..ea11dc6c07 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -4448,9 +4448,11 @@ export type CatalogPlugin = { name: string, version: string, description: string, + descriptionLocales?: { [key in string]: string }, authors: string[], homepage: string | null, changeNotes: string | null, + changeNotesLocales?: { [key in string]: string }, icon: PluginIcon | null, /** Package directory; install with `install_from_dir(path)`. */ path: IpcPath, @@ -8941,6 +8943,8 @@ export type IndexEntry = { name: string, version: string, description?: string, + /** Localized descriptions keyed by BCP 47 language tag (e.g. `zh-CN`). */ + descriptionLocales?: { [key in string]: string }, authors?: string[], publisher: string, /** The package, relative to the index (or an absolute URL). */ @@ -8965,6 +8969,8 @@ export type IndexEntry = { homepage?: string | null, /** This version's release notes (the manifest's `change-notes`). */ notes?: string | null, + /** Localized release notes keyed by BCP 47 language tag (e.g. `zh-CN`). */ + notesLocales?: { [key in string]: string }, /** Downloads of the plugin's packages, as counted by whoever serves them. */ downloads?: number | null, /** Picked by the marketplace's maintainers. */ @@ -11606,9 +11612,11 @@ export type PluginInfo = { name: string, version: string, description: string, + descriptionLocales?: { [key in string]: string }, authors: string[], homepage: string | null, changeNotes: string | null, + changeNotesLocales?: { [key in string]: string }, icon: PluginIcon | null, /** The Java agent this plugin declares, and whether it is still approved. */ javaAgent: PluginJavaAgent | null, diff --git a/src/features/plugins/PluginsPage.module.css b/src/features/plugins/PluginsPage.module.css index dfcedd588f..c377af0581 100644 --- a/src/features/plugins/PluginsPage.module.css +++ b/src/features/plugins/PluginsPage.module.css @@ -261,11 +261,95 @@ } .notes { margin: 10px 0 0; + max-width: 640px; color: var(--fg); font: inherit; - white-space: pre-wrap; overflow-wrap: anywhere; } +.markdown { + line-height: 1.55; + overflow-wrap: anywhere; +} +.markdownPlain { + white-space: pre-wrap; +} +.markdown > :first-child { + margin-top: 0; +} +.markdown > :last-child { + margin-bottom: 0; +} +.markdown :where(h1, h2, h3, h4, h5, h6) { + margin: 14px 0 6px; + color: var(--fg-strong); + font-weight: 600; + line-height: 1.3; +} +.markdown :where(h1) { + font-size: 1.25em; +} +.markdown :where(h2) { + font-size: 1.125em; +} +.markdown :where(h3, h4, h5, h6) { + font-size: 1em; +} +.markdown :where(p) { + margin: 0 0 8px; +} +.markdown :where(ul, ol) { + margin: 0 0 8px; + padding-left: 20px; +} +.markdown :where(li) { + margin: 2px 0; +} +.markdown :where(a) { + color: var(--link); + text-decoration: none; +} +.markdown :where(a:hover) { + color: var(--link-hover); + text-decoration: underline; +} +.markdown :where(code) { + padding: 1px 4px; + border-radius: var(--radius-small); + background: var(--bg-input); + font-family: var(--font-mono); + font-size: var(--fs-code); +} +.markdown :where(pre) { + overflow: auto; + margin: 0 0 10px; + padding: 8px 10px; + border-radius: var(--radius-small); + background: var(--bg-input); +} +.markdown :where(pre code) { + padding: 0; + background: none; +} +.markdown :where(blockquote) { + margin: 0 0 8px; + padding-left: 10px; + border-left: 2px solid var(--border-strong); + color: var(--fg-secondary); +} +.markdown :where(hr) { + height: 1px; + margin: 12px 0; + border: 0; + background: var(--border); +} +.markdown :where(table) { + margin: 0 0 10px; + border-collapse: collapse; +} +.markdown :where(th, td) { + padding: 4px 8px; + border: 1px solid var(--border); +} .titleLine { display: flex; align-items: center; diff --git a/src/features/plugins/PluginsPage.tsx b/src/features/plugins/PluginsPage.tsx index 3b78936902..ebc275ec71 100644 --- a/src/features/plugins/PluginsPage.tsx +++ b/src/features/plugins/PluginsPage.tsx @@ -73,7 +73,8 @@ import { createPortal } from "react-dom"; import styles from "./PluginsPage.module.css"; import { pluginsBackend } from "./backend"; import { confirm } from "@/workbench/messages"; -import { tx } from "@/platform/i18n"; +import { tx, useI18n } from "@/platform/i18n"; +import { PluginMarkdown, localizePluginText } from "./pluginMarkdown"; const STATUS: Record< PluginStatus, @@ -124,14 +125,26 @@ export function filterPlugins(plugins: readonly PluginInfo[], query: string): Pl const q = query.trim().toLowerCase(); if (!q) return [...plugins]; return plugins.filter((p) => - matches([p.name, p.id, p.description, ...p.authors, ...p.contributions.map((c) => c.label)], q), + matches( + [ + p.name, + p.id, + p.description, + ...Object.values(p.descriptionLocales ?? {}), + ...p.authors, + ...p.contributions.map((c) => c.label), + ], + q, + ), ); } export function filterCatalog(catalog: readonly CatalogPlugin[], query: string): CatalogPlugin[] { const q = query.trim().toLowerCase(); if (!q) return [...catalog]; - return catalog.filter((p) => matches([p.name, p.id, p.description, ...p.authors], q)); + return catalog.filter((p) => + matches([p.name, p.id, p.description, ...Object.values(p.descriptionLocales ?? {}), ...p.authors], q), + ); } /** What the Available tab offers for a catalog package given what is installed. */ @@ -441,8 +454,8 @@ function DetailTabs({ notes, overview }: { notes: string | null; overview: React /> {tab === "overview" ? ( overview - ) : notes ? ( -
{notes.trim()}
+ ) : notes?.trim() ? ( + ) : (

This version has no release notes. @@ -775,6 +788,8 @@ function authorContacts(entries: readonly string[]) { } function InstalledDetails({ plugin }: { plugin: PluginInfo }) { + const locale = useI18n((s) => s.locale); + const t = usePluginT(plugin.id); const busy = usePlugins((s) => !!s.busy[plugin.id]); const installing = usePlugins((s) => s.installing); const update = useMarketUpdate(plugin); @@ -783,6 +798,10 @@ function InstalledDetails({ plugin }: { plugin: PluginInfo }) { const [confirmUninstall, setConfirmUninstall] = useState(false); const { authors, emails } = authorContacts(plugin.authors); const author = vendorOf(authors) || plugin.publisher; + const description = + localizePluginText(null, plugin.descriptionLocales, locale) ?? (plugin.description ? t(plugin.description) : null); + const notes = + localizePluginText(null, plugin.changeNotesLocales, locale) ?? (plugin.changeNotes ? t(plugin.changeNotes) : null); const toggle = (