//! The plugin commands in the shell's command palette, native side, for every app: the list each //! site tab last reported ([`reported`]; validated by [`crate::plugins::commands`]), kept per tab, //! forwarded to the shell, and the check behind the shell-only `tab_run_command` ([`run`]: only a //! command that tab reported, only while it is on the site; the command's code runs in the page). use crate::app::config; use crate::host::{emit_shell, tab_webview}; use crate::plugins::commands::{self as palette, PaletteCommand}; use serde::Serialize; use std::collections::HashMap; use std::sync::{Mutex, MutexGuard, OnceLock}; use tauri::{AppHandle, Webview}; fn lists() -> MutexGuard<'static, HashMap>> { static LISTS: OnceLock>>> = OnceLock::new(); LISTS.get_or_init(Default::default).lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Stores what tab `label` has (empty = none) and tells the shell when it changed. fn store(app: &AppHandle, label: &str, list: Vec) { let Some(id) = crate::policy::tab_id(label) else { return }; let changed = { let mut lists = lists(); let changed = lists.get(label).map(Vec::as_slice).unwrap_or(&[]) != list.as_slice(); if list.is_empty() { lists.remove(label); } else { lists.insert(label.to_owned(), list.clone()); } changed }; if changed { #[derive(Clone, Serialize)] struct Commands { id: String, commands: Vec, } emit_shell(app, palette::EVENT, Commands { id: id.to_owned(), commands: list }); } } /// A new document started in tab `label`: its plugins register their commands again. pub(crate) fn cleared(app: &AppHandle, label: &str) { store(app, label, Vec::new()); } /// A tab reported its commands. Accepted only from a tab that is on the site right now; the list /// is validated as a whole (any bad entry rejects the report). pub fn reported(app: &AppHandle, webview: &Webview, list: Vec) -> Result<(), String> { if !webview.url().is_ok_and(|url| config(app).site.is_origin(&url)) { return Ok(()); } store(app, webview.label(), palette::validate(list)?); Ok(()) } /// Runs command `command` in tab `id` (the caller checked it is the shell). pub(crate) fn run(app: &AppHandle, id: &str, command: &str) -> Result<(), String> { let label = crate::policy::tab_label(id); if !lists().get(&label).is_some_and(|list| list.iter().any(|item| item.id == command)) { return Err("VALIDATION: that tab has no such command".into()); } let site = config(app).site; let tab = tab_webview(app, id).ok_or("VALIDATION: no such tab")?; if !tab.url().is_ok_and(|url| site.is_origin(&url)) { return Err("VALIDATION: the tab is not on the site".into()); } let script = palette::run_script(site, command)?; let _ = tab.set_focus(); tab.eval(&script).map_err(|error| format!("TABS: {error}")) }