Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Preferences: a Plugins page lists installed plugin folders (#2718)

Thodoris Tsagkogeorgasde7fabc3bc64
diff --git a/assets/locales/en.json b/assets/locales/en.json
index 7557c6b443..54d6af1433 100644
--- a/assets/locales/en.json
+++ b/assets/locales/en.json
@@ -1410,6 +1410,12 @@
"ui.placement": "Placement",
"ui.plane": "Plane",
"ui.plane_at_angle": "Plane at Angle",
+ "ui.plugins": "Plugins",
+ "ui.plugins_desktop": "Plugins are available in the desktop app.",
+ "ui.plugins_empty": "No plugins installed.",
+ "ui.plugins_note": "Each plugin is a folder inside {path} with a plugin.json. SolidCraft reads that file and does not run any code from the folder. Turning a plugin off keeps it installed.",
+ "ui.plugins_skipped": "{count} folder(s) could not be read.",
+ "ui.plugins_version": "{version}",
"ui.point": "Point",
"ui.point_under_the_cursor": "Point under the cursor",
"ui.points": "Points",
diff --git a/assets/locales/ja.json b/assets/locales/ja.json
index ba6fbfe048..d2413d6280 100644
--- a/assets/locales/ja.json
+++ b/assets/locales/ja.json
@@ -1410,6 +1410,12 @@
"ui.placement": "配置",
"ui.plane": "平面",
"ui.plane_at_angle": "傾斜平面",
+ "ui.plugins": "プラグイン",
+ "ui.plugins_desktop": "プラグインはデスクトップ版で使えます。",
+ "ui.plugins_empty": "プラグインは入っていません。",
+ "ui.plugins_note": "プラグインは {path} の中のフォルダで、plugin.json を置きます。SolidCraft はそのファイルを読むだけで、フォルダのコードは実行しません。オフにしてもインストールは残ります。",
+ "ui.plugins_skipped": "{count} 個のフォルダを読めませんでした。",
+ "ui.plugins_version": "{version}",
"ui.point": "点",
"ui.point_under_the_cursor": "カーソル下の点",
"ui.points": "点",
diff --git a/assets/locales/zh.json b/assets/locales/zh.json
index 8bfb7be4e6..822647cbca 100644
--- a/assets/locales/zh.json
+++ b/assets/locales/zh.json
@@ -1410,6 +1410,12 @@
"ui.placement": "放置",
"ui.plane": "平面",
"ui.plane_at_angle": "角度平面",
+ "ui.plugins": "插件",
+ "ui.plugins_desktop": "插件仅在桌面版中可用。",
+ "ui.plugins_empty": "尚未安装插件。",
+ "ui.plugins_note": "每个插件是 {path} 里的一个文件夹,其中有 plugin.json。SolidCraft 只读取该文件,不运行文件夹里的代码。关闭插件仍会保留安装。",
+ "ui.plugins_skipped": "有 {count} 个文件夹无法读取。",
+ "ui.plugins_version": "{version}",
"ui.point": "点",
"ui.point_under_the_cursor": "光标下的点",
"ui.points": "点",
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 595a674c74..90c09fe698 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -130,6 +130,7 @@ pub mod palette;
pub mod params_dialog;
pub(crate) mod pick_buffer;
pub(crate) mod pick_index;
+pub(crate) mod plugins;
pub mod prefs;
#[cfg(test)]
mod preselect_tests;
diff --git a/crates/ui-egui/src/plugins.rs b/crates/ui-egui/src/plugins.rs
new file mode 100644
index 0000000000..7a42066f57
--- /dev/null
+++ b/crates/ui-egui/src/plugins.rs
@@ -0,0 +1,256 @@
+//! Preferences › Plugins: packages installed under the per-user data folder.
+//!
+//! A plugin is a directory of `{data}/plugins/<id>/plugin.json`. This page reads that file and
+//! records which ids are turned off. It does not load or run anything from the folder. Running a
+//! plugin (the wasm host in docs/plugins.md) is a later step; it will honour `disabled_plugins`.
+
+use std::path::{Path, PathBuf};
+
+use egui::RichText;
+use serde::Deserialize;
+
+use crate::SolveApp;
+
+/// How many turned-off ids a preferences file may name.
+pub const MAX_DISABLED: usize = 256;
+/// `plugin.json` larger than this is refused.
+const MAX_MANIFEST_BYTES: u64 = 16 * 1024;
+
+/// One installed plugin, as its manifest describes it.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Plugin {
+ pub id: String,
+ pub name: String,
+ pub version: String,
+ pub description: String,
+}
+
+/// A folder under the plugins directory that is not a plugin.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Skipped {
+ pub folder: String,
+ pub reason: String,
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct Manifest {
+ id: String,
+ name: String,
+ version: String,
+ #[serde(default)]
+ description: String,
+}
+
+/// The plugins directory: `$XDG_DATA_HOME/solidcraft/plugins` (and the platform equivalents of
+/// [`solidcraft_engine::recovery::data_dir`]). `None` when that folder cannot be named.
+pub fn plugins_dir() -> Option<PathBuf> {
+ solidcraft_engine::recovery::data_dir().map(|d| d.join("plugins"))
+}
+
+/// An id a folder and a manifest may share: 1–64 characters, lowercase letters, digits and
+/// hyphens, not starting or ending with a hyphen.
+pub fn valid_id(id: &str) -> bool {
+ let b = id.as_bytes();
+ (1..=64).contains(&b.len())
+ && b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
+ && b[0] != b'-'
+ && *b.last().unwrap_or(&b'-') != b'-'
+}
+
+fn plain(text: &str, max: usize) -> bool {
+ !text.is_empty() && text.chars().count() <= max && text.chars().all(|c| !c.is_control())
+}
+
+fn check(m: Manifest, folder: &str) -> Result<Plugin, String> {
+ if m.id != folder {
+ return Err(format!("plugin.json id `{}` does not match the folder `{folder}`", m.id));
+ }
+ if !valid_id(&m.id) {
+ return Err("the id must be 1–64 lowercase letters, digits and hyphens".into());
+ }
+ let name = m.name.trim();
+ if !plain(name, 80) {
+ return Err("the name must be 1–80 characters with no line breaks".into());
+ }
+ let version = m.version.trim();
+ if !plain(version, 32) || !version.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+')) {
+ return Err("the version must be 1–32 letters, digits, dots, hyphens or plus signs".into());
+ }
+ let description = m.description.trim();
+ if description.chars().count() > 240 || description.chars().any(|c| c.is_control()) {
+ return Err("the description must be at most 240 characters with no line breaks".into());
+ }
+ Ok(Plugin { id: m.id, name: name.to_string(), version: version.to_string(), description: description.to_string() })
+}
+
+fn read_plugin(dir: &Path, folder: &str) -> Result<Plugin, String> {
+ let path = dir.join("plugin.json");
+ let meta = std::fs::metadata(&path).map_err(|_| "no plugin.json".to_string())?;
+ if !meta.is_file() || meta.len() > MAX_MANIFEST_BYTES {
+ return Err("plugin.json is missing or larger than 16 KiB".into());
+ }
+ let text = std::fs::read_to_string(&path).map_err(|e| format!("plugin.json could not be read ({e})"))?;
+ let manifest: Manifest = serde_json::from_str(&text).map_err(|e| format!("plugin.json is not a plugin manifest ({e})"))?;
+ check(manifest, folder)
+}
+
+/// The plugins in `dir`, and the folders that were not. A missing directory is an empty list.
+pub fn scan(dir: &Path) -> (Vec<Plugin>, Vec<Skipped>) {
+ let mut plugins = Vec::new();
+ let mut skipped = Vec::new();
+ let Ok(entries) = std::fs::read_dir(dir) else {
+ return (plugins, skipped);
+ };
+ for entry in entries.flatten() {
+ let Ok(kind) = entry.file_type() else { continue };
+ if !kind.is_dir() {
+ continue;
+ }
+ let Some(folder) = entry.file_name().into_string().ok() else {
+ skipped.push(Skipped { folder: String::new(), reason: "the folder name is not text".into() });
+ continue;
+ };
+ if folder.starts_with('.') {
+ continue;
+ }
+ match read_plugin(&entry.path(), &folder) {
+ Ok(plugin) => plugins.push(plugin),
+ Err(reason) => skipped.push(Skipped { folder, reason }),
+ }
+ }
+ plugins.sort_by(|a, b| a.name.cmp(&b.name).then(a.id.cmp(&b.id)));
+ skipped.sort_by(|a, b| a.folder.cmp(&b.folder));
+ (plugins, skipped)
+}
+
+/// Whether an installed plugin is offered. Unknown ids are on; an id in `disabled_plugins` is off.
+pub fn enabled(app: &SolveApp, id: &str) -> bool {
+ !app.preferences.disabled_plugins.contains(id)
+}
+
+/// The Plugins page. Desktop only: the browser build has no per-user plugin folder.
+pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
+ let t = crate::theme::Tokens::get();
+ if cfg!(target_arch = "wasm32") {
+ ui.label(crate::i18n::tr("ui.plugins_desktop"));
+ return;
+ }
+ let Some(dir) = plugins_dir() else {
+ ui.label(crate::i18n::tr("ui.plugins_desktop"));
+ return;
+ };
+ let path = dir.display().to_string();
+ ui.add(egui::Label::new(RichText::new(crate::i18n::format("ui.plugins_note", &[("path", &path)])).size(11.0).color(t.text_dim)).wrap());
+ ui.add_space(8.0);
+ if ui.button(crate::i18n::tr_label("Show in folder")).clicked() {
+ // `show_in_folder` opens the parent of the path it is given, so the argument is a name
+ // inside the plugins directory (it need not exist).
+ if let Err(e) = std::fs::create_dir_all(&dir) {
+ app.set_status(format!("Could not create the plugins folder: {e}"), true);
+ } else if let Some(show) = &app.services.show_in_folder {
+ show(&dir.join("plugin.json").display().to_string());
+ }
+ }
+ ui.add_space(8.0);
+ let (plugins, skipped) = scan(&dir);
+ if plugins.is_empty() {
+ ui.label(crate::i18n::tr("ui.plugins_empty"));
+ }
+ for plugin in &plugins {
+ let mut on = enabled(app, &plugin.id);
+ ui.horizontal(|ui| {
+ let check = ui.checkbox(&mut on, "");
+ crate::scenario::publish_handle(&format!("prefs:plugin:{}", plugin.id), check.rect.center());
+ if check.changed() {
+ if on {
+ app.preferences.disabled_plugins.remove(&plugin.id);
+ } else if app.preferences.disabled_plugins.len() < MAX_DISABLED {
+ app.preferences.disabled_plugins.insert(plugin.id.clone());
+ }
+ }
+ ui.vertical(|ui| {
+ ui.label(RichText::new(&plugin.name).strong());
+ ui.label(RichText::new(crate::i18n::format("ui.plugins_version", &[("version", &plugin.version)])).size(11.0).color(t.text_dim));
+ if !plugin.description.is_empty() {
+ ui.label(RichText::new(&plugin.description).size(11.0).color(t.text_dim));
+ }
+ });
+ });
+ ui.separator();
+ }
+ if !skipped.is_empty() {
+ ui.add_space(6.0);
+ ui.label(RichText::new(crate::i18n::format("ui.plugins_skipped", &[("count", &skipped.len().to_string())])).size(11.0).color(t.text_dim));
+ for skip in skipped.iter().take(8) {
+ let who = if skip.folder.is_empty() { "folder" } else { skip.folder.as_str() };
+ ui.label(RichText::new(format!("{who}: {}", skip.reason)).size(11.0).color(t.text_dim));
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn write(dir: &Path, folder: &str, body: &str) {
+ let d = dir.join(folder);
+ std::fs::create_dir_all(&d).unwrap();
+ std::fs::write(d.join("plugin.json"), body).unwrap();
+ }
+
+ #[test]
+ fn a_folder_with_plugin_json_is_listed_and_a_bad_one_is_skipped() {
+ let dir = std::env::temp_dir().join(format!("solidcraft-plugins-scan-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ write(
+ &dir,
+ "ftc-frc-parts",
+ r#"{"id":"ftc-frc-parts","name":"FTC and FRC parts","version":"0.1.0","description":"Commercial robot parts."}"#,
+ );
+ write(&dir, "broken", r#"{"id":"other","name":"Nope","version":"1"}"#);
+ std::fs::create_dir_all(dir.join("notes")).unwrap();
+ let (plugins, skipped) = scan(&dir);
+ assert_eq!(plugins.len(), 1);
+ assert_eq!(plugins[0].id, "ftc-frc-parts");
+ assert_eq!(plugins[0].name, "FTC and FRC parts");
+ assert!(skipped.iter().any(|s| s.folder == "broken" && s.reason.contains("does not match")));
+ assert!(skipped.iter().any(|s| s.folder == "notes" && s.reason.contains("no plugin.json")));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn ids_and_manifests_refuse_what_would_not_fit_on_the_page() {
+ assert!(valid_id("a"));
+ assert!(valid_id("ftc-frc-parts"));
+ assert!(!valid_id(""));
+ assert!(!valid_id("-a"));
+ assert!(!valid_id("a-"));
+ assert!(!valid_id("FTC"));
+ assert!(!valid_id(&"a".repeat(65)));
+ let bad = Manifest { id: "gear".into(), name: "Gear\nbox".into(), version: "1".into(), description: String::new() };
+ assert!(check(bad, "gear").is_err());
+ let big = Manifest { id: "gear".into(), name: "Gear".into(), version: "1".into(), description: "x".repeat(241) };
+ assert!(check(big, "gear").unwrap_err().contains("240"));
+ }
+
+ #[test]
+ fn turning_a_plugin_off_is_saved_and_restore_defaults_turns_it_back_on() {
+ use serde_json::json;
+ let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());
+ assert!(enabled(&app, "ftc-frc-parts"));
+ crate::prefs::set(&mut app, &json!({"disabled_plugins": ["ftc-frc-parts"]})).unwrap();
+ assert!(!enabled(&app, "ftc-frc-parts"));
+ let err = crate::prefs::set(&mut app, &json!({"disabled_plugins": ["Bad Id"]})).unwrap_err();
+ assert!(err.contains("disabled_plugins"), "{err}");
+ assert!(!enabled(&app, "ftc-frc-parts"), "a refused list leaves the previous choice");
+ let mut other = crate::SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());
+ other.load_prefs(&app.prefs());
+ assert!(!enabled(&other, "ftc-frc-parts"));
+ crate::prefs::control(&mut app, &json!({"open": "Plugins", "button": "defaults"})).unwrap();
+ assert_eq!(app.prefs_window.section, crate::prefs::PAGE_PLUGINS);
+ assert!(enabled(&app, "ftc-frc-parts"));
+ assert!(crate::prefs::control(&mut app, &json!({"open": "NoSuch"})).is_err());
+ }
+}
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index 661fd5ebd2..af70af2166 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -208,8 +208,9 @@ pub fn nav_preset(id: &str) -> &'static NavPreset {
NAV_PRESETS.iter().find(|p| p.id == id).unwrap_or(&NAV_PRESETS[0])
}
/// The dialog's pages, in order.
-pub const PAGES: [&str; 8] = ["General", "Navigation", "Keyboard Shortcuts", "Design", "Graphics", "Sketch", "Selection", "AI"];
+pub const PAGES: [&str; 9] = ["General", "Navigation", "Keyboard Shortcuts", "Design", "Graphics", "Sketch", "Selection", "AI", "Plugins"];
pub const PAGE_AI: usize = 7;
+pub const PAGE_PLUGINS: usize = 8;
pub const PAGE_SHORTCUTS: usize = 2;
pub const PAGE_DESIGN: usize = 3;
pub const PAGE_GRAPHICS: usize = 4;
@@ -406,6 +407,8 @@ pub struct Prefs {
/// When true: Shift+click adds without removing; Primary toggles.
/// When false (default): Shift and Primary both toggle.
pub selection_shift_add_only: bool,
+ /// Plugin ids turned off (Preferences › Plugins). An installed plugin whose id is absent is on.
+ pub disabled_plugins: std::collections::BTreeSet<String>,
}
/// What a middle-button double-click in the view does.
@@ -506,6 +509,7 @@ impl Default for Prefs {
suppress_sketch_snap: ModifierCombo::CTRL_ALT,
manipulator_free_alt: true,
selection_shift_add_only: false,
+ disabled_plugins: std::collections::BTreeSet::new(),
}
}
}
@@ -740,6 +744,7 @@ fn defaults(app: &mut SolveApp, page: usize) {
app.autosave_minutes = 5.0;
set_autosave(app);
}
+ PAGE_PLUGINS => p.disabled_plugins.clear(),
PAGE_AI => {
// The agents the user added and their "always allow" answers stay.
p.ai_features = d.ai_features;
@@ -1221,6 +1226,10 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {
crate::agent_chat::settings::page(app, ui);
return;
}
+ if app.prefs_window.section == PAGE_PLUGINS {
+ crate::plugins::page(app, ui);
+ return;
+ }
egui::Grid::new(("sc_prefs_grid", app.prefs_window.section)).num_columns(2).spacing([16.0, 8.0]).show(ui, |ui| match app.prefs_window.section {
0 => {
ui.label(app.tr("ui.language"));
@@ -1842,12 +1851,23 @@ pub fn migrate(mut p: Prefs) -> Prefs {
p
}
+/// Drop plugin ids this page would not show, and keep at most [`crate::plugins::MAX_DISABLED`],
+/// so a hand-edited preferences file cannot carry a huge or nonsense list. `set` still refuses
+/// those instead of dropping them.
+fn limit_disabled_plugins(mut p: Prefs) -> Prefs {
+ p.disabled_plugins.retain(|id| crate::plugins::valid_id(id));
+ if p.disabled_plugins.len() > crate::plugins::MAX_DISABLED {
+ p.disabled_plugins = p.disabled_plugins.into_iter().take(crate::plugins::MAX_DISABLED).collect();
+ }
+ p
+}
+
/// Saved preferences, keeping every one that still reads. A value this version doesn't
/// understand (a setting a newer or older release saved differently, a hand edit) falls back to
/// its default on its own instead of discarding all of them.
pub fn lenient(saved: &serde_json::Value) -> Prefs {
if let Ok(p) = serde_json::from_value::<Prefs>(saved.clone()) {
- return migrate(p);
+ return limit_disabled_plugins(migrate(p));
}
let Ok(mut cur) = serde_json::to_value(Prefs::default()) else { return Prefs::default() };
if let (Some(o), Some(src)) = (cur.as_object_mut(), saved.as_object()) {
@@ -1861,7 +1881,7 @@ pub fn lenient(saved: &serde_json::Value) -> Prefs {
}
}
}
- serde_json::from_value(cur).map(migrate).unwrap_or_default()
+ serde_json::from_value(cur).map(migrate).map(limit_disabled_plugins).unwrap_or_default()
}
/// Set preferences from JSON (control channel); returns them all.
@@ -1904,6 +1924,9 @@ pub fn set(app: &mut SolveApp, p: &serde_json::Value) -> Result<serde_json::Valu
if new.ui_font != app.preferences.ui_font && !new.ui_font.trim().is_empty() && crate::fonts::ui_font(&new.ui_font).is_none() {
return Err(format!("`ui_font`: `{}` is not an installed font family or a readable font file", new.ui_font.trim()));
}
+ if new.disabled_plugins.len() > crate::plugins::MAX_DISABLED || new.disabled_plugins.iter().any(|id| !crate::plugins::valid_id(id)) {
+ return Err(format!("`disabled_plugins` must be at most {} ids of lowercase letters, digits and hyphens", crate::plugins::MAX_DISABLED));
+ }
if !(0.5..=2.5).contains(&new.ui_scale) || !(0.25..=4.0).contains(&new.look_at_speed) {
return Err("`ui_scale` must be 0.5…2.5 and `look_at_speed` 0.25…4".into());
}
@@ -2478,7 +2501,7 @@ mod tests {
let mut out = ctx.run_ui(Default::default(), |ui| show(&mut app, ui.ctx()));
out.textures_delta.clear();
assert!(app.prefs_window.open && app.prefs_window.section == PAGE_SHORTCUTS && !app.keymap.open);
- assert!(control(&mut app, &json!({"open": "Plugins"})).is_err());
+ assert!(control(&mut app, &json!({"open": "NoSuch"})).is_err());
assert!(set(&mut app, &json!({"up_axis": "x"})).is_err());
assert!(set(&mut app, &json!({"theme": "sepia"})).is_err());
assert!(set(&mut app, &json!({"language": "xx"})).is_err());