diff --git a/crates/ide-host/src/plugins/event_wake.rs b/crates/ide-host/src/plugins/event_wake.rs new file mode 100644 index 0000000000..53844b68ef --- /dev/null +++ b/crates/ide-host/src/plugins/event_wake.rs @@ -0,0 +1,61 @@ +//! Lets the event pump sleep until something needs it, instead of for a fixed period. +use parking_lot::{Condvar, Mutex}; +use std::time::{Duration, Instant}; + +/// A flag the event pump waits on between [`flush_events`](super::PluginHost::flush_events) +/// calls: waking it early costs one notification, an idle pump still wakes only on its +/// timeout. A notification made while the pump is busy is kept for its next wait. +#[derive(Default)] +pub struct EventWake { + signalled: Mutex, + changed: Condvar, +} + +impl EventWake { + /// Makes the current or next [`wait`](Self::wait) return at once. + pub fn notify(&self) { + *self.signalled.lock() = true; + self.changed.notify_one(); + } + + /// Blocks until [`notify`](Self::notify) or `timeout`; true when it was notified. + pub fn wait(&self, timeout: Duration) -> bool { + let deadline = Instant::now() + timeout; + let mut signalled = self.signalled.lock(); + while !*signalled { + if self.changed.wait_until(&mut signalled, deadline).timed_out() { + break; + } + } + std::mem::take(&mut *signalled) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + #[test] + fn a_notification_ends_the_wait_and_is_consumed() { + let wake = EventWake::default(); + assert!(!wake.wait(Duration::from_millis(10)), "times out when idle"); + wake.notify(); + assert!(wake.wait(Duration::from_secs(5)), "kept for the next wait"); + assert!(!wake.wait(Duration::ZERO), "consumed"); + } + + #[test] + fn a_waiting_pump_wakes_early() { + let wake = Arc::new(EventWake::default()); + let start = Instant::now(); + let waiter = { + let wake = wake.clone(); + std::thread::spawn(move || wake.wait(Duration::from_secs(30))) + }; + std::thread::sleep(Duration::from_millis(20)); + wake.notify(); + assert!(waiter.join().unwrap()); + assert!(start.elapsed() < Duration::from_secs(10)); + } +} diff --git a/crates/ide-host/src/plugins/linked_watch.rs b/crates/ide-host/src/plugins/linked_watch.rs new file mode 100644 index 0000000000..e41d42f06c --- /dev/null +++ b/crates/ide-host/src/plugins/linked_watch.rs @@ -0,0 +1,153 @@ +//! Linked plugins (`openidea-plugin link`) are read in place, so editing their files +//! reloads them: a theme regenerated by a script, a rebuilt `dist/plugin.wasm`. +//! +//! Every linked plugin folder is watched recursively. The watcher already coalesces a +//! burst (a write-then-rename, a build touching many files) into one batch, so a batch +//! with a relevant change marks its folder as changed and wakes the event pump +//! ([`super::PluginHost::event_wake`]); [`super::PluginHost::flush_events_at`] then +//! reloads the plugin right away. Installed copies and project plugins are never watched. +use super::event_wake::EventWake; +use ide_core::NullSink; +use ide_vfs::{FsBatch, Watcher}; +use parking_lot::Mutex; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; + +/// Folders whose contents never belong to a plugin package. +const SKIPPED_DIRS: [&str; 3] = [".git", "target", "node_modules"]; + +#[derive(Default)] +pub(super) struct LinkedWatches { + watchers: Mutex>, + /// Folders with a change that has not been reloaded yet. + changed: Arc>>, + /// Signalled when a folder is added to `changed`. + wake: Arc, + /// Folders that could not be watched, so the warning is given once. + failed: Mutex>, +} + +impl LinkedWatches { + /// What the event pump waits on; signalled when a linked folder changes. + pub fn wake(&self) -> Arc { + self.wake.clone() + } + + /// Watches exactly `dirs`: starts the missing watchers, stops the others. + pub fn sync(&self, dirs: &BTreeSet) { + let mut watchers = self.watchers.lock(); + watchers.retain(|dir, _| dirs.contains(dir)); + self.changed.lock().retain(|dir| dirs.contains(dir)); + self.failed.lock().retain(|dir| dirs.contains(dir)); + for dir in dirs { + if watchers.contains_key(dir) { + continue; + } + match self.watch(dir) { + Ok(watcher) => { + watchers.insert(dir.clone(), watcher); + } + Err(e) => { + if self.failed.lock().insert(dir.clone()) { + tracing::warn!("linked plugin {} is not reloaded on change: {e}", dir.display()); + } + } + } + } + } + + fn watch(&self, dir: &Path) -> ide_core::IdeResult { + let changed = Arc::downgrade(&self.changed); + let wake = Arc::downgrade(&self.wake); + // Events carry canonical paths. + let root = dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()); + let key = dir.to_path_buf(); + let on_change = Box::new(move |batch: &FsBatch| { + if !affects_plugin(&root, batch) { + return; + } + let (Some(changed), Some(wake)) = (changed.upgrade(), wake.upgrade()) else { return }; + changed.lock().insert(key.clone()); + wake.notify(); + }); + let excludes = SKIPPED_DIRS.iter().map(|d| (*d).to_owned()).collect(); + Watcher::start(dir, excludes, Arc::new(NullSink), on_change) + } + + /// The folders changed since the last call. + pub fn take_changed(&self) -> Vec { + std::mem::take(&mut *self.changed.lock()).into_iter().collect() + } + + /// Stops every watch. + pub fn clear(&self) { + self.watchers.lock().clear(); + self.changed.lock().clear(); + self.failed.lock().clear(); + } +} + +/// Whether `batch` holds a change that can affect the package in `root`. Ignored files +/// count: a generated theme is often listed in the package's `.gitignore`. +fn affects_plugin(root: &Path, batch: &FsBatch) -> bool { + batch.created.iter().chain(&batch.modified).chain(&batch.removed).chain(&batch.ignored).any(|p| relevant(root, p)) +} + +fn relevant(root: &Path, path: &Path) -> bool { + let rel = path.strip_prefix(root).unwrap_or(path); + if rel.components().any(|c| matches!(c, Component::Normal(n) if SKIPPED_DIRS.iter().any(|d| n == *d))) { + return false; + } + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return true }; + !(name.ends_with('~') + || name.ends_with(".swp") + || name.ends_with(".swx") + || name.starts_with(".#") + || (name.starts_with('#') && name.ends_with('#')) + || name == "4913" + || name == ".DS_Store") +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + #[test] + fn only_package_files_count() { + let root = Path::new("/links/theme"); + for kept in ["theme.json", "themes/dark.json", "dist/plugin.wasm", "plugin.toml", ".hidden.json"] { + assert!(relevant(root, &root.join(kept)), "{kept}"); + } + for skipped in [ + ".git/index", + "target/debug/build.rs", + "sub/node_modules/x/package.json", + "theme.json~", + ".theme.json.swp", + ".#theme.json", + "#theme.json#", + "4913", + ".DS_Store", + ] { + assert!(!relevant(root, &root.join(skipped)), "{skipped}"); + } + // A plugin that itself lives below a `target` folder is still watched. + let nested = Path::new("/work/target/plugin"); + assert!(relevant(nested, &nested.join("theme.json"))); + } + + #[test] + fn a_change_is_taken_once_and_wakes_the_pump() { + let watches = LinkedWatches::default(); + let dir = PathBuf::from("/links/theme"); + let wake = watches.wake(); + assert!(watches.take_changed().is_empty()); + assert!(!wake.wait(Duration::ZERO)); + watches.changed.lock().insert(dir.clone()); + watches.changed.lock().insert(dir.clone()); + assert_eq!(watches.take_changed(), vec![dir]); + assert!(watches.take_changed().is_empty(), "reloaded once"); + } +} diff --git a/crates/ide-host/src/plugins/mod.rs b/crates/ide-host/src/plugins/mod.rs index 86d43b2634..b2c33954b8 100644 --- a/crates/ide-host/src/plugins/mod.rs +++ b/crates/ide-host/src/plugins/mod.rs @@ -27,6 +27,7 @@ pub(crate) mod diagnostics; pub mod docs; mod endpoints; mod event_paths; +mod event_wake; mod execution; mod external_watch; mod files_changed; @@ -44,6 +45,7 @@ pub mod intellij; mod ipc; mod java_agents; pub mod language_features; +mod linked_watch; mod market; mod mcp; pub mod navigation; @@ -68,6 +70,7 @@ mod websocket; pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore}; pub use build_graph::{BuildGraph, GradleModule}; pub use docs::{MAX_PLUGIN_DOC, PluginDocs, explain_capabilities, plugin_docs}; +pub use event_wake::EventWake; pub(crate) use execution::plugin_run_config_owner; pub(crate) use hover::merge as merge_hover; pub use icons::{ @@ -419,6 +422,8 @@ pub struct PluginHost { queues: Mutex>, /// Serializes loading / unloading so concurrent windows can't race. lifecycle: Mutex<()>, + /// Watches of the linked plugins' folders: their changes reload them. + linked_watches: linked_watch::LinkedWatches, /// Set once the first [`load_all`](Self::load_all) has finished. initial_load: (Mutex, Condvar), /// `on-startup-finished` has fired. @@ -544,6 +549,7 @@ impl PluginHost { shared, queues: Mutex::default(), lifecycle: Mutex::new(()), + linked_watches: Default::default(), initial_load: (Mutex::new(false), Condvar::new()), startup_finished: AtomicBool::new(false), fired_activations: Mutex::new(Vec::new()), @@ -636,6 +642,7 @@ impl PluginHost { for plugin in self.in_start_order(to_start) { self.start(&plugin); } + self.watch_linked(); let (done, cv) = &self.initial_load; *done.lock() = true; cv.notify_all(); @@ -830,6 +837,41 @@ impl PluginHost { self.reconcile(); self.changed(); } + self.watch_linked(); + } + + /// Watches the folders of the loaded linked plugins and no others. + fn watch_linked(&self) { + let dirs = self + .plugins + .read() + .values() + .filter(|p| p.source == PluginSource::Linked) + .map(|p| p.dir().to_path_buf()) + .collect(); + self.linked_watches.sync(&dirs); + } + + /// What the event pump waits on instead of sleeping: signalled when a linked + /// plugin's files change, so [`flush_events`](Self::flush_events) can reload it at once. + /// Hold it rather than the host, which the pump must be able to let go of. + pub fn event_wake(&self) -> Arc { + self.linked_watches.wake() + } + + /// Reloads the linked plugins whose files changed. A plugin that no longer loads + /// shows its error like after Reload; the next valid write loads it again. + fn reload_changed_links(&self) { + for dir in self.linked_watches.take_changed() { + let id = { + let plugins = self.plugins.read(); + plugins.values().find(|p| p.source == PluginSource::Linked && p.dir() == dir).map(|p| p.id().to_owned()) + }; + let Some(id) = id else { continue }; + if let Err(e) = self.reload(&id) { + tracing::info!(plugin = %id, "reload after a file change: {}", e.message); + } + } } /// Links a development plugin folder (loaded until unlinked; granted by path). @@ -2375,13 +2417,15 @@ impl PluginHost { /// Delivers queued events: to running plugins right away, to idle ones /// (which must be activated) after [`IDLE_BATCH`], so frequent events /// don't keep waking them. Filesystem events are already debounced by - /// the watcher and bypass that delay. Call it a few times a second. + /// the watcher and bypass that delay. Call it a few times a second, and + /// whenever [`event_wake`](Self::event_wake) is signalled. pub fn flush_events(&self) { self.flush_events_at(Instant::now()); } #[doc(hidden)] pub fn flush_events_at(&self, now: Instant) { + self.reload_changed_links(); self.queue_watched_changes(now); let running: BTreeSet = self .plugins @@ -2828,6 +2872,7 @@ impl PluginHost { /// Deactivates every plugin (also done on drop). pub fn shutdown(&self) { + self.linked_watches.clear(); let (ids, actors): (Vec, Vec<_>) = { let plugins = self.plugins.read(); let ids = plugins.keys().cloned().collect(); diff --git a/crates/ide-host/src/plugins/remote_host.rs b/crates/ide-host/src/plugins/remote_host.rs index de11e3f2fa..2d279397ad 100644 --- a/crates/ide-host/src/plugins/remote_host.rs +++ b/crates/ide-host/src/plugins/remote_host.rs @@ -30,8 +30,8 @@ use parking_lot::Mutex; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; use std::path::{Component, Path, PathBuf}; -use std::sync::{Arc, Weak}; -use std::time::Duration; +use std::sync::Arc; +use std::time::{Duration, Instant}; /// The server command the desktop calls with its packages. pub const SYNC_PACKAGES: &str = "plugin_sync_packages"; @@ -319,7 +319,7 @@ impl RemotePlugins { ide_run::set_external_detection(Some(host.run_detection())); host.load_all(); host.startup_finished(); - spawn_supervision(Arc::downgrade(&host))?; + spawn_supervision(&host)?; Ok(Arc::new(Self { host, incoming: data_dir.join(INCOMING_DIR), sync: Mutex::new(()) })) } @@ -453,13 +453,17 @@ impl RemotePlugins { } } -fn spawn_supervision(host: Weak) -> IdeResult<()> { +fn spawn_supervision(host: &Arc) -> IdeResult<()> { + let wake = host.event_wake(); + let host = Arc::downgrade(host); std::thread::Builder::new().name("remote-plugins".into()).spawn(move || { - for n in 1u32.. { - std::thread::sleep(EVENT_FLUSH); + let mut tick_due = Instant::now() + EVENT_FLUSH * TICKS_PER_SUPERVISION; + loop { + wake.wait(EVENT_FLUSH); let Some(host) = host.upgrade() else { return }; host.flush_events(); - if n % TICKS_PER_SUPERVISION == 0 { + if Instant::now() >= tick_due { + tick_due = Instant::now() + EVENT_FLUSH * TICKS_PER_SUPERVISION; host.tick(); } } diff --git a/crates/ide-host/tests/plugins.rs b/crates/ide-host/tests/plugins.rs index 9b56298d1b..5b2049c4cb 100644 --- a/crates/ide-host/tests/plugins.rs +++ b/crates/ide-host/tests/plugins.rs @@ -2639,6 +2639,150 @@ fn linked_development_plugins() { assert!(again.info_of("language-toy").is_err()); } +/// Drives the event flush the app runs every 250 ms until `f` holds. +fn flushing(host: &PluginHost, mut f: impl FnMut() -> bool) -> bool { + eventually(|| { + host.flush_events(); + f() + }) +} + +/// Plugin changes announced since the last call (each reload announces one). +fn announced_changes(f: &Fixture) -> usize { + f.take_events().iter().filter(|(_, e)| matches!(e, PluginEvent::CommandsChanged)).count() +} + +/// Lets the watch of a just-linked folder go quiet: macOS reports the files written right +/// before the watch started as a first change, which reloads the plugin once. +fn settle(f: &Fixture) { + changes_within(f, Duration::from_millis(600)); + f.host.event_wake().wait(Duration::ZERO); +} + +/// Runs the flush for `span` and counts the plugin changes announced meanwhile. +fn changes_within(f: &Fixture, span: Duration) -> usize { + let until = Instant::now() + span; + while Instant::now() < until { + f.host.flush_events(); + std::thread::sleep(Duration::from_millis(25)); + } + announced_changes(f) +} + +fn night_tokens(f: &Fixture) -> Option { + let active = f.host.active_theme()?; + active.theme.tokens.get("--bg-frame").cloned() +} + +fn night_json(color: &str) -> String { + format!(r##"{{"id":"night","name":"Night","kind":"dark","tokens":{{"--bg-frame":"{color}"}}}}"##) +} + +#[test] +fn linked_plugins_reload_when_their_files_change() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let pkg = tmp.path().join("pair"); + write_theme_pair(&pkg); + f.host.link(&pkg).unwrap(); + f.host.grant("theme-pair", &Consent::default()).unwrap(); + f.host.set_theme(Some(("theme-pair", "night"))).unwrap(); + assert_eq!(night_tokens(&f).as_deref(), Some("#111111")); + settle(&f); + + // A script regenerates the theme: temp file, rename, then touches it again. + let theme = pkg.join("t/night.json"); + for color in ["#222222", "#333333", "#444444"] { + let tmp_file = pkg.join("t/night.json.tmp"); + std::fs::write(&tmp_file, night_json(color)).unwrap(); + std::fs::rename(&tmp_file, &theme).unwrap(); + } + let mut reloads = 0; + let loaded = flushing(&f.host, || { + reloads += announced_changes(&f); + night_tokens(&f).as_deref() == Some("#444444") + }); + assert!(loaded, "the final write is loaded"); + reloads += changes_within(&f, Duration::from_millis(600)); + assert_eq!(reloads, 1, "the whole burst is one batch and reloads once"); + + // A change that doesn't load shows its error; the next valid write recovers. + std::fs::write(&theme, "{ not json").unwrap(); + assert!(flushing(&f.host, || f.status("theme-pair") == PluginStatus::Failed)); + assert!(f.host.info_of("theme-pair").unwrap().error.is_some()); + std::fs::write(&theme, night_json("#555555")).unwrap(); + assert!(flushing(&f.host, || f.status("theme-pair") == PluginStatus::Static)); + assert_eq!(night_tokens(&f).as_deref(), Some("#555555"), "the selected theme survives the failed reload"); + + // Build output and VCS metadata are not part of the package. + f.take_events(); + std::fs::create_dir_all(pkg.join("target/debug")).unwrap(); + std::fs::create_dir_all(pkg.join(".git")).unwrap(); + std::fs::write(pkg.join("target/debug/out.bin"), "x").unwrap(); + std::fs::write(pkg.join(".git/index"), "x").unwrap(); + std::fs::write(pkg.join("t/night.json~"), "x").unwrap(); + assert_eq!(changes_within(&f, Duration::from_millis(600)), 0); +} + +#[test] +fn a_change_to_a_linked_plugin_wakes_the_event_pump() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let pkg = tmp.path().join("pair"); + write_theme_pair(&pkg); + f.host.link(&pkg).unwrap(); + settle(&f); + let wake = f.host.event_wake(); + assert!(!wake.wait(Duration::from_millis(50)), "idle until something changes"); + + std::fs::write(pkg.join("t/night.json"), night_json("#666666")).unwrap(); + assert!(wake.wait(Duration::from_secs(5)), "the pump is woken without waiting for its period"); + f.host.flush_events(); + assert_eq!(announced_changes(&f), 1, "the woken flush reloads the plugin"); + + // Files that are not part of the package leave the pump asleep. + std::fs::create_dir_all(pkg.join("target")).unwrap(); + std::fs::write(pkg.join("target/out.bin"), "x").unwrap(); + std::fs::write(pkg.join("t/night.json~"), "x").unwrap(); + assert!(!wake.wait(Duration::from_millis(600))); +} + +#[test] +fn only_linked_plugins_are_watched() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let linked = tmp.path().join("linked"); + write_theme_pair(&linked); + f.host.link(&linked).unwrap(); + let copied = tmp.path().join("copied"); + write_theme_pair(&copied); + std::fs::write( + copied.join("plugin.toml"), + std::fs::read_to_string(copied.join("plugin.toml")).unwrap().replace("theme-pair", "theme-copy"), + ) + .unwrap(); + f.install(&copied); + let installed = f.installed("theme-copy"); + settle(&f); + + // The installed copy is not read in place again: editing it changes nothing. + std::fs::write(installed.join("t/night.json"), night_json("#999999")).unwrap(); + assert_eq!(changes_within(&f, Duration::from_millis(600)), 0); + + // Unlinking ends the watch (and the plugin): later edits don't bring it back. + std::fs::write(linked.join("t/day.json"), r##"{"id":"day","name":"Day","kind":"light","tokens":{}}"##).unwrap(); + assert!(flushing(&f.host, || announced_changes(&f) > 0), "a linked plugin is watched"); + f.host.unlink("theme-pair").unwrap(); + f.take_events(); + std::fs::write( + linked.join("t/day.json"), + r##"{"id":"day","name":"Day","kind":"light","tokens":{"--bg-frame":"#fff"}}"##, + ) + .unwrap(); + assert_eq!(changes_within(&f, Duration::from_millis(600)), 0); + assert!(f.host.info_of("theme-pair").is_err()); +} + #[test] fn catalog_lists_sample_packages() { let f = fixture(Limits::default()); diff --git a/docs/en/plugins/guides/themes.mdx b/docs/en/plugins/guides/themes.mdx index f11eb34204..40ebc01a32 100644 --- a/docs/en/plugins/guides/themes.mdx +++ b/docs/en/plugins/guides/themes.mdx @@ -133,9 +133,12 @@ There is no build step: the package is the folder. To iterate without reinstalling, link the folder with `openidea-plugin link` (it is read in place), or put or symlink it in `/.openidea/plugins//` of a trusted project. -Then press **Reload** on the plugin, or run the **Reload Plugins** action, to pick up your -edits. If a file or value is invalid, **Settings › Plugins** shows the load error with the -file and line. +A linked plugin reloads by itself shortly after any file in its folder changes, so a theme +file rewritten by a script (a wallpaper colour generator, say) restyles the IDE straight away, +including when it is the theme in use. A project plugin does not: press **Reload** on it, or run +the **Reload Plugins** action. **Reload** also works for linked plugins. If a file or value is +invalid, **Settings › Plugins** shows the load error with the file and line; the next valid +save loads it again. To share a theme, publish it like any plugin; see [Packaging](/en/plugins/publishing/packaging). diff --git a/docs/en/plugins/lifecycle.mdx b/docs/en/plugins/lifecycle.mdx index c97719381d..5212bbb0ad 100644 --- a/docs/en/plugins/lifecycle.mdx +++ b/docs/en/plugins/lifecycle.mdx @@ -173,7 +173,7 @@ The [`settings-controls` fixture](https://github.com/l0ng-ai/openidea/tree/main/ ## Reload, update and roll back -- **Reload while developing:** select the plugin in **Settings › Plugins** and click **Reload from disk**, or run the **Reload Plugins** action. Linked plugins are read from their folder, so a rebuild plus reload picks up new code and manifest changes. +- **Reload while developing:** select the plugin in **Settings › Plugins** and click **Reload from disk**, or run the **Reload Plugins** action. Linked plugins are read from their folder, so a rebuild plus reload picks up new code and manifest changes. Linked plugins also reload by themselves shortly after any file in their folder changes (a rebuilt `dist/plugin.wasm`, a regenerated theme), ignoring `.git`, `target`, `node_modules` and editor temp files. If the plugin no longer loads, **Settings › Plugins** shows the error and the next valid save loads it again. Installed and project plugins are not watched; reload those by hand. - **Updates:** the IDE checks the marketplace daily. When it finds newer versions of installed plugins it says so once, with **Update All**; the gear menu has **Update All Plugins** too. An update that asks for nothing new keeps the existing grants. - **Versions on disk:** installed plugins live in `/plugins///` with an `active` pointer that is switched only once the new version is in place. If an update's code fails to start the first time, the IDE rolls back to the previous version automatically and tells you why. **Roll Back to ``** in the plugin's details does it by hand. - **Disable and uninstall:** disabling stops the code and withdraws its contributions; storage stays. Uninstalling removes the plugin, its storage and its private directory. diff --git a/docs/zh/plugins/guides/themes.mdx b/docs/zh/plugins/guides/themes.mdx index 2726715ded..d50630c229 100644 --- a/docs/zh/plugins/guides/themes.mdx +++ b/docs/zh/plugins/guides/themes.mdx @@ -117,8 +117,9 @@ editor-scheme = "themes/harbor-night.scheme.json" # 可选 想不重新安装就反复修改,可以用 `openidea-plugin link` 链接文件夹(直接从原处读取),或者把它放进(或软链接到)受信任项目的 -`/.openidea/plugins//`。之后在插件上点 **重新加载**,或执行 **重新加载插件** 动作,即可加载修改。 -文件或取值无效时,**设置 › 插件** 会显示加载错误以及所在文件和行号。 +`/.openidea/plugins//`。链接的插件会在其文件夹中的任何文件变化后不久自动重新加载,所以脚本(例如根据壁纸生成配色的工具)重写主题文件后,IDE +会立即换色,正在使用的主题也一样。项目插件不会自动重新加载:在插件上点 **重新加载**,或执行 **重新加载插件** 动作。链接的插件也可以手动 **重新加载**。 +文件或取值无效时,**设置 › 插件** 会显示加载错误以及所在文件和行号;下一次有效保存后会重新加载。 分享主题的方式与其他插件相同,见 [打包](/zh/plugins/publishing/packaging)。 diff --git a/docs/zh/plugins/lifecycle.mdx b/docs/zh/plugins/lifecycle.mdx index dca15af436..8779ce843d 100644 --- a/docs/zh/plugins/lifecycle.mdx +++ b/docs/zh/plugins/lifecycle.mdx @@ -173,7 +173,7 @@ API 1.3 增加了多页设置(`[[contributes.settings.pages]]`)、分组、 ## 重新加载、更新与回滚 -- **开发时重新加载:** 在 **设置 › 插件** 中选中插件并点击 **从磁盘重新加载**,或运行 **重新加载插件** 操作。链接的插件从其文件夹读取,所以重新构建后再加载就能用上新的代码和清单。 +- **开发时重新加载:** 在 **设置 › 插件** 中选中插件并点击 **从磁盘重新加载**,或运行 **重新加载插件** 操作。链接的插件从其文件夹读取,所以重新构建后再加载就能用上新的代码和清单。链接的插件还会在其文件夹中的任何文件变化后不久自动重新加载(重新构建的 `dist/plugin.wasm`、重新生成的主题),`.git`、`target`、`node_modules` 和编辑器临时文件除外。插件无法加载时,**设置 › 插件** 会显示错误,下一次有效保存后会重新加载。已安装的插件和项目插件不会被监视,需要手动重新加载。 - **更新:** IDE 每天检查一次插件市场。发现已安装插件有新版本时会提示一次,并提供 **全部更新**;齿轮菜单里也有 **更新全部插件**。不要求新能力的更新沿用已有授权。 - **磁盘上的版本:** 已安装的插件位于 `/plugins///`,有一个 `active` 指针,只有新版本完全就位后才会切换。更新后的代码第一次启动就失败时,IDE 会自动回滚到之前的版本并告诉你原因。插件详情中的 **回滚到 ``** 可以手动回滚。 - **禁用与卸载:** 禁用会停止代码并撤回其贡献,存储保留。卸载会删除插件、它的存储和私有目录。 diff --git a/src-tauri/src/commands/plugin.rs b/src-tauri/src/commands/plugin.rs index b41d89f119..f9f881d294 100644 --- a/src-tauri/src/commands/plugin.rs +++ b/src-tauri/src/commands/plugin.rs @@ -29,8 +29,8 @@ const INITIAL_LOAD_WAIT: Duration = Duration::from_secs(5); const STARTUP_FINISHED_DELAY: Duration = Duration::from_millis(1500); /// How often the marketplace index is read again (revocations). const MARKET_REFRESH: Duration = Duration::from_secs(24 * 60 * 60); -/// Period of [`PluginHost::flush_events`]; [`PluginHost::tick`] runs every -/// [`TICKS_PER_SUPERVISION`] of them. +/// Longest wait between two [`PluginHost::flush_events`] (a linked plugin's change wakes the +/// pump earlier); [`PluginHost::tick`] runs every [`TICKS_PER_SUPERVISION`] of them. const EVENT_FLUSH: Duration = Duration::from_millis(250); const TICKS_PER_SUPERVISION: u32 = 20; /// Plugin changes (install, enable, grants) reach remote servers after this quiet time. @@ -135,15 +135,18 @@ pub fn create_host(app: &AppHandle, data_dir: &Path, project_host: &Arc= tick_due { + tick_due = std::time::Instant::now() + EVENT_FLUSH * TICKS_PER_SUPERVISION; host.tick(); } if std::time::Instant::now() >= market_due { diff --git a/src/features/plugins/__tests__/plugins.test.tsx b/src/features/plugins/__tests__/plugins.test.tsx index f71a819926..0320130ced 100644 --- a/src/features/plugins/__tests__/plugins.test.tsx +++ b/src/features/plugins/__tests__/plugins.test.tsx @@ -32,6 +32,7 @@ import { pluginActionId, startPluginBridge, syncProjection, + trackPluginTheme, } from "../bridge"; import { iconResolver, selectedIconTheme, useIconThemes } from "../iconThemes"; import { markerIcon, placeMarkers } from "../lineMarkerGutter"; @@ -429,6 +430,47 @@ describe("store", () => { } }); + it("restyles the selected plugin theme in place when its plugin reloads with new tokens", async () => { + const stop = [syncProjection(), followThemeSetting(), trackPluginTheme()]; + const root = document.documentElement; + const observer = new MutationObserver(() => {}); + try { + useProject.setState({ settings: { appearance: { theme: "plugin:theme-harbor-night/harbor-night" } } as never }); + await refreshPlugins(); + await waitFor(() => expect(usePlugins.getState().activeTheme?.theme.id).toBe("harbor-night")); + expect(document.getElementById(PLUGIN_THEME_STYLE_ID)?.textContent).toContain("--bg-frame: #1f252e"); + + // A reload swaps the contribution: the host announces the new theme and the list follows. + const snapshot = await backend.list(); + const edit = }>(t: T): T => ({ + ...t, + tokens: { ...t.tokens, "--bg-frame": "#123456" }, + }); + const reloaded = { + ...snapshot, + ui: snapshot.ui.map((c) => (c.point === "themes" ? { ...c, decl: edit(c.decl as never) } : c)), + activeTheme: { ...snapshot.activeTheme!, theme: edit(snapshot.activeTheme!.theme) }, + }; + const setTheme = vi.spyOn(backend, "setTheme"); + setPluginsBackend({ ...backend, list: async () => reloaded }); + observer.observe(root, { attributes: true, attributeOldValue: true, attributeFilter: ["data-plugin-theme"] }); + handlePluginEvent({ type: "themeChanged", theme: reloaded.activeTheme }); + expect(document.getElementById(PLUGIN_THEME_STYLE_ID)?.textContent).toContain("--bg-frame: #123456"); + await refreshPlugins(); + await new Promise((r) => setTimeout(r, 0)); + + expect(document.getElementById(PLUGIN_THEME_STYLE_ID)?.textContent).toContain("--bg-frame: #123456"); + expect(setTheme).not.toHaveBeenCalled(); + // The theme attribute was never dropped on the way (no flash to the built-in theme). + expect(observer.takeRecords().every((r) => r.oldValue === "theme-harbor-night/harbor-night")).toBe(true); + expect(usePlugins.getState().activeTheme?.theme.tokens["--bg-frame"]).toBe("#123456"); + } finally { + observer.disconnect(); + stop.forEach((s) => s()); + useProject.setState({ settings: null as never }); + } + }); + it("leaves a theme another window selected alone until this window's settings change", async () => { const stop = [syncProjection(), followThemeSetting()]; try { diff --git a/src/features/plugins/themeRuntime.ts b/src/features/plugins/themeRuntime.ts index 803a2ed29e..c34aad1d56 100644 --- a/src/features/plugins/themeRuntime.ts +++ b/src/features/plugins/themeRuntime.ts @@ -223,7 +223,20 @@ export function followThemeSetting(): () => void { void selectPluginTheme(want && target ? want.pluginId : null, want && target ? want.themeId : null); }; reconcile(); + // A reloaded plugin replaces its theme (removed, then added again within one synchronous + // sync): looking in between would read the selected theme as gone and deselect it. + let scheduled = false; + let stopped = false; + const reconcileSoon = () => { + if (scheduled) return; + scheduled = true; + queueMicrotask(() => { + scheduled = false; + if (!stopped) reconcile(); + }); + }; const disposers = [ + () => (stopped = true), // Not on the host's theme changing: another window selects it before this one's settings // say so, and selecting this window's choice back would flip it until they agree. usePlugins.subscribe((s, prev) => { @@ -233,7 +246,7 @@ export function followThemeSetting(): () => void { if (s.settings?.appearance !== prev.settings?.appearance) reconcile(); }), useThemeOverride.subscribe(reconcile), - useContributedThemes.subscribe(reconcile), + useContributedThemes.subscribe(reconcileSoon), subscribeScheme(reconcile), ]; return () => disposers.forEach((d) => d());