Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

feat(settings): put the plugins on one page with the sidebar's panels

RoversX80731c5e6535
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftl
index 452e8acf..4cc8c794 100644
--- a/thinkterm-i18n/i18n/de-DE.ftl
+++ b/thinkterm-i18n/i18n/de-DE.ftl
@@ -715,7 +715,7 @@ settings-about-privacy = Datenschutz
settings-about-config-file = Konfigurationsdatei
settings-about-data-folder = Datenordner
# --- Seitenleiste ----------------------------------------------------------
-settings-section-sidebar = Seitenleiste
+settings-section-sidebar = Seitenleiste & Plugins
settings-sidebar-description = Wählen Sie aus, welche Panels die rechte Seitenleiste anbietet. Schalten Sie alle aus, verschwindet die Seitenleiste.
settings-sidebar-files-description = Durchsuchen Sie das Arbeitsverzeichnis und Remote-Verzeichnisse über SFTP.
settings-sidebar-notes-description = Markdown-Notizen, die beim Projekt liegen.
@@ -739,6 +739,27 @@ settings-update-method-windows = Vom Windows-Installer installiert; ein Update l
settings-update-method-source = Dies ist ein Build aus dem Quellcode: Holen Sie das Repository und bauen Sie es erneut.
settings-update-method-unknown = Diese Kopie wurde nicht vom Installationsskript installiert, deshalb ersetzt ThinkTerm sie nicht; aktualisieren Sie sie so, wie sie installiert wurde.
+# --- Plugins: Einstellungen › Plugins ---
+settings-section-plugins = Plugins
+settings-plugins-description = Plugins erscheinen nur in der rechten Seitenleiste. Installierte schalten und laden Sie hier neu.
+settings-plugins-folder = Plugin-Ordner
+settings-plugins-open-folder = Öffnen
+settings-plugins-reload = Plugins neu laden
+settings-plugins-reload-description = Hinzugefügte oder entfernte Plugins finden und laufende Plugins neu starten.
+settings-plugins-reload-button = Neu laden
+settings-plugins-builtin = Integriert
+settings-plugins-builtin-panel = Integriert · Stellt das Panel „{ $panel }“ in der rechten Seitenleiste bereit
+settings-plugins-starting = Wird gestartet …
+settings-plugins-running = Läuft
+settings-plugins-crashed = Angehalten: { $reason }
+settings-plugins-failed = Fehlgeschlagen: { $reason }
+settings-plugins-invalid = Nicht verwendbar: { $reason }
+settings-plugins-unsupported = Auf diesem System nicht verfügbar
+settings-plugins-unusable = Nicht verfügbar
+settings-plugins-loading = Plugins werden geladen …
+settings-plugins-unavailable = Plugins sind nicht verfügbar: { $reason }
+settings-plugins-refused = Das Plugin wurde nicht geändert: { $reason }
+
# --- Web: die Terminals dieses Rechners im Browser erreichen ---
settings-section-web = Web
settings-web-heading = Diese Terminals im Browser erreichen
diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftl
index f9bda4e7..401e2bc9 100644
--- a/thinkterm-i18n/i18n/en-US.ftl
+++ b/thinkterm-i18n/i18n/en-US.ftl
@@ -715,7 +715,7 @@ settings-about-privacy = Privacy
settings-about-config-file = Config File
settings-about-data-folder = Data Folder
# --- Sidebar ---------------------------------------------------------------
-settings-section-sidebar = Sidebar
+settings-section-sidebar = Sidebar & Plugins
settings-sidebar-description = Choose which panels the right sidebar offers. Turn them all off and the sidebar goes away.
settings-sidebar-files-description = Browse the working directory, and remote directories over SFTP.
settings-sidebar-notes-description = Markdown notes kept alongside the project.
@@ -739,6 +739,27 @@ settings-update-method-windows = Installed by the Windows installer; installing
settings-update-method-source = This is a build from source: pull the repository and build again.
settings-update-method-unknown = This copy was not installed by the install script, so ThinkTerm will not replace it; update it the way it was installed.
+# --- Plugins: Settings › Plugins ---
+settings-section-plugins = Plugins
+settings-plugins-description = Plugins show only in the right sidebar. Installed ones are switched and reloaded here.
+settings-plugins-folder = Plugins folder
+settings-plugins-open-folder = Open
+settings-plugins-reload = Reload plugins
+settings-plugins-reload-description = Find plugins that were added or removed, and restart the ones that are running.
+settings-plugins-reload-button = Reload
+settings-plugins-builtin = Built in
+settings-plugins-builtin-panel = Built in · Provides the { $panel } panel in the right sidebar
+settings-plugins-starting = Starting…
+settings-plugins-running = Running
+settings-plugins-crashed = Stopped: { $reason }
+settings-plugins-failed = Failed: { $reason }
+settings-plugins-invalid = Can't be used: { $reason }
+settings-plugins-unsupported = Not available on this system
+settings-plugins-unusable = Unavailable
+settings-plugins-loading = Loading plugins…
+settings-plugins-unavailable = Plugins are unavailable: { $reason }
+settings-plugins-refused = The plugin was not changed: { $reason }
+
# --- Web: browser access to this machine's terminals ---
settings-section-web = Web
settings-web-heading = Reach these terminals from a browser
diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftl
index 8bd47d9c..c6607d1e 100644
--- a/thinkterm-i18n/i18n/fr-FR.ftl
+++ b/thinkterm-i18n/i18n/fr-FR.ftl
@@ -712,7 +712,7 @@ settings-about-privacy = Confidentialité
settings-about-config-file = Fichier de configuration
settings-about-data-folder = Dossier de données
# --- Barre latérale --------------------------------------------------------
-settings-section-sidebar = Barre latérale
+settings-section-sidebar = Panneaux et extensions
settings-sidebar-description = Choisissez les panneaux proposés par la barre latérale droite. Désactivez-les tous et elle disparaît.
settings-sidebar-files-description = Parcourir le répertoire de travail, et les répertoires distants via SFTP.
settings-sidebar-notes-description = Notes Markdown conservées avec le projet.
@@ -736,6 +736,27 @@ settings-update-method-windows = Installé par l'installateur Windows ; la mise
settings-update-method-source = Ceci est une compilation depuis les sources : mettez à jour le dépôt et recompilez.
settings-update-method-unknown = Cette copie n'a pas été installée par le script d'installation ; ThinkTerm ne la remplacera pas. Mettez-la à jour comme elle a été installée.
+# --- Extensions : Réglages › Extensions ---
+settings-section-plugins = Extensions
+settings-plugins-description = Les extensions ne s'affichent que dans la barre latérale droite. Celles installées se règlent ici.
+settings-plugins-folder = Dossier des extensions
+settings-plugins-open-folder = Ouvrir
+settings-plugins-reload = Recharger les extensions
+settings-plugins-reload-description = Trouver les extensions ajoutées ou supprimées, et redémarrer celles qui tournent.
+settings-plugins-reload-button = Recharger
+settings-plugins-builtin = Intégrée
+settings-plugins-builtin-panel = Intégré · Fournit le panneau « { $panel } » de la barre latérale droite
+settings-plugins-starting = Démarrage…
+settings-plugins-running = En cours d'exécution
+settings-plugins-crashed = Arrêtée : { $reason }
+settings-plugins-failed = En échec : { $reason }
+settings-plugins-invalid = Inutilisable : { $reason }
+settings-plugins-unsupported = Indisponible sur ce système
+settings-plugins-unusable = Indisponible
+settings-plugins-loading = Chargement des extensions…
+settings-plugins-unavailable = Les extensions sont indisponibles : { $reason }
+settings-plugins-refused = L'extension n'a pas été modifiée : { $reason }
+
# --- Web : accéder à ces terminaux depuis un navigateur ---
settings-section-web = Web
settings-web-heading = Ouvrir ces terminaux depuis un navigateur
diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftl
index 68cc1040..26b5df49 100644
--- a/thinkterm-i18n/i18n/ja-JP.ftl
+++ b/thinkterm-i18n/i18n/ja-JP.ftl
@@ -700,7 +700,7 @@ settings-about-privacy = プライバシー
settings-about-config-file = 設定ファイル
settings-about-data-folder = データフォルダ
# --- サイドバー ------------------------------------------------------------
-settings-section-sidebar = サイドバー
+settings-section-sidebar = サイドバーとプラグイン
settings-sidebar-description = 右サイドバーに表示するパネルを選びます。すべてオフにするとサイドバー自体が消えます。
settings-sidebar-files-description = 作業ディレクトリと、SFTP 経由のリモートディレクトリを閲覧します。
settings-sidebar-notes-description = プロジェクトと一緒に置く Markdown のノートです。
@@ -724,6 +724,27 @@ settings-update-method-windows = Windows インストーラーでインストー
settings-update-method-source = ソースからのビルドです。リポジトリを更新して再ビルドしてください。
settings-update-method-unknown = このコピーはインストールスクリプトによるものではないため、ThinkTerm は置き換えません。元の方法で更新してください。
+# --- プラグイン:設定のプラグインページ ---
+settings-section-plugins = プラグイン
+settings-plugins-description = プラグインは右サイドバーにだけ表示されます。インストールしたものはここでオン・オフ、再読み込みします。
+settings-plugins-folder = プラグインフォルダー
+settings-plugins-open-folder = 開く
+settings-plugins-reload = プラグインを再読み込み
+settings-plugins-reload-description = 追加・削除されたプラグインを見つけ、実行中のプラグインを再起動します。
+settings-plugins-reload-button = 再読み込み
+settings-plugins-builtin = 内蔵
+settings-plugins-builtin-panel = 内蔵 · 右サイドバーの「{ $panel }」パネルを提供します
+settings-plugins-starting = 起動中…
+settings-plugins-running = 実行中
+settings-plugins-crashed = 停止しました:{ $reason }
+settings-plugins-failed = 失敗しました:{ $reason }
+settings-plugins-invalid = 使用できません:{ $reason }
+settings-plugins-unsupported = このシステムでは使用できません
+settings-plugins-unusable = 使用不可
+settings-plugins-loading = プラグインを読み込み中…
+settings-plugins-unavailable = プラグインは利用できません:{ $reason }
+settings-plugins-refused = プラグインを変更できませんでした:{ $reason }
+
# --- Web: ブラウザからこのマシンの端末へ ---
settings-section-web = Web
settings-web-heading = ブラウザからこの端末を開く
diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftl
index c0041110..eeb8e860 100644
--- a/thinkterm-i18n/i18n/zh-CN.ftl
+++ b/thinkterm-i18n/i18n/zh-CN.ftl
@@ -700,7 +700,7 @@ settings-about-privacy = 隐私
settings-about-config-file = 配置文件
settings-about-data-folder = 数据目录
# --- 侧栏 ------------------------------------------------------------------
-settings-section-sidebar = 侧栏
+settings-section-sidebar = 侧栏与插件
settings-sidebar-description = 选择右侧栏提供哪些面板。全部关掉,侧栏就不显示了。
settings-sidebar-files-description = 浏览工作目录,以及通过 SFTP 浏览远程目录。
settings-sidebar-notes-description = 与项目放在一起的 Markdown 笔记。
@@ -724,6 +724,27 @@ settings-update-method-windows = 由 Windows 安装器安装;安装更新会下
settings-update-method-source = 这是从源码构建的版本:拉取仓库后重新构建。
settings-update-method-unknown = 这个副本不是由安装脚本安装的,ThinkTerm 不会替换它;请按原来的安装方式更新。
+# --- 插件:设置里的插件页 ---
+settings-section-plugins = 插件
+settings-plugins-description = 插件只会显示在右侧栏里。装进来的插件在这里开关、重新加载。
+settings-plugins-folder = 插件文件夹
+settings-plugins-open-folder = 打开
+settings-plugins-reload = 重新加载插件
+settings-plugins-reload-description = 找出新加或删掉的插件,并重启正在运行的插件。
+settings-plugins-reload-button = 重新加载
+settings-plugins-builtin = 内置
+settings-plugins-builtin-panel = 内置 · 提供右侧栏的「{ $panel }」面板
+settings-plugins-starting = 正在启动…
+settings-plugins-running = 运行中
+settings-plugins-crashed = 已停止:{ $reason }
+settings-plugins-failed = 出错:{ $reason }
+settings-plugins-invalid = 无法使用:{ $reason }
+settings-plugins-unsupported = 不支持这个系统
+settings-plugins-unusable = 不可用
+settings-plugins-loading = 正在加载插件…
+settings-plugins-unavailable = 插件暂时不可用:{ $reason }
+settings-plugins-refused = 没能修改插件:{ $reason }
+
# --- 网页端:用浏览器访问这台机器的终端 ---
settings-section-web = 网页
settings-web-heading = 用浏览器打开这里的终端
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index 889d8f11..bdf1b06c 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -55,6 +55,7 @@ mod native_paths;
mod native_settings;
mod overlay;
mod perf;
+mod plugins;
mod quad;
mod renderstate;
mod resize_increment_calculator;
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rs
index 1289dc04..629d9d40 100644
--- a/wezterm-gui/src/native_settings.rs
+++ b/wezterm-gui/src/native_settings.rs
@@ -468,7 +468,15 @@ pub(crate) struct NativeChromeSettings {
/// a separate window, so turning one back on is still reachable.
pub(crate) right_sidebar_files_enabled: Option<bool>,
pub(crate) right_sidebar_notes_enabled: Option<bool>,
+ /// The Snippets panel's own switch from before Snippets was a plugin.
+ /// Only ever read to carry an "off" over to the plugin's switch, once
+ /// (`plugins::follow_snippets_switch`), and cleared then.
pub(crate) right_sidebar_snippets_enabled: Option<bool>,
+ /// The Snippets plugin's switch as the plugin host last said it, so the
+ /// panel is offered or not from the start; the host's switch, which the
+ /// panel's in Settings › Sidebar & Plugins flips, is the one that
+ /// counts.
+ pub(crate) snippets_plugin_enabled: Option<bool>,
/// Feature toggle for agent status detection and the right-sidebar
/// Agents panel. Absent means on -- it was off by default while the
/// detection was new, and is a panel toggle like the three above now.
@@ -1366,10 +1374,10 @@ pub(crate) fn right_sidebar_panel_toggles() -> RightSidebarPanelToggles {
RightSidebarPanelToggles {
files: settings.chrome.right_sidebar_files_enabled.unwrap_or(true),
notes: settings.chrome.right_sidebar_notes_enabled.unwrap_or(true),
- snippets: settings
- .chrome
- .right_sidebar_snippets_enabled
- .unwrap_or(true),
+ // An "off" from before Snippets was a plugin stands until the
+ // plugin's switch has taken it over.
+ snippets: settings.chrome.right_sidebar_snippets_enabled != Some(false)
+ && settings.chrome.snippets_plugin_enabled.unwrap_or(true),
}
}
diff --git a/wezterm-gui/src/plugins.rs b/wezterm-gui/src/plugins.rs
new file mode 100644
index 00000000..8a8057ef
--- /dev/null
+++ b/wezterm-gui/src/plugins.rs
@@ -0,0 +1,453 @@
+//! ThinkTerm's plugins, as the desktop sees them.
+//!
+//! Every plugin lives in the plugin host, the thinkterm-plugin-server
+//! process (see thinkterm-plugin-channel): the desktop shows what the host
+//! answers and forwards what the user does. This holds what the windows
+//! share -- the one session with the host, the plugin list it last sent,
+//! and the windows to tell when something changes. Snippets is built on it
+//! (`crate::snippets`), and so is the plugin list in Settings › Sidebar &
+//! Plugins. Nothing of a plugin shows outside the sidebar.
+//!
+//! The session is let go once nothing has used it for a while. The list
+//! stays as what was last heard, and is asked for afresh on the next use:
+//! it is never taken for current once the session that sent it is gone.
+
+use crate::termwindow::{TermWindow, TermWindowNotif};
+use parking_lot::{Mutex, MutexGuard};
+use serde_json::Value;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+use thinkterm_plugin_channel::client::{Answer, Host, Notice, Session};
+use thinkterm_plugin_channel::registry::{self as api, Info};
+use window::{Window, WindowOps};
+
+/// How long the plugins may go unused before the session is let go.
+const RELEASE_AFTER: Duration = Duration::from_secs(120);
+/// How often that is looked at.
+const RELEASE_CHECK: Duration = Duration::from_secs(15);
+
+/// The plugin list as last heard, and asking for it: one request at a time,
+/// with changes that arrive meanwhile folded into one more.
+struct Listing {
+ plugins: Option<Vec<Info>>,
+ /// The language the list was last asked for in, answered or not; one in
+ /// another is asked for again.
+ locale: &'static str,
+ asking: bool,
+ /// What was last heard is out of date: something changed since, or the
+ /// session that sent it is gone.
+ stale: bool,
+}
+
+impl Listing {
+ /// Whether to ask for the list now, in `locale`, marking it asked: when
+ /// what was heard is out of date or in another language, and nothing is
+ /// asking. A list that cannot be had is not asked for again until
+ /// something changes.
+ fn begin(&mut self, locale: &'static str) -> bool {
+ if self.locale != locale {
+ self.stale = true;
+ }
+ if self.asking || !self.stale {
+ return false;
+ }
+ self.asking = true;
+ self.stale = false;
+ self.locale = locale;
+ true
+ }
+
+ /// The answer came: the plugins, or `None` when there was an error and
+ /// what was shown stays.
+ fn heard(&mut self, plugins: Option<Vec<Info>>) {
+ self.asking = false;
+ if let Some(plugins) = plugins {
+ self.plugins = Some(plugins);
+ }
+ }
+}
+
+struct Shared {
+ session: Option<Arc<Session>>,
+ /// Counts sessions, so a release check stops with the one it watched.
+ generation: u64,
+ /// The windows showing a panel a plugin sends events about -- the
+ /// Snippets panel -- since the session started. A handful at most; one
+ /// that has closed ignores what it is told.
+ windows: Vec<Window>,
+ /// Why the host cannot be reached, while it cannot.
+ trouble: Option<String>,
+ last_used: Option<Instant>,
+ listing: Listing,
+ /// Switches flipped here whose change is on its way, and to what.
+ switching: Vec<(String, bool)>,
+ /// Why the host refused the last change asked of it here.
+ refused: Option<String>,
+}
+
+static SHARED: Mutex<Shared> = parking_lot::const_mutex(Shared {
+ session: None,
+ generation: 0,
+ windows: Vec::new(),
+ trouble: None,
+ last_used: None,
+ listing: Listing {
+ plugins: None,
+ locale: "",
+ asking: false,
+ stale: true,
+ },
+ switching: Vec::new(),
+ refused: None,
+});
+
+/// The shared state, marked as in use, with a session to the host. On the
+/// GUI thread: it may start the release check.
+fn in_use() -> MutexGuard<'static, Shared> {
+ let mut shared = SHARED.lock();
+ shared.last_used = Some(Instant::now());
+ if shared.session.is_none() {
+ let started = Host::for_this_build().and_then(|host| Session::start(host, on_notice));
+ match started {
+ Ok(session) => {
+ shared.session = Some(Arc::new(session));
+ shared.generation += 1;
+ release_when_idle(shared.generation);
+ }
+ Err(err) => shared.trouble = Some(format!("{err:#}")),
+ }
+ }
+ shared
+}
+
+/// `window` shows a panel a plugin sends events about: it is told of them,
+/// and the session is kept.
+pub fn window_in_use(window: &Window) {
+ let mut shared = in_use();
+ if !shared.windows.contains(window) {
+ shared.windows.push(window.clone());
+ }
+}
+
+/// Why the host cannot be reached, while it cannot.
+pub fn trouble() -> Option<String> {
+ SHARED.lock().trouble.clone()
+}
+
+/// Asks `plugin` something, waiting `wait` for the answer, which `reply` is
+/// given on the session's thread -- or why there is none.
+pub fn call_within(
+ plugin: &str,
+ body: Value,
+ wait: Duration,
+ reply: impl FnOnce(Answer) + Send + 'static,
+) {
+ let (session, trouble) = {
+ let shared = in_use();
+ (shared.session.clone(), shared.trouble.clone())
+ };
+ // Called with the lock let go: a session that has ended answers at once.
+ match session {
+ Some(session) => session.call_within(plugin, body, wait, reply),
+ None => {
+ reply(Err(trouble.unwrap_or_else(|| {
+ "the plugin host cannot be reached".into()
+ })))
+ }
+ }
+}
+
+/// [`call_within`], with the wait a call is given.
+pub fn call(plugin: &str, body: Value, reply: impl FnOnce(Answer) + Send + 'static) {
+ call_within(
+ plugin,
+ body,
+ thinkterm_plugin_channel::client::CALL_TIMEOUT,
+ reply,
+ )
+}
+
+/// Has every window showing a plugin's panel apply `change` to itself.
+pub fn tell_windows(change: fn(&mut TermWindow)) {
+ let windows: Vec<Window> = SHARED.lock().windows.clone();
+ promise::spawn::spawn_into_main_thread(async move {
+ for window in windows {
+ let repaint = window.clone();
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ change(term_window);
+ repaint.invalidate();
+ })));
+ }
+ })
+ .detach();
+}
+
+/// What shows the list brought up to date: the settings window.
+fn list_changed() {
+ promise::spawn::spawn_into_main_thread(async move {
+ crate::settings_window::invalidate_open_settings_window();
+ })
+ .detach();
+}
+
+fn on_notice(notice: Notice) {
+ match notice {
+ // Whatever the host said before, it is asked again.
+ Notice::Connected => {
+ {
+ let mut shared = SHARED.lock();
+ shared.trouble = None;
+ shared.listing.stale = true;
+ }
+ ask_for_list();
+ tell_windows(TermWindow::snippets_changed);
+ }
+ Notice::Event { plugin, body } if plugin == api::PLUGIN => {
+ match serde_json::from_value(body) {
+ Ok(api::Event::Changed) => {
+ SHARED.lock().listing.stale = true;
+ ask_for_list();
+ }
+ Err(err) => log::warn!("a plugin list event that does not read: {err}"),
+ }
+ }
+ Notice::Event { plugin, body } => crate::snippets::on_event(&plugin, body),
+ Notice::Trouble(why) => {
+ SHARED.lock().trouble = Some(why);
+ // Rows already on show stay; an empty panel says why.
+ tell_windows(|_| {});
+ list_changed();
+ }
+ }
+}
+
+/// Lets the session go once nothing has used it for a while, and the
+/// windows' rows with it -- without asking them to paint, which would
+/// only ask for them again.
+fn release_when_idle(generation: u64) {
+ promise::spawn::spawn(async move {
+ loop {
+ smol::Timer::after(RELEASE_CHECK).await;
+ let mut shared = SHARED.lock();
+ if shared.generation != generation || shared.session.is_none() {
+ return;
+ }
+ let idle = shared
+ .last_used
+ .map_or(true, |used| used.elapsed() >= RELEASE_AFTER);
+ if !idle {
+ continue;
+ }
+ shared.session = None;
+ shared.trouble = None;
+ shared.listing.stale = true;
+ shared.listing.asking = false;
+ for window in shared.windows.drain(..) {
+ window.notify(TermWindowNotif::Apply(Box::new(|term_window| {
+ term_window.snippets_released();
+ })));
+ }
+ return;
+ }
+ })
+ .detach();
+}
+
+/// Asks for the list if what was last heard is out of date and nothing is
+/// asking already.
+fn ask_for_list() {
+ let (session, locale) = {
+ let mut shared = SHARED.lock();
+ let Some(session) = shared.session.clone() else {
+ return;
+ };
+ let locale = crate::i18n::current_locale();
+ if !shared.listing.begin(locale) {
+ return;
+ }
+ (session, locale)
+ };
+ let request = api::Request::List {
+ locale: locale.to_string(),
+ };
+ session.call(api::PLUGIN, to_body(&request), listed);
+}
+
+fn listed(answer: Answer) {
+ let plugins = answer.and_then(|body| from_body::<Vec<Info>>(body));
+ let heard = match plugins {
+ Ok(plugins) => Some(plugins),
+ // What was shown stays; the next change asks again.
+ Err(why) => {
+ log::warn!("plugins: {why}");
+ None
+ }
+ };
+ SHARED.lock().listing.heard(heard.clone());
+ if let Some(plugins) = heard {
+ promise::spawn::spawn_into_main_thread(async move {
+ follow_snippets_switch(&plugins);
+ })
+ .detach();
+ }
+ ask_for_list();
+ list_changed();
+}
+
+/// Someone is looking again -- Settings › Sidebar & Plugins came on show:
+/// the list is asked for afresh, and with it the host looks at the plugins
+/// directory again, finding what was installed or removed since.
+pub fn refresh() {
+ in_use().listing.stale = true;
+ ask_for_list();
+}
+
+/// The plugins as last heard, asking for them when that is out of date.
+/// `None` until the host first answers. Cheap: for painting.
+pub fn plugins() -> Option<Vec<Info>> {
+ let plugins = in_use().listing.plugins.clone();
+ ask_for_list();
+ plugins
+}
+
+/// The switch of plugin `id` as it is to be shown: the change on its way,
+/// if one is.
+pub fn switching(id: &str) -> Option<bool> {
+ SHARED
+ .lock()
+ .switching
+ .iter()
+ .find(|(switching, _)| switching == id)
+ .map(|(_, enabled)| *enabled)
+}
+
+/// Why the host refused the last change asked of it here.
+pub fn refused() -> Option<String> {
+ SHARED.lock().refused.clone()
+}
+
+/// Turns plugin `id` on or off. The switch shows the change until the host
+/// has answered, and goes back if it refuses.
+pub fn set_enabled(id: &str, enabled: bool) {
+ {
+ let mut shared = in_use();
+ shared.refused = None;
+ shared.switching.retain(|(switching, _)| switching != id);
+ shared.switching.push((id.to_string(), enabled));
+ }
+ let request = api::Request::SetEnabled {
+ id: id.to_string(),
+ enabled,
+ };
+ let id = id.to_string();
+ call(api::PLUGIN, to_body(&request), move |answer| {
+ {
+ let mut shared = SHARED.lock();
+ shared.switching.retain(|(switching, _)| *switching != id);
+ if let Err(why) = answer {
+ shared.refused = Some(why);
+ }
+ // The answer comes before the change is announced: the list
+ // on show is out of date whichever way it went.
+ shared.listing.stale = true;
+ }
+ ask_for_list();
+ list_changed();
+ });
+ list_changed();
+}
+
+/// Looks for new and removed plugins, and restarts the running ones.
+pub fn reload() {
+ SHARED.lock().refused = None;
+ let request = api::Request::Reload { id: None };
+ call(api::PLUGIN, to_body(&request), |answer| {
+ if let Err(why) = answer {
+ SHARED.lock().refused = Some(why);
+ }
+ list_changed();
+ });
+}
+
+/// Snippets appears as a panel of the right sidebar only while its plugin
+/// is on. The desktop keeps the switch as last heard, so the panel is
+/// offered at once when it starts; the host's word wins when it comes. On
+/// the GUI thread, with the settings.
+fn follow_snippets_switch(plugins: &[Info]) {
+ let Some(snippets) = plugins
+ .iter()
+ .find(|plugin| plugin.id == thinkterm_snippets::wire::PLUGIN)
+ else {
+ return;
+ };
+ let enabled = snippets.enabled;
+ let mut settings = crate::native_settings::load();
+ let chrome = &mut settings.chrome;
+ // The panel was turned off in Settings › Sidebar before it was a
+ // plugin: that choice becomes the plugin's switch, once.
+ if chrome.right_sidebar_snippets_enabled == Some(false) {
+ chrome.right_sidebar_snippets_enabled = None;
+ chrome.snippets_plugin_enabled = Some(false);
+ if let Err(err) = crate::native_settings::save(&settings) {
+ log::warn!("saving the Snippets switch: {err:#}");
+ }
+ if enabled {
+ let request = api::Request::SetEnabled {
+ id: thinkterm_snippets::wire::PLUGIN.into(),
+ enabled: false,
+ };
+ call(api::PLUGIN, to_body(&request), |_| {});
+ }
+ return;
+ }
+ if chrome.snippets_plugin_enabled == Some(enabled) {
+ return;
+ }
+ chrome.snippets_plugin_enabled = Some(enabled);
+ if let Err(err) = crate::native_settings::save(&settings) {
+ log::warn!("saving the Snippets switch: {err:#}");
+ }
+ if let Some(front_end) = crate::frontend::try_front_end() {
+ for gui_window in front_end.gui_windows() {
+ gui_window
+ .window
+ .notify(TermWindowNotif::Apply(Box::new(|term_window| {
+ term_window.right_sidebar_panels_changed();
+ })));
+ }
+ }
+}
+
+fn to_body(request: &api::Request) -> Value {
+ serde_json::to_value(request).expect("a plugin request always serialises")
+}
+
+pub fn from_body<T: serde::de::DeserializeOwned>(body: Value) -> Result<T, String> {
+ serde_json::from_value(body).map_err(|err| format!("an answer that does not read: {err}"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_list_that_cannot_be_had_is_not_asked_for_in_a_loop() {
+ let mut listing = Listing {
+ plugins: None,
+ locale: "",
+ asking: false,
+ stale: true,
+ };
+ assert!(listing.begin("en-US"));
+ assert!(!listing.begin("en-US"), "one request at a time");
+ listing.heard(None);
+ assert!(
+ !listing.begin("en-US"),
+ "an error is asked about again at once"
+ );
+ listing.stale = true;
+ assert!(listing.begin("en-US"), "a change asks again");
+ listing.heard(Some(Vec::new()));
+ assert!(listing.begin("zh-CN"), "another language asks again");
+ }
+}
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index 82c314ca..15dd9a70 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -420,6 +420,8 @@ fn initial_section() -> SettingsSection {
"workspaces" => SettingsSection::Workspaces,
"agents" => SettingsSection::Agents,
"web" => SettingsSection::Web,
+ // The plugins are on the Sidebar page, the only place they show.
+ "plugins" => SettingsSection::Sidebar,
"archived" => SettingsSection::Archived,
"keymap" => SettingsSection::Keymap,
"commandpalette" => SettingsSection::CommandPalette,
@@ -435,6 +437,9 @@ fn initial_section() -> SettingsSection {
if section == SettingsSection::Agents {
crate::agent_status::refresh_path_probe();
}
+ if section == SettingsSection::Sidebar {
+ crate::plugins::refresh();
+ }
section
}
@@ -648,10 +653,15 @@ impl SettingsSection {
"Panels",
"Files",
"Notes",
- "Snippets",
"Agents",
"Agent Panel",
"Right Sidebar",
+ "Snippets",
+ "Plugins",
+ "Plugin",
+ "Extensions",
+ "Reload",
+ "Installed",
],
Self::Backup => &[
"Backup",
@@ -844,6 +854,77 @@ fn settings_tr(id: &'static str, values: &[(&'static str, String)]) -> String {
crate::i18n::tr_args(id, &args)
}
+/// A plugin id as something a `Copy` action can carry, hashed as a token
+/// id is: two plugins in one list do not collide.
+fn plugin_key(id: &str) -> u64 {
+ web_token_key(id)
+}
+
+/// Every window lays its right sidebar out again. Not invalidate_all_windows:
+/// the sidebar's width can have gone to or from zero, and only a real
+/// relayout resizes the panes around that.
+fn right_sidebar_panels_changed() {
+ if let Some(front_end) = crate::frontend::try_front_end() {
+ for gui_window in front_end.gui_windows() {
+ gui_window
+ .window
+ .notify(crate::termwindow::TermWindowNotif::Apply(Box::new(
+ |term_window| {
+ term_window.right_sidebar_panels_changed();
+ },
+ )));
+ }
+ }
+}
+
+/// The right-sidebar panel a built-in plugin provides, by its label.
+fn builtin_panel_label(id: &str) -> Option<String> {
+ (id == thinkterm_snippets::wire::PLUGIN).then(|| crate::i18n::tr("right-mode-snippets"))
+}
+
+/// What a plugin's row says under its name: where it came from, what state
+/// it is in when that is worth saying, and what it does. A built-in one
+/// says which panel it provides.
+fn plugin_row_description(plugin: &thinkterm_plugin_channel::registry::Info) -> String {
+ use thinkterm_plugin_channel::registry::State;
+ if let Some(panel) = plugin
+ .builtin
+ .then(|| builtin_panel_label(&plugin.id))
+ .flatten()
+ {
+ return settings_tr("settings-plugins-builtin-panel", &[("panel", panel)]);
+ }
+ let origin = if plugin.builtin {
+ crate::i18n::tr("settings-plugins-builtin")
+ } else {
+ plugin.version.clone()
+ };
+ let state = match &plugin.state {
+ State::Off | State::Idle => None,
+ State::Starting => Some(crate::i18n::tr("settings-plugins-starting")),
+ State::Running => Some(crate::i18n::tr("settings-plugins-running")),
+ State::Crashed { reason } => Some(settings_tr(
+ "settings-plugins-crashed",
+ &[("reason", reason.clone())],
+ )),
+ State::Failed { reason } => Some(settings_tr(
+ "settings-plugins-failed",
+ &[("reason", reason.clone())],
+ )),
+ State::Invalid { reason } => Some(settings_tr(
+ "settings-plugins-invalid",
+ &[("reason", reason.clone())],
+ )),
+ State::Unsupported { .. } => Some(crate::i18n::tr("settings-plugins-unsupported")),
+ };
+ vec![Some(origin), state, Some(plugin.description.clone())]
+ .into_iter()
+ .flatten()
+ .filter(|part| !part.is_empty())
+ .collect::<Vec<_>>()
+ .join(" · ")
+}
+
/// A token id as something a `Copy` action can carry. Ids are random, so a
/// 64-bit hash of one is as good as the id for telling rows apart.
fn web_token_key(id: &str) -> u64 {
@@ -875,6 +956,11 @@ enum SettingsAction {
Hint(&'static str),
/// Turn one right-sidebar panel on or off.
ToggleRightSidebarPanel(crate::termwindow::RightSidebarMode),
+ /// Turn a plugin on or off. Carries `plugin_key(id)`, as RevokeWebToken
+ /// carries its token's: the list can change between press and release.
+ TogglePlugin(u64),
+ ReloadPlugins,
+ OpenPluginsFolder,
ToggleAgentDetails(&'static str),
/// Index into the archived rows cached at paint time.
UnarchiveArchivedRow(usize),
@@ -1465,6 +1551,9 @@ struct SettingsUiState {
/// must cut off the row that was under the pointer, not whichever row
/// holds that index after the list refreshed.
web_tokens: Vec<codec::WebTokenInfo>,
+ /// The plugins' switches as last painted: each one's key, its id and
+ /// the position it showed.
+ plugin_switches: Vec<(u64, String, bool)>,
/// The shells found on this machine. Refreshed when the Terminal
/// section is entered, never while painting: discovery touches the
/// filesystem, and the paint path must not.
@@ -1523,6 +1612,7 @@ impl SettingsUiState {
memory_snapshot_copied_until: None,
archived_rows: Vec::new(),
web_tokens: Vec::new(),
+ plugin_switches: Vec::new(),
shell_catalog: Vec::new(),
confirm_delete_archived: None,
confirm_stop_server: false,
@@ -3988,6 +4078,10 @@ impl SettingsWindow {
// on entry and the row paints from the cache.
self.refresh_shell_catalog();
}
+ if section == SettingsSection::Sidebar {
+ // Plugins installed or removed since are found on entry.
+ crate::plugins::refresh();
+ }
if matches!(section, SettingsSection::Update | SettingsSection::About) {
// Re-read the cache the background checker writes, so re-entering
// the page picks up a check that ran while the window sat on
@@ -4596,6 +4690,54 @@ impl SettingsWindow {
}
window.invalidate();
}
+ SettingsAction::ToggleRightSidebarPanel(
+ crate::termwindow::RightSidebarMode::Snippets,
+ ) => {
+ // Snippets is a built-in plugin, and its panel's switch is
+ // the plugin's, which every client follows. What was chosen
+ // is kept here too, so this desktop's panel follows at once.
+ self.ui.open_dropdown = None;
+ let enabled = !self
+ .right_sidebar_panel_enabled(crate::termwindow::RightSidebarMode::Snippets);
+ let chrome = &mut self.native_settings.chrome;
+ chrome.right_sidebar_snippets_enabled = None;
+ chrome.snippets_plugin_enabled = Some(enabled);
+ match crate::native_settings::save(&self.native_settings) {
+ Ok(()) => right_sidebar_panels_changed(),
+ Err(err) => {
+ self.status = format!("Unable to save sidebar panel setting: {err:#}");
+ }
+ }
+ crate::plugins::set_enabled(thinkterm_snippets::wire::PLUGIN, enabled);
+ }
+ SettingsAction::TogglePlugin(key) => {
+ self.ui.open_dropdown = None;
+ let switch = self
+ .ui
+ .plugin_switches
+ .iter()
+ .find(|(shown, _, _)| *shown == key)
+ .cloned();
+ if let Some((_, id, enabled)) = switch {
+ crate::plugins::set_enabled(&id, !enabled);
+ }
+ window.invalidate();
+ }
+ SettingsAction::ReloadPlugins => {
+ self.ui.open_dropdown = None;
+ crate::plugins::reload();
+ }
+ SettingsAction::OpenPluginsFolder => {
+ self.ui.open_dropdown = None;
+ let dir = thinkterm_plugin_channel::paths::plugins_dir();
+ // Made so there is something to open, and to drop a plugin
+ // into.
+ if let Err(err) = std::fs::create_dir_all(&dir) {
+ self.status = format!("Unable to create {}: {err:#}", dir.display());
+ } else {
+ Self::open_path(dir);
+ }
+ }
SettingsAction::ToggleRightSidebarPanel(panel) => {
self.ui.open_dropdown = None;
let slot = self.right_sidebar_panel_slot(panel);
@@ -4606,20 +4748,7 @@ impl SettingsWindow {
// closure reads the new shared value; without this the
// gate waits for the next safety tick.
mux::agent_status::refresh_enabled();
- // Not invalidate_all_windows: the sidebar's width can
- // have gone to or from zero, and only a real relayout
- // resizes the panes around that.
- if let Some(front_end) = crate::frontend::try_front_end() {
- for gui_window in front_end.gui_windows() {
- gui_window.window.notify(
- crate::termwindow::TermWindowNotif::Apply(Box::new(
- |term_window| {
- term_window.right_sidebar_panels_changed();
- },
- )),
- );
- }
- }
+ right_sidebar_panels_changed();
}
Err(err) => {
self.status = format!("Unable to save sidebar panel setting: {err:#}");
@@ -9157,10 +9286,6 @@ impl SettingsWindow {
let panels = Self::RIGHT_SIDEBAR_PANELS;
let (card_y, first_row_y) = self.settings_card_geometry(section_y, panels.len());
let card_height = self.settings_card_height(panels.len());
- self.ui.content_scroll.set_extents(
- self.content_viewport_extent(),
- self.settings_content_extent(card_y + scroll + card_height),
- );
self.draw_text(
layers,
@@ -9187,6 +9312,165 @@ impl SettingsWindow {
index > 0,
)?;
}
+ // The plugins below the panels: whatever a plugin shows, it shows in
+ // the sidebar.
+ let plugins_title_y = card_y + card_height + self.settings_section_card_gap();
+ self.paint_plugins(layers, x, max_width, plugins_title_y)
+ }
+
+ /// The plugins, on the Sidebar page from `title_y`: where they are
+ /// installed, reloading them, and each as the plugin host last listed
+ /// it. An installed one has its switch here; a built-in one says which
+ /// panel it provides, whose switch is above.
+ fn paint_plugins(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ max_width: f32,
+ title_y: f32,
+ ) -> anyhow::Result<()> {
+ use thinkterm_plugin_channel::registry::State;
+ let palette = self.palette();
+ let body_font = Rc::clone(&self.body_font);
+ let scroll = self.ui.content_scroll.offset;
+ let row_step = self.settings_row_step();
+ let card_padding = self.ui_px(36.0);
+ let row_x = x + card_padding;
+ let row_width = max_width - card_padding * 2.0;
+
+ let plugins = crate::plugins::plugins();
+ let card_y = title_y + self.settings_section_card_gap().min(54.0);
+ let first_row_y = card_y + self.settings_card_top_padding();
+ let card_height = self.settings_card_height(2);
+ let list_rows = plugins.as_ref().map_or(1, |plugins| plugins.len().max(1));
+ let list_y = card_y + card_height + self.settings_section_card_gap();
+ let list_first_row_y = list_y + (first_row_y - card_y);
+ let list_height = self.settings_card_height(list_rows);
+ self.ui.content_scroll.set_extents(
+ self.content_viewport_extent(),
+ self.settings_content_extent(list_y + scroll + list_height),
+ );
+
+ // In the primary colour when it is news: a change refused, or the
+ // host gone, which makes the list below only what was last heard.
+ let (description, description_color) =
+ match (crate::plugins::refused(), crate::plugins::trouble()) {
+ (Some(why), _) => (
+ settings_tr("settings-plugins-refused", &[("reason", why)]),
+ palette.text,
+ ),
+ (None, Some(why)) => (
+ settings_tr("settings-plugins-unavailable", &[("reason", why)]),
+ palette.text,
+ ),
+ (None, None) => (
+ crate::i18n::tr("settings-plugins-description"),
+ palette.secondary_text,
+ ),
+ };
+ self.draw_text(
+ layers,
+ &body_font,
+ x,
+ title_y,
+ &description,
+ description_color,
+ max_width,
+ )?;
+
+ self.paint_group_card(layers, x, card_y, max_width, card_height)?;
+ self.paint_action_setting_row(
+ layers,
+ row_x,
+ first_row_y,
+ row_width,
+ &crate::i18n::tr("settings-plugins-folder"),
+ &thinkterm_plugin_channel::paths::plugins_dir()
+ .display()
+ .to_string(),
+ &crate::i18n::tr("settings-plugins-open-folder"),
+ SettingsAction::OpenPluginsFolder,
+ false,
+ )?;
+ self.paint_action_setting_row(
+ layers,
+ row_x,
+ first_row_y + row_step,
+ row_width,
+ &crate::i18n::tr("settings-plugins-reload"),
+ &crate::i18n::tr("settings-plugins-reload-description"),
+ &crate::i18n::tr("settings-plugins-reload-button"),
+ SettingsAction::ReloadPlugins,
+ true,
+ )?;
+
+ self.paint_group_card(layers, x, list_y, max_width, list_height)?;
+ self.ui.plugin_switches.clear();
+ let Some(plugins) = plugins.filter(|plugins| !plugins.is_empty()) else {
+ let label = match crate::plugins::trouble() {
+ Some(why) => settings_tr("settings-plugins-unavailable", &[("reason", why)]),
+ None => crate::i18n::tr("settings-plugins-loading"),
+ };
+ return self.draw_text(
+ layers,
+ &body_font,
+ row_x,
+ list_first_row_y,
+ &label,
+ palette.secondary_text,
+ row_width,
+ );
+ };
+ for (index, plugin) in plugins.iter().enumerate() {
+ let y = list_first_row_y + row_step * index as f32;
+ let description = plugin_row_description(plugin);
+ if plugin.builtin {
+ // Its switch is its panel's, among the panels above.
+ self.paint_label_row(
+ layers,
+ row_x,
+ y,
+ row_width,
+ &plugin.name,
+ &description,
+ index > 0,
+ )?;
+ continue;
+ }
+ if matches!(
+ plugin.state,
+ State::Invalid { .. } | State::Unsupported { .. }
+ ) {
+ // Nothing a switch could do for it.
+ self.paint_setting_row(
+ layers,
+ row_x,
+ y,
+ row_width,
+ &plugin.name,
+ &description,
+ &crate::i18n::tr("settings-plugins-unusable"),
+ index > 0,
+ )?;
+ continue;
+ }
+ let key = plugin_key(&plugin.id);
+ let enabled = crate::plugins::switching(&plugin.id).unwrap_or(plugin.enabled);
+ self.ui
+ .plugin_switches
+ .push((key, plugin.id.clone(), enabled));
+ self.paint_toggle_setting_row(
+ layers,
+ row_x,
+ y,
+ row_width,
+ &plugin.name,
+ &description,
+ enabled,
+ SettingsAction::TogglePlugin(key),
+ index > 0,
+ )?;
+ }
Ok(())
}
@@ -9573,6 +9857,35 @@ impl SettingsWindow {
Ok(())
}
+ /// A row that only tells: its label and its description, no control.
+ fn paint_label_row(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ width: f32,
+ label: &str,
+ description: &str,
+ draw_top_rule: bool,
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+ let body_font = Rc::clone(&self.body_font);
+ if draw_top_rule {
+ self.paint_separator(layers, x, y - self.ui_px(28.0), width)?;
+ }
+ self.draw_text(layers, &ui_font, x, y, label, palette.text, width)?;
+ self.draw_text(
+ layers,
+ &body_font,
+ x,
+ self.settings_row_description_y(y),
+ description,
+ palette.secondary_text,
+ width,
+ )
+ }
+
fn paint_setting_row(
&self,
layers: &mut TripleLayerQuadAllocator<'_>,
diff --git a/wezterm-gui/src/snippets.rs b/wezterm-gui/src/snippets.rs
index e780148d..f9b6ef35 100644
--- a/wezterm-gui/src/snippets.rs
+++ b/wezterm-gui/src/snippets.rs
@@ -1,55 +1,26 @@
//! ThinkTerm command snippets shown in the right sidebar.
//!
-//! The snippets live in the plugin host, the thinkterm-plugin-server process,
-//! which keeps them and does everything with them: searching, saving,
-//! deleting, making the text a pane is sent (see thinkterm-snippets
-//! `wire`). A window's panel is only a view of it: each window keeps its
-//! own search and the rows sent for it (thinkterm-snippets `view`), and
-//! forwards what the user does. This holds what the windows share: the one
-//! session with the host, and the windows to tell when the snippets change.
-//! A browser's panel is another view of the same.
+//! The snippets live in the Snippets plugin, in the plugin host (see
+//! `crate::plugins`), which keeps them and does everything with them:
+//! searching, saving, deleting, making the text a pane is sent (see
+//! thinkterm-snippets `wire`). A window's panel is only a view of it: each
+//! window keeps its own search and the rows sent for it (thinkterm-snippets
+//! `view`), and forwards what the user does. A browser's panel is another
+//! view of the same.
//!
-//! The session is let go once no window has painted the panel for a while,
-//! and the windows' rows with it; the next paint asks again.
+//! The windows that painted the panel are told when the snippets change,
+//! and when the session with the host is let go, their rows with it; the
+//! next paint asks again.
use crate::termwindow::{TermWindow, TermWindowNotif};
use anyhow::Result;
-use parking_lot::{Mutex, MutexGuard};
use serde::de::DeserializeOwned;
use std::path::{Path, PathBuf};
-use std::time::{Duration, Instant};
-use thinkterm_plugin_channel::client::{Host, Notice, Session};
use thinkterm_snippets::wire::{Event, Request, PLUGIN};
use window::{Window, WindowOps};
pub use thinkterm_snippets::wire::{Row, Saved, Snippet};
-/// How long the panel may go unpainted before the session is let go.
-const RELEASE_AFTER: Duration = Duration::from_secs(120);
-/// How often that is looked at.
-const RELEASE_CHECK: Duration = Duration::from_secs(15);
-
-struct Shared {
- session: Option<Session>,
- /// Counts sessions, so a release check stops with the one it watched.
- generation: u64,
- /// The windows that have painted the panel since the session started:
- /// the ones told when the snippets change, or the rows are let go. A
- /// handful at most; one that has closed ignores what it is told.
- windows: Vec<Window>,
- /// Why the host cannot be reached, while it cannot.
- trouble: Option<String>,
- last_used: Option<Instant>,
-}
-
-static SHARED: Mutex<Shared> = parking_lot::const_mutex(Shared {
- session: None,
- generation: 0,
- windows: Vec::new(),
- trouble: None,
- last_used: None,
-});
-
/// What a window's panel has to show.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Availability {
@@ -69,113 +40,31 @@ pub(crate) fn check_snippet_store(path: &Path) -> Result<()> {
thinkterm_snippets::file::load(path).map(drop)
}
-/// The shared state, marked as in use, with a session to the host. On the
-/// GUI thread: it may start the release check.
-fn shared_in_use() -> MutexGuard<'static, Shared> {
- let mut shared = SHARED.lock();
- shared.last_used = Some(Instant::now());
- if shared.session.is_none() {
- let started = Host::for_this_build().and_then(|host| Session::start(host, on_notice));
- match started {
- Ok(session) => {
- shared.session = Some(session);
- shared.generation += 1;
- release_when_idle(shared.generation);
- }
- Err(err) => shared.trouble = Some(format!("{err:#}")),
- }
- }
- shared
-}
-
/// `window` paints the panel: it is told when the snippets change, and the
/// session is kept.
pub fn in_use(window: &Window) {
- let mut shared = shared_in_use();
- if !shared.windows.contains(window) {
- shared.windows.push(window.clone());
- }
+ crate::plugins::window_in_use(window);
}
/// Why the host cannot be reached, while it cannot.
pub fn trouble() -> Option<String> {
- SHARED.lock().trouble.clone()
-}
-
-/// Has every window that shows the panel apply `change` to itself.
-fn tell_windows(change: fn(&mut TermWindow)) {
- let windows: Vec<Window> = SHARED.lock().windows.iter().cloned().collect();
- promise::spawn::spawn_into_main_thread(async move {
- for window in windows {
- let repaint = window.clone();
- window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
- change(term_window);
- repaint.invalidate();
- })));
- }
- })
- .detach();
+ crate::plugins::trouble()
}
-fn on_notice(notice: Notice) {
- match notice {
- // Whatever the host said before, it is asked again.
- Notice::Connected => {
- SHARED.lock().trouble = None;
- tell_windows(TermWindow::snippets_changed);
- }
- Notice::Event { plugin, body } if plugin == PLUGIN => {
- if let Ok(Event::Changed) = serde_json::from_value(body) {
- tell_windows(TermWindow::snippets_changed);
- }
- }
- Notice::Event { .. } => {}
- Notice::Trouble(why) => {
- SHARED.lock().trouble = Some(why);
- // Rows already on show stay; an empty panel says why.
- tell_windows(|_| {});
- }
+/// What a plugin other than the host itself told its watchers.
+pub(crate) fn on_event(plugin: &str, body: serde_json::Value) {
+ if plugin != PLUGIN {
+ return;
+ }
+ if let Ok(Event::Changed) = serde_json::from_value(body) {
+ crate::plugins::tell_windows(TermWindow::snippets_changed);
}
-}
-
-/// Lets the session go once no window has painted the panel for a while,
-/// and the windows' rows with it -- without asking them to paint, which
-/// would only ask for them again.
-fn release_when_idle(generation: u64) {
- promise::spawn::spawn(async move {
- loop {
- smol::Timer::after(RELEASE_CHECK).await;
- let mut shared = SHARED.lock();
- if shared.generation != generation || shared.session.is_none() {
- return;
- }
- let idle = shared
- .last_used
- .map_or(true, |used| used.elapsed() >= RELEASE_AFTER);
- if !idle {
- continue;
- }
- shared.session = None;
- shared.trouble = None;
- for window in shared.windows.drain(..) {
- window.notify(TermWindowNotif::Apply(Box::new(|term_window| {
- term_window.snippets_released();
- })));
- }
- return;
- }
- })
- .detach();
}
fn to_body(request: &Request) -> serde_json::Value {
serde_json::to_value(request).expect("a snippets request always serialises")
}
-fn from_body<T: DeserializeOwned>(body: serde_json::Value) -> std::result::Result<T, String> {
- serde_json::from_value(body).map_err(|err| format!("an answer that does not read: {err}"))
-}
-
/// Asks the host something on behalf of `window`, and hands the answer, or
/// why there is none, to `apply` on that window alone.
fn ask<T: DeserializeOwned + Send + Sync + 'static>(
@@ -183,8 +72,8 @@ fn ask<T: DeserializeOwned + Send + Sync + 'static>(
window: Window,
apply: impl FnOnce(&mut TermWindow, std::result::Result<T, String>) + Send + Sync + 'static,
) {
- let shared = shared_in_use();
- let deliver = move |answer: std::result::Result<T, String>| {
+ crate::plugins::call(PLUGIN, to_body(&request), move |answer| {
+ let answer = answer.and_then(crate::plugins::from_body);
promise::spawn::spawn_into_main_thread(async move {
let repaint = window.clone();
window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
@@ -193,16 +82,7 @@ fn ask<T: DeserializeOwned + Send + Sync + 'static>(
})));
})
.detach();
- };
- match &shared.session {
- Some(session) => session.call(PLUGIN, to_body(&request), move |answer| {
- deliver(answer.and_then(from_body));
- }),
- None => deliver(Err(shared
- .trouble
- .clone()
- .unwrap_or_else(|| "the plugin host cannot be reached".into()))),
- }
+ });
}
/// The rows matching `query`, for `window`'s panel.
@@ -266,14 +146,9 @@ pub fn save(
}
pub fn delete(id: &str) {
- let shared = shared_in_use();
- let Some(session) = &shared.session else {
- log::error!("failed to delete snippet {id}: the plugin host cannot be reached");
- return;
- };
let request = Request::Delete { id: id.to_string() };
let id = id.to_string();
- session.call(PLUGIN, to_body(&request), move |answer| {
+ crate::plugins::call(PLUGIN, to_body(&request), move |answer| {
if let Err(why) = answer {
log::error!("failed to delete snippet {id}: {why}");
}