Skip to main content

brep_app/
plugins.rs

1//! Explicit installation and host-only acquisition. Document opening never installs code.
2use crate::ui_kit;
3use crate::store::{ModelStore, PLUGINS_KEY};
4use brep_render::engine_state::EngineState;
5use eframe::egui;
6use serde::{Deserialize, Serialize};
7use serde_json::{json, Value};
8use std::{cell::RefCell, rc::Rc, sync::mpsc::Receiver};
9
10const MAX_BUNDLE_BYTES: usize = 16 * 1024 * 1024;
11
12#[derive(Clone, Serialize, Deserialize)]
13pub struct InstalledBundle {
14    /// Original UTF-8 bytes, preserved for portable export and offline reopening.
15    pub bytes: String,
16    pub enabled: bool,
17    pub id: String,
18    pub digest: String,
19    pub version: String,
20    pub source: Option<String>,
21}
22
23pub type SharedPackages = Rc<RefCell<Vec<InstalledBundle>>>;
24
25pub fn restore(engine: &mut EngineState, packages: &[InstalledBundle]) -> Result<u64, String> {
26    let entries: Result<Vec<_>, String> = packages
27        .iter()
28        .map(|p| {
29            let bundle: brep_plugins::PackageBundle =
30                serde_json::from_str(&p.bytes).map_err(|e| e.to_string())?;
31            let pin = bundle.pin()?;
32            if pin.id != p.id || pin.version != p.version || pin.digest != p.digest {
33                return Err(format!(
34                    "Stored plugin {} content does not match its pinned identity",
35                    p.id
36                ));
37            }
38            Ok(json!({"bundle": bundle, "enabled": p.enabled}))
39        })
40        .collect();
41    engine.submit_plugin_installations(Value::Array(entries?))
42}
43
44/// Parse only the portable container here; runtime validates modules and registrations.
45pub fn parse_bundle(bytes: &[u8]) -> Result<(String, Value), String> {
46    if bytes.len() > MAX_BUNDLE_BYTES {
47        return Err("Plugin bundle exceeds 16 MiB".into());
48    }
49    let text = std::str::from_utf8(bytes).map_err(|e| format!("Bundle must be UTF-8: {e}"))?;
50    let value: Value =
51        serde_json::from_str(text).map_err(|e| format!("Invalid plugin bundle JSON: {e}"))?;
52    if !value["manifest"].is_object() || !value["modules"].is_object() {
53        return Err("Expected a bundle containing manifest and modules objects".into());
54    }
55    Ok((text.to_owned(), value))
56}
57
58/// GitHub blob links resolve their ref through the commits API before downloading.
59/// Direct HTTP(S) bundles are pinned by their validated content digest.
60#[derive(Debug, PartialEq)]
61enum Acquisition {
62    Direct(String),
63    Github {
64        owner: String,
65        repo: String,
66        revision: String,
67        path: String,
68    },
69}
70fn acquisition(url: &str) -> Result<Acquisition, String> {
71    let url = url.trim();
72    if let Some(rest) = url.strip_prefix("https://github.com/") {
73        let parts: Vec<_> = rest.split('/').collect();
74        if parts.len() < 5
75            || parts[2] != "blob"
76            || parts
77                .iter()
78                .any(|p| p.is_empty() || *p == ".." || p.contains(['?', '#', '\\']))
79        {
80            return Err("Use a GitHub blob URL to a .brep-plugin.json bundle (refs containing / require an immutable commit URL)".into());
81        }
82        return Ok(Acquisition::Github {
83            owner: parts[0].into(),
84            repo: parts[1].into(),
85            revision: parts[3].into(),
86            path: parts[4..].join("/"),
87        });
88    }
89    if !(url.starts_with("https://") || url.starts_with("http://")) {
90        return Err("Enter an HTTP(S) bundle URL or GitHub blob URL".into());
91    }
92    Ok(Acquisition::Direct(url.into()))
93}
94
95struct Download {
96    rx: Receiver<Result<Vec<u8>, String>>,
97    source: String,
98    github: Option<(String, String, String)>,
99}
100
101pub struct PluginsPanel {
102    pub open: bool,
103    pub packages: SharedPackages,
104    pub error: Option<String>,
105    pub message: Option<String>,
106    pub(crate) storage_error: Option<String>,
107    url: String,
108    #[cfg(not(target_arch = "wasm32"))]
109    local_path: String,
110    pasted: String,
111    download: Option<Download>,
112    importing: bool,
113    action: Option<ActionForm>,
114    panel_params: std::collections::HashMap<String, Value>,
115    panel_hits: std::collections::HashMap<String, egui::Rect>,
116    ui_package_stamp: String,
117    synced: std::collections::HashMap<u64, String>,
118    pub(crate) active_document: u64,
119    pending_install: Option<(u64, u64, Vec<InstalledBundle>)>,
120    /// A package's Export asked: the shell hands these to the file dialog's
121    /// export door ([`Self::take_save_requests`]), which on desktop asks where.
122    exports: Vec<crate::panels::file::SaveRequest>,
123}
124struct ActionForm {
125    id: String,
126    package_digest: Value,
127    label: String,
128    schema: Value,
129    params: Value,
130    error: Option<String>,
131    pending: bool,
132}
133
134impl PluginsPanel {
135    pub fn new(store: &dyn ModelStore) -> Self {
136        let (packages, error) = match store.read(PLUGINS_KEY) {
137            Some(text) => match serde_json::from_str::<Vec<InstalledBundle>>(&text) {
138                Ok(v) => (v, None),
139                Err(e) => (
140                    vec![],
141                    Some(format!("Installed plugins could not be read: {e}")),
142                ),
143            },
144            None => (vec![], None),
145        };
146        Self {
147            open: false,
148            packages: Rc::new(RefCell::new(packages)),
149            error,
150            message: None,
151            storage_error: None,
152            url: String::new(),
153            #[cfg(not(target_arch = "wasm32"))]
154            local_path: String::new(),
155            pasted: String::new(),
156            download: None,
157            importing: false,
158            action: None,
159            panel_params: Default::default(),
160            panel_hits: Default::default(),
161            ui_package_stamp: String::new(),
162            synced: Default::default(),
163            active_document: 0,
164            pending_install: None,
165            exports: Vec::new(),
166        }
167    }
168
169    pub fn sync_documents(&mut self, docs: &mut crate::document::Documents) {
170        let packages = self.packages.borrow();
171        let stamp = packages
172            .iter()
173            .map(|p| format!("{}:{}:{}", p.id, p.digest, p.enabled))
174            .collect::<Vec<_>>()
175            .join("|");
176        if self.ui_package_stamp != stamp { self.panel_params.clear(); self.action = None; self.ui_package_stamp = stamp.clone(); }
177        if self.active_document != docs.active_id() { self.panel_params.clear(); self.action = None; }
178        self.active_document = docs.active_id();
179        self.synced
180            .retain(|id, _| docs.iter().any(|d| d.id() == *id));
181        for doc in docs.iter_mut() {
182            if self
183                .pending_install
184                .as_ref()
185                .is_some_and(|p| p.0 == doc.id())
186            {
187                continue;
188            }
189            let status = doc.engine.plugin_installation_status();
190            if status["state"] == "error" {
191                self.error = status["error"].as_str().map(str::to_owned);
192            }
193            if status["state"] == "pending" {
194                continue;
195            }
196            if self.synced.get(&doc.id()) != Some(&stamp) {
197                let expected: Vec<_> = packages
198                    .iter()
199                    .map(|p| json!([p.id, p.digest, p.enabled]))
200                    .collect();
201                let actual: Vec<_> = doc
202                    .engine
203                    .installed_plugins()
204                    .as_array()
205                    .into_iter()
206                    .flatten()
207                    .map(|p| json!([p["id"], p["digest"], p["enabled"]]))
208                    .collect();
209                if expected == actual {
210                    self.synced.insert(doc.id(), stamp.clone());
211                    continue;
212                }
213                match restore(&mut doc.engine, &packages) {
214                    Ok(_) => {
215                        self.synced.insert(doc.id(), stamp.clone());
216                    }
217                    Err(e) => {
218                        self.error = Some(e);
219                        self.synced.insert(doc.id(), stamp.clone());
220                    }
221                }
222            }
223        }
224    }
225
226    pub fn close_action(&mut self) {
227        self.action = None;
228    }
229
230    fn persist(&self, store: &dyn ModelStore, next: &[InstalledBundle]) -> Result<(), String> {
231        store.write(
232            PLUGINS_KEY,
233            &serde_json::to_string(next).map_err(|e| e.to_string())?,
234        )
235    }
236
237    pub fn install(
238        &mut self,
239        engine: &mut EngineState,
240        _store: &dyn ModelStore,
241        bytes: &[u8],
242        source: Option<String>,
243    ) -> Result<u64, String> {
244        let (bytes, bundle) = parse_bundle(bytes)?;
245        let typed: brep_plugins::PackageBundle =
246            serde_json::from_value(bundle).map_err(|e| e.to_string())?;
247        let pin = typed.pin()?;
248        let mut next = self.packages.borrow().clone();
249        next.retain(|p| !(p.id == pin.id && p.digest == pin.digest));
250        next.push(InstalledBundle {
251            bytes,
252            enabled: true,
253            id: pin.id,
254            digest: pin.digest,
255            version: pin.version,
256            source,
257        });
258        self.queue_install(engine, next)
259    }
260
261    fn queue_install(
262        &mut self,
263        engine: &mut EngineState,
264        next: Vec<InstalledBundle>,
265    ) -> Result<u64, String> {
266        if self.pending_install.is_some() {
267            return Err("A plugin installation is already pending".into());
268        }
269        let id = restore(engine, &next)?;
270        self.pending_install = Some((self.active_document, id, next));
271        self.error = None;
272        self.storage_error = None;
273        self.message = Some("Validating plugin registrations in the history worker…".into());
274        Ok(id)
275    }
276
277    pub fn finish_installations(
278        &mut self,
279        docs: &mut crate::document::Documents,
280        store: &dyn ModelStore,
281    ) {
282        let Some((owner, id, _)) = &self.pending_install else {
283            return;
284        };
285        let Some(doc) = docs.iter_mut().find(|d| d.id() == *owner) else {
286            self.pending_install = None;
287            self.error = Some("Installation cancelled because its document was closed".into());
288            return;
289        };
290        let status = doc.engine.plugin_installation_status();
291        if status["id"].as_u64() != Some(*id) {
292            return;
293        }
294        match status["state"].as_str() {
295            Some("complete") => {
296                let (_, _, next) = self.pending_install.take().unwrap();
297                match self.persist(store, &next) {
298                    Ok(()) => {
299                        *self.packages.borrow_mut() = next;
300                        self.message = Some(
301                            "Installed exact package bytes. Existing document pins stay unchanged."
302                                .into(),
303                        );
304                    }
305                    Err(e) => {
306                        self.storage_error = Some(e.clone());
307                        self.error = Some(e);
308                        let _ = restore(&mut doc.engine, &self.packages.borrow());
309                    }
310                }
311            }
312            Some("error") => {
313                self.error = Some(
314                    status["error"]
315                        .as_str()
316                        .unwrap_or("Plugin installation failed")
317                        .into(),
318                );
319                self.pending_install = None;
320            }
321            _ => {}
322        }
323    }
324
325    pub fn open_action(&mut self, engine: &EngineState, id: &str) -> Result<(), String> {
326        if self.action.as_ref().is_some_and(|a| a.pending) {
327            return Err("Wait for or cancel the pending action before opening another".into());
328        }
329        let catalogue = engine.plugin_catalogue();
330        let action = catalogue["actions"]
331            .as_array()
332            .and_then(|a| a.iter().find(|a| a["id"] == id))
333            .ok_or_else(|| format!("Plugin action {id} is unavailable"))?;
334        let schema = action["inputParamsSchema"].clone();
335        let mut params = json!({});
336        if let Some(fields) = schema.as_object() {
337            for (key, field) in fields {
338                if let Some(default) = field.get("default_value") {
339                    params[key] = default.clone();
340                }
341            }
342        }
343        self.action = Some(ActionForm {
344            id: id.into(),
345            package_digest: action["package"]["digest"].clone(),
346            label: action["ribbonPath"].as_str().and_then(|p| p.rsplit('/').next()).or(action["label"].as_str()).unwrap_or(id).into(),
347            schema,
348            params,
349            error: None,
350            pending: false,
351        });
352        Ok(())
353    }
354
355    pub fn poll(&mut self, ctx: &egui::Context, engine: &mut EngineState, store: &dyn ModelStore) {
356        if self.importing {
357            if let Some(file) = store.take_import() {
358                self.importing = false;
359                if let Err(e) = self.install(engine, store, &file.bytes, None) {
360                    self.error = Some(e);
361                }
362            }
363        }
364        let result = self.download.as_ref().and_then(|d| d.rx.try_recv().ok());
365        if let Some(result) = result {
366            let download = self.download.take().unwrap();
367            match result {
368                Err(e) => self.error = Some(e),
369                Ok(bytes) => {
370                    if let Some((owner, repo, path)) = download.github {
371                        let commit = serde_json::from_slice::<Value>(&bytes)
372                            .ok()
373                            .and_then(|v| v["sha"].as_str().map(str::to_owned));
374                        match commit.filter(|sha| {
375                            sha.len() == 40 && sha.bytes().all(|c| c.is_ascii_hexdigit())
376                        }) {
377                            Some(sha) => {
378                                let source = format!(
379                                    "https://raw.githubusercontent.com/{owner}/{repo}/{sha}/{path}"
380                                );
381                                self.download = Some(Download {
382                                    rx: crate::http::fetch_bytes(ctx, source.clone()),
383                                    source,
384                                    github: None,
385                                });
386                            }
387                            None => {
388                                self.error =
389                                    Some("GitHub did not return an immutable commit SHA".into())
390                            }
391                        }
392                    } else if let Err(e) =
393                        self.install(engine, store, &bytes, Some(download.source))
394                    {
395                        self.error = Some(e);
396                    }
397                }
398            }
399        }
400        if let Some(result) = engine.poll_plugin_action() {
401            match result {
402                Ok(value) => {
403                    self.message = Some(value.to_string());
404                    if let Some(form) = &mut self.action {
405                        form.pending = false;
406                    }
407                }
408                Err(e) => {
409                    self.error = Some(e.clone());
410                    if let Some(form) = &mut self.action {
411                        form.error = Some(e);
412                        form.pending = false;
413                    }
414                }
415            }
416        }
417        if self.download.is_some()
418            || self.pending_install.is_some()
419            || engine.plugin_installation_status()["state"] == "pending"
420            || self.action.as_ref().is_some_and(|a| a.pending)
421        {
422            ctx.request_repaint_after(std::time::Duration::from_millis(30));
423        }
424    }
425
426    /// The bundles Export asked to save, once: the shell hands them to
427    /// [`crate::panels::file::FileDialog::request_save_file`].
428    pub fn take_save_requests(&mut self) -> Vec<crate::panels::file::SaveRequest> {
429        std::mem::take(&mut self.exports)
430    }
431
432    pub fn show(&mut self, ctx: &egui::Context, engine: &mut EngineState, store: &dyn ModelStore) {
433        let mut open = self.open;
434        egui::Window::new("Plugins").open(&mut open).default_width(560.0).default_pos(crate::panels::below_chrome(ctx, 400.0, 0.0)).show(ctx, |ui| {
435            ui.label("Install trusted JavaScript package bundles. Code runs with the CAD host API; installation is separate from opening a document.");
436            if let Some(error) = &self.error { ui.colored_label(egui::Color32::LIGHT_RED, error); }
437            if let Some(message) = &self.message { ui.label(message); }
438            if engine.plugin_installation_status()["state"] == "pending" { ui.spinner(); ui.label("Validating package registrations…"); }
439            for error in engine.plugin_catalogue()["errors"].as_array().into_iter().flatten() { if let Some(error) = error.as_str() { ui.colored_label(egui::Color32::LIGHT_RED, error); } }
440            ui.horizontal(|ui| {
441                // Labelled like the local path row below it; the field said nothing (lane U item 15).
442                ui.label("Package URL");
443                ui.add(egui::TextEdit::singleline(&mut self.url).hint_text("https://… or a github.com repository"));
444                if ui_kit::button::add_enabled(ui, self.download.is_none(), ui_kit::Button::new("Install URL / GitHub")).clicked() {
445                    match acquisition(&self.url) {
446                        Ok(Acquisition::Direct(source)) => self.download = Some(Download { rx: crate::http::fetch_bytes(ctx, source.clone()), source, github: None }),
447                        Ok(Acquisition::Github { owner, repo, revision, path }) => { let source = format!("https://api.github.com/repos/{owner}/{repo}/commits/{revision}"); self.download = Some(Download { rx: crate::http::fetch_bytes(ctx, source.clone()), source, github: Some((owner, repo, path)) }); },
448                        Err(e) => self.error = Some(e),
449                    }
450                }
451            });
452            if self.download.is_some() { ui.spinner(); ui.label("Acquiring pinned package bytes…"); }
453            if store.supports_file_interchange() && ui.add(ui_kit::Button::new("Import local bundle…")).clicked() {
454                match store.begin_import_filtered(("Plugin bundle", &["json"])) { Ok(()) => self.importing = true, Err(e) => self.error = Some(e) }
455            }
456            #[cfg(not(target_arch = "wasm32"))]
457            ui.horizontal(|ui| { ui.label("Local bundle path"); ui.text_edit_singleline(&mut self.local_path); if ui.add(ui_kit::Button::new("Import")).clicked() { let result = std::fs::read(&self.local_path).map_err(|e| e.to_string()).and_then(|bytes| self.install(engine, store, &bytes, None)); if let Err(e) = result { self.error = Some(e); } } });
458            ui.collapsing("Paste portable bundle JSON", |ui| { ui.add(egui::TextEdit::multiline(&mut self.pasted).code_editor().desired_rows(6)); if ui.add(ui_kit::Button::new("Install pasted bundle")).clicked() { let bytes = self.pasted.as_bytes().to_vec(); if let Err(e) = self.install(engine, store, &bytes, None) { self.error = Some(e); } } });
459            ui.separator();
460            let installed = self.packages.borrow().clone();
461            for package in &installed {
462                ui.group(|ui| {
463                    ui.label(crate::theme::data(format!("{}  {}", package.id, package.version)));
464                    ui.small(crate::theme::data(format!("SHA-256 {}", package.digest)));
465                    if let Some(source) = &package.source { ui.small(crate::theme::data(source)); }
466                    ui.horizontal_wrapped(|ui| {
467                        let mut enabled = package.enabled;
468                        if ui_kit::checkbox(ui, &mut enabled, "Enabled").changed() { self.change(engine, store, package, Some(enabled)); }
469                        if ui.add(ui_kit::Button::new("Use in document")).clicked() { if let Err(e) = engine.select_plugin(&package.id, &package.digest) { self.error = Some(e); } }
470                        if ui.add(ui_kit::Button::new("Migrate document")).clicked() { if let Err(e) = engine.migrate_plugin(&package.id, &package.digest) { self.error = Some(e); } }
471                        if ui.add(ui_kit::Button::new("Reload stored bytes")).clicked() { if let Err(e) = self.queue_install(engine, installed.clone()) { self.error = Some(e); } }
472                        if ui.add(ui_kit::Button::new("Export")).clicked() { self.exports.push(crate::panels::file::SaveRequest::text("Export the plugin bundle", format!("{}-{}.brep-plugin.json", package.id.replace('/', "_"), package.version), package.bytes.clone())); }
473                        if ui.add(ui_kit::Button::new("Remove")).clicked() { self.change(engine, store, package, None); }
474                    });
475                });
476            }
477            ui.small("Updates keep old bundles. Reload revalidates stored bytes; import again to load edited source. Panels appear in their claimed workbench; typed annotations are authored in PMI.");
478        });
479        self.open = open;
480        self.show_action(ctx, engine);
481    }
482
483    pub(crate) fn change(
484        &mut self,
485        engine: &mut EngineState,
486        _store: &dyn ModelStore,
487        package: &InstalledBundle,
488        enabled: Option<bool>,
489    ) {
490        let result = (|| {
491            let mut next = self.packages.borrow().clone();
492            if let Some(enabled) = enabled {
493                for p in &mut next {
494                    if p.id == package.id && p.digest == package.digest {
495                        p.enabled = enabled;
496                    }
497                }
498            } else {
499                next.retain(|p| !(p.id == package.id && p.digest == package.digest));
500            }
501            self.queue_install(engine, next)?;
502            self.action = None;
503            Ok::<_, String>(())
504        })();
505        if let Err(e) = result {
506            self.error = Some(e);
507        }
508    }
509
510    pub fn clear_panel_hits(&mut self) { self.panel_hits.clear(); }
511    pub fn panel_hits_json(&self) -> String { crate::automation::hit_rects::hits_json(&self.panel_hits) }
512
513    /// Draw validated static controls. Only button clicks submit worker actions.
514    pub fn show_panel(&mut self, ui: &mut egui::Ui, engine: &mut EngineState, id: &str) {
515        let catalogue = engine.plugin_catalogue();
516        let Some(panel) = catalogue["panels"].as_array().into_iter().flatten().find(|p| p["id"] == id) else {
517            ui.label("Panel owner is unavailable for this document."); return;
518        };
519        let pending = engine.plugin_action_status()["state"] == "pending";
520        egui::ScrollArea::vertical().id_salt(("plugin-panel", id)).show(ui, |ui| {
521            for (index, control) in panel["controls"].as_array().into_iter().flatten().enumerate() {
522                ui.push_id((id, index), |ui| {
523                    match control["type"].as_str().unwrap_or("") {
524                        "text" => { ui.label(control["text"].as_str().unwrap_or("")); }
525                        "table" => { egui::Grid::new("table").striped(true).show(ui, |ui| {
526                            crate::theme::data_rows(ui);
527                            for column in control["columns"].as_array().into_iter().flatten() { ui.strong(column.as_str().unwrap_or("")); } ui.end_row();
528                            for row in control["rows"].as_array().into_iter().flatten() {
529                                for cell in row.as_array().into_iter().flatten() { ui.label(cell.as_str().unwrap_or("")); } ui.end_row();
530                            }
531                        }); }
532                        "action" | "form" => {
533                            let action_id = control["action"].as_str().unwrap_or("");
534                            let Some(action) = catalogue["actions"].as_array().into_iter().flatten().find(|a| a["id"] == action_id) else {
535                                ui.label("Action owner unavailable"); return;
536                            };
537                            let key = format!("{}:{}:{}", panel["package"]["digest"], id, control["id"]);
538                            let params = self.panel_params.entry(key).or_insert_with(|| {
539                                let mut params = schema_defaults(&action["inputParamsSchema"]);
540                                if let Some(overrides) = control["params"].as_object() { params.as_object_mut().unwrap().extend(overrides.clone()); } params
541                            });
542                            ui.add_enabled_ui(!pending && engine.history.locked().is_none(), |ui| {
543                                if control["type"] == "form" { schema_fields(ui, engine, &action["inputParamsSchema"], params); }
544                                let button = ui.add(ui_kit::Button::new(&(control["label"].as_str().unwrap_or(action_id))));
545                                self.panel_hits.insert(format!("panel:{id}:{}", control["id"].as_str().unwrap_or("")), button.rect);
546                                if button.clicked() {
547                                    let selection = serde_json::from_str(&engine.selection_json()).unwrap_or(Value::Null);
548                                    match engine.plugin_action(action_id, params.clone(), selection) {
549                                        Ok(_) => { self.error = None; ui.ctx().request_repaint(); }
550                                        Err(e) => self.error = Some(e),
551                                    }
552                                }
553                            });
554                        }
555                        _ => { ui.label("Unsupported panel control"); }
556                    }
557                });
558            }
559            if pending { ui.spinner(); ui.ctx().request_repaint_after(std::time::Duration::from_millis(30)); }
560            if let Some(error) = &self.error { ui.colored_label(egui::Color32::LIGHT_RED, error); }
561        });
562    }
563
564    fn show_action(&mut self, ctx: &egui::Context, engine: &mut EngineState) {
565        let Some(form) = &mut self.action else { return };
566        if !engine.plugin_catalogue()["actions"].as_array().into_iter().flatten().any(|a| a["id"] == form.id && a["package"]["digest"] == form.package_digest) {
567            self.action = None; return;
568        }
569        let mut open = true;
570        egui::Window::new(&form.label)
571            .id(egui::Id::new("plugin-action-form"))
572            .open(&mut open)
573            .show(ctx, |ui| {
574                ui.small(&form.id);
575                if let Some(error) = &form.error {
576                    ui.colored_label(egui::Color32::LIGHT_RED, error);
577                }
578                ui.add_enabled_ui(!form.pending, |ui| {
579                    schema_fields(ui, engine, &form.schema, &mut form.params);
580                    if ui.add(ui_kit::Button::new("Run action")).clicked() {
581                        match engine.plugin_action(
582                            &form.id,
583                            form.params.clone(),
584                            serde_json::from_str(&engine.selection_json()).unwrap_or(Value::Null),
585                        ) {
586                            Ok(_) => {
587                                form.pending = true;
588                                form.error = None;
589                            }
590                            Err(e) => form.error = Some(e),
591                        }
592                    }
593                });
594                if form.pending {
595                    ui.spinner();
596                    if ui.add(ui_kit::Button::new("Cancel")).clicked() {
597                        engine.cancel_plugin_action();
598                        form.pending = false;
599                    }
600                }
601            });
602        if !open {
603            if form.pending {
604                engine.cancel_plugin_action();
605            }
606            self.action = None;
607        }
608    }
609}
610
611pub(crate) fn schema_defaults(schema: &Value) -> Value {
612    let mut params = json!({});
613    for (key, field) in schema.as_object().into_iter().flatten() {
614        if let Some(default) = field.get("default_value") { params[key] = default.clone(); }
615    }
616    params
617}
618
619pub(crate) fn schema_fields(ui: &mut egui::Ui, engine: &EngineState, schema: &Value, params: &mut Value) {
620    let entry = json!({"inputParamsSchema": schema});
621    let fields = brep_render::features::plugin_form_fields_from_schema(&entry);
622    let selection: Value = serde_json::from_str(&engine.selection_json()).unwrap_or(Value::Null);
623    for field in &fields {
624        ui.label(&field.label);
625        let mut actions = crate::form::FieldActions::default();
626        crate::form::field_input(ui, field, params, None, &mut actions);
627        if actions.clicked.is_some() {
628            if let brep_render::style::FieldKind::Reference { filter, multiple } = &field.kind {
629                let names: Vec<Value> = filter.iter().flat_map(|kind| {
630                    let key = match kind.to_ascii_lowercase().as_str() {
631                        "solid" => "solids", "face" => "faces", "edge" => "edges", "datum" => "datums", _ => "",
632                    };
633                    selection[key].as_array().into_iter().flatten().cloned()
634                }).collect();
635                params[field.key()] = if *multiple { Value::Array(names) } else { names.into_iter().next().unwrap_or(Value::Null) };
636            }
637        }
638        if matches!(&field.kind, brep_render::style::FieldKind::Reference { .. }) { ui.small("Select uses the current viewport selection."); }
639    }
640}
641
642pub fn feature_label(engine: &EngineState, ty: &str) -> String {
643    if !ty.contains('/') {
644        return brep_render::features::feature_plain_name(ty);
645    }
646    engine
647        .feature_schema(ty)
648        .and_then(|s| s["longName"].as_str().map(str::to_owned))
649        .unwrap_or_else(|| ty.to_owned())
650}
651
652
653pub const HIT_KEYS: &[crate::automation::hit_keys::HitKeyDoc] = &[crate::automation::hit_keys::HitKeyDoc { panel: "plugins", prefix: "panel:", meaning: "submit the named action for a declarative panel control", command: Some("plugin_action") }];