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.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
feat(gui): show plugin panels in the right sidebar
RoversX5492edad18ce
diff --git a/Cargo.lock b/Cargo.lockindex 50c0da78..70b27cc6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -10616,6 +10616,7 @@ dependencies = ["thinkterm-file-index","thinkterm-i18n","thinkterm-plugin-channel",+ "thinkterm-plugin-panel","thinkterm-proto","thinkterm-render","thinkterm-snippets",diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftlindex 4cc8c794..7d1989a8 100644--- a/thinkterm-i18n/i18n/de-DE.ftl+++ b/thinkterm-i18n/i18n/de-DE.ftl@@ -406,6 +406,9 @@ right-search = Suchenright-no-snippets = Keine Snippetsright-no-matching-snippets = Keine passenden Snippetsright-snippets-unavailable = Snippets sind gerade nicht verfügbar+right-plugin-starting = Wird gestartet…+right-plugin-stopped = Dieses Panel wurde beendet: { $reason }+right-plugin-connect = Braucht eine Verbindung zu { $host }right-edit-snippet = Snippet bearbeitenright-snippet = Snippetright-personal-vault = Persönlicher Vaultdiff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftlindex 401e2bc9..65689c98 100644--- a/thinkterm-i18n/i18n/en-US.ftl+++ b/thinkterm-i18n/i18n/en-US.ftl@@ -406,6 +406,9 @@ right-search = Searchright-no-snippets = No snippetsright-no-matching-snippets = No matching snippetsright-snippets-unavailable = Snippets are unavailable right now+right-plugin-starting = Starting…+right-plugin-stopped = This panel stopped: { $reason }+right-plugin-connect = Needs a connection to { $host }right-edit-snippet = Edit Snippetright-snippet = Snippetright-personal-vault = Personal vaultdiff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftlindex c6607d1e..7ad347bd 100644--- a/thinkterm-i18n/i18n/fr-FR.ftl+++ b/thinkterm-i18n/i18n/fr-FR.ftl@@ -406,6 +406,9 @@ right-search = Rechercherright-no-snippets = Aucun extraitright-no-matching-snippets = Aucun extrait correspondantright-snippets-unavailable = Les extraits sont indisponibles pour le moment+right-plugin-starting = Démarrage…+right-plugin-stopped = Ce panneau s'est arrêté : { $reason }+right-plugin-connect = Nécessite une connexion à { $host }right-edit-snippet = Modifier l’extraitright-snippet = Extraitright-personal-vault = Coffre personneldiff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftlindex 26b5df49..2ff7329c 100644--- a/thinkterm-i18n/i18n/ja-JP.ftl+++ b/thinkterm-i18n/i18n/ja-JP.ftl@@ -397,6 +397,9 @@ right-search = 検索right-no-snippets = スニペットはありませんright-no-matching-snippets = 一致するスニペットはありませんright-snippets-unavailable = スニペットは現在利用できません+right-plugin-starting = 起動しています…+right-plugin-stopped = このパネルは停止しました:{ $reason }+right-plugin-connect = { $host } への接続が必要ですright-edit-snippet = スニペットを編集right-snippet = スニペットright-personal-vault = 個人用保管庫diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftlindex eeb8e860..dcdca797 100644--- a/thinkterm-i18n/i18n/zh-CN.ftl+++ b/thinkterm-i18n/i18n/zh-CN.ftl@@ -397,6 +397,9 @@ right-search = 搜索right-no-snippets = 没有片段right-no-matching-snippets = 没有匹配的片段right-snippets-unavailable = 片段暂时不可用+right-plugin-starting = 正在启动…+right-plugin-stopped = 这个面板停了:{ $reason }+right-plugin-connect = 需要连接到 { $host }right-edit-snippet = 编辑片段right-snippet = 片段right-personal-vault = 个人库diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.tomlindex 5945db8c..110ad165 100644--- a/wezterm-gui/Cargo.toml+++ b/wezterm-gui/Cargo.toml@@ -119,6 +119,7 @@ tiny-skia.workspace = truethinkterm-syntax = { path = "../thinkterm-syntax" }thinkterm-core.workspace = truethinkterm-plugin-channel = { workspace = true, features = ["native"] }+thinkterm-plugin-panel.workspace = truethinkterm-snippets = { workspace = true, features = ["native"] }trash.workspace = trueumask.workspace = truediff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex bdf1b06c..dc406887 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -1446,6 +1446,10 @@ fn run_terminal_gui(opts: StartCommand, default_domain_name: Option<String>) ->.detach();maybe_show_configuration_error_window();+ // Once the GUI can be handed work: the panels plugins add, if any+ // plugin is installed.+ crate::plugins::look_for_panels();+// A debugging hook alongside THINKTERM_FRAME_DUMP: open the Settings// window on a given section once the GUI is up, so a page can be// captured from a scripted launch with no keyboard or mouse.@@ -1460,6 +1464,25 @@ fn run_terminal_gui(opts: StartCommand, default_domain_name: Option<String>) ->}).detach();}+ // Likewise a plugin's panel, by the plugin's id: the right sidebar is+ // opened on it in every window.+ if let Some(plugin) = std::env::var_os("THINKTERM_OPEN_PANEL") {+ let plugin = plugin.to_string_lossy().into_owned();+ promise::spawn::spawn_into_main_thread(async move {+ smol::Timer::after(std::time::Duration::from_millis(2500)).await;+ if let Some(front_end) = crate::frontend::try_front_end() {+ for gui_window in front_end.gui_windows() {+ let plugin = plugin.clone();+ gui_window+ .window+ .notify(crate::termwindow::TermWindowNotif::Apply(Box::new(+ move |term_window| term_window.show_plugin_panel(&plugin),+ )));+ }+ }+ })+ .detach();+ }gui.run_forever()}diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rsindex 629d9d40..56d7b541 100644--- a/wezterm-gui/src/native_settings.rs+++ b/wezterm-gui/src/native_settings.rs@@ -1,6 +1,7 @@use config::ConfigHandle;use parking_lot::Mutex;use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;use std::fs;use std::io;use std::path::PathBuf;@@ -481,6 +482,21 @@ pub(crate) struct NativeChromeSettings {/// 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.pub(crate) agent_panel_enabled: Option<bool>,+ /// The panels plugins add to the right sidebar, as the plugin host last+ /// listed them (`plugins::follow_panels`): offered from the start,+ /// before the host is asked.+ pub(crate) plugin_panels: Vec<NativePluginPanel>,+ /// How wide the user made each plugin's extended view, by plugin, in+ /// unscaled pixels. A plugin's goes when the host lists it no more.+ pub(crate) plugin_extended_widths: BTreeMap<String, usize>,+}++#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]+pub(crate) struct NativePluginPanel {+ pub(crate) id: String,+ pub(crate) name: String,+ /// A Lucide icon's name.+ pub(crate) icon: String,}#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]@@ -1367,6 +1383,8 @@ pub(crate) struct RightSidebarPanelToggles {pub(crate) files: bool,pub(crate) notes: bool,pub(crate) snippets: bool,+ /// Whether any plugin adds a panel.+ pub(crate) plugins: bool,}pub(crate) fn right_sidebar_panel_toggles() -> RightSidebarPanelToggles {@@ -1378,9 +1396,15 @@ pub(crate) fn right_sidebar_panel_toggles() -> RightSidebarPanelToggles {// plugin's switch has taken it over.snippets: settings.chrome.right_sidebar_snippets_enabled != Some(false)&& settings.chrome.snippets_plugin_enabled.unwrap_or(true),+ plugins: !settings.chrome.plugin_panels.is_empty(),}}+/// The panels plugins add to the right sidebar, as last heard.+pub(crate) fn plugin_panels() -> Vec<NativePluginPanel> {+ load_shared().chrome.plugin_panels.clone()+}+pub(crate) fn right_sidebar_width() -> Option<usize> {load().chrome.right_sidebar_width}@@ -1444,6 +1468,24 @@ pub(crate) fn save_right_sidebar_markdown_preview_rendered(rendered: bool) -> ansave(&settings)}+/// How wide the user made plugin `plugin`'s extended view.+pub(crate) fn plugin_extended_width(plugin: &str) -> Option<usize> {+ load_shared()+ .chrome+ .plugin_extended_widths+ .get(plugin)+ .copied()+}++pub(crate) fn save_plugin_extended_width(plugin: &str, width: usize) -> anyhow::Result<()> {+ let mut settings = load();+ settings+ .chrome+ .plugin_extended_widths+ .insert(plugin.to_string(), width);+ save(&settings)+}+pub(crate) fn save_right_sidebar_note_pane_width(width: usize) -> anyhow::Result<()> {let mut settings = load();settings.chrome.right_sidebar_note_pane_width = Some(width);diff --git a/wezterm-gui/src/plugins.rs b/wezterm-gui/src/plugins.rsindex 8a8057ef..79d07ee8 100644--- a/wezterm-gui/src/plugins.rs+++ b/wezterm-gui/src/plugins.rs@@ -6,19 +6,32 @@//! 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.+//! Plugins. So are the panels plugins draw in the right sidebar: each one+//! on show is a view, numbered here, whose frames are read on the session's+//! thread and handed to the window showing it+//! (`termwindow::ui::plugin_panel`). 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.+//! While a plugin runs always, the host itself is kept up for as long as+//! the desktop runs, on a connection of its own (`keep_host_up`).+//!+//! What a panel's plugin asks of the other machine its terminal runs on+//! comes over the session too, and goes to the window showing the panel,+//! which answers it (`plugin_panel`).use crate::termwindow::{TermWindow, TermWindowNotif};use parking_lot::{Mutex, MutexGuard};use serde_json::Value;+use std::collections::HashMap;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 thinkterm_plugin_channel::registry::{self as api, Background, Info};+use thinkterm_plugin_channel::wire::{PanelEvent, PanelRequest, Raw};+use thinkterm_plugin_panel::{Ask, Env, Frame, Rows};use window::{Window, WindowOps};/// How long the plugins may go unused before the session is let go.@@ -81,8 +94,44 @@ struct Shared {listing: Listing,/// Switches flipped here whose change is on its way, and to what.switching: Vec<(String, bool)>,+ /// How long plugins run unused, chosen here, on its way.+ choosing: Vec<(String, Background)>,/// Why the host refused the last change asked of it here.refused: Option<String>,+ /// The plugin panels on show, by number, and the window showing each.+ /// The session is kept while there are any.+ views: Option<HashMap<u64, Window>>,+ next_view: u64,+ /// A panel was opened with no session to send it on: the panels are+ /// opened again once one connects, the first time included.+ unsent: bool,+}++/// What a window hears about the plugin panel it shows, read on the+/// session's thread: frames and rows parsed there, not on the thread that+/// paints.+pub enum PanelNews {+ Frame(Frame),+ Rows(Rows),+ /// The host no longer serves it; `again` when opening it anew may work.+ Closed {+ reason: String,+ again: bool,+ },+ /// The host cannot be reached, and why: the panel is opened again once+ /// it can.+ Unreachable(String),+ /// The session connected anew, without the panel: it is to be opened+ /// again.+ Reconnected,+ /// Its plugin asks something of `machine`, the other machine it was+ /// told the panel's terminal runs on, to be answered with [`answer`]+ /// and `id`.+ Remote {+ id: u64,+ machine: String,+ ask: Ask,+ },}static SHARED: Mutex<Shared> = parking_lot::const_mutex(Shared {@@ -98,7 +147,11 @@ static SHARED: Mutex<Shared> = parking_lot::const_mutex(Shared {stale: true,},switching: Vec::new(),+ choosing: Vec::new(),refused: None,+ views: None,+ next_view: 0,+ unsent: false,});/// The shared state, marked as in use, with a session to the host. On the@@ -193,15 +246,24 @@ fn list_changed() {fn on_notice(notice: Notice) {match notice {// Whatever the host said before, it is asked again.- Notice::Connected => {- {+ Notice::Connected { again } => {+ let views = {let mut shared = SHARED.lock();shared.trouble = None;shared.listing.stale = true;- }+ let again = again || std::mem::take(&mut shared.unsent);+ match (again, &shared.views) {+ (true, Some(views)) => views.clone(),+ _ => HashMap::new(),+ }+ };ask_for_list();tell_windows(TermWindow::snippets_changed);+ for (view, window) in views {+ tell_panel_window(&window, view, PanelNews::Reconnected);+ }}+ Notice::Panel { view, event } => heard_for_panel(view, event),Notice::Event { plugin, body } if plugin == api::PLUGIN => {match serde_json::from_value(body) {Ok(api::Event::Changed) => {@@ -213,7 +275,14 @@ fn on_notice(notice: Notice) {}Notice::Event { plugin, body } => crate::snippets::on_event(&plugin, body),Notice::Trouble(why) => {- SHARED.lock().trouble = Some(why);+ let views = {+ let mut shared = SHARED.lock();+ shared.trouble = Some(why.clone());+ shared.views.clone().unwrap_or_default()+ };+ for (view, window) in views {+ tell_panel_window(&window, view, PanelNews::Unreachable(why.clone()));+ }// Rows already on show stay; an empty panel says why.tell_windows(|_| {});list_changed();@@ -235,7 +304,8 @@ fn release_when_idle(generation: u64) {let idle = shared.last_used.map_or(true, |used| used.elapsed() >= RELEASE_AFTER);- if !idle {+ let panels = shared.views.as_ref().is_some_and(|views| !views.is_empty());+ if !idle || panels {continue;}shared.session = None;@@ -253,6 +323,149 @@ fn release_when_idle(generation: u64) {.detach();}+/// Shows plugin `plugin`'s panel in `window` for `env` -- the extended view+/// of panel `extends`, with one: its number, which what the window hears+/// about it and what it sends carry.+pub fn open_panel(plugin: &str, env: &Env, extends: Option<u64>, window: &Window) -> u64 {+ let view = {+ let mut shared = SHARED.lock();+ shared.next_view += 1;+ let view = shared.next_view;+ shared+ .views+ .get_or_insert_with(HashMap::new)+ .insert(view, window.clone());+ view+ };+ send_open(view, open_request(plugin, env, extends));+ view+}++/// Opens panel `view` again: the host closed it, or the session that had it+/// is gone.+pub fn reopen_panel(view: u64, plugin: &str, env: &Env) {+ send_open(view, open_request(plugin, env, None));+}++/// Sends the open of panel `view`; with no session to send it on, the+/// window says why, and it is opened once a session connects.+fn send_open(view: u64, request: PanelRequest) {+ let (session, lost) = {+ let mut shared = in_use();+ match shared.session.clone() {+ Some(session) => (Some(session), None),+ None => {+ shared.unsent = true;+ let why = shared+ .trouble+ .clone()+ .unwrap_or_else(|| "the plugin host cannot be reached".into());+ let window = shared+ .views+ .as_ref()+ .and_then(|views| views.get(&view).cloned());+ (None, window.map(|window| (window, why)))+ }+ }+ };+ match (session, lost) {+ (Some(session), _) => session.panel(view, request),+ (None, Some((window, why))) => {+ tell_panel_window(&window, view, PanelNews::Unreachable(why))+ }+ (None, None) => {}+ }+}++fn open_request(plugin: &str, env: &Env, extends: Option<u64>) -> PanelRequest {+ PanelRequest::Open {+ plugin: plugin.to_string(),+ env: Raw::new(env),+ extends,+ }+}++/// Tells the host about panel `view`.+pub fn tell_panel(view: u64, request: PanelRequest) {+ let session = in_use().session.clone();+ if let Some(session) = session {+ session.panel(view, request);+ }+}++/// Panel `view` went off show.+pub fn close_panel(view: u64) {+ let session = {+ let mut shared = SHARED.lock();+ if let Some(views) = shared.views.as_mut() {+ views.remove(&view);+ }+ shared.session.clone()+ };+ if let Some(session) = session {+ session.panel(view, PanelRequest::Close);+ }+}++/// Reads what the host said about panel `view`, and hands it to the window+/// showing it. A frame that does not read is still taken in, so the next+/// one can come: said over the session it came on, from its thread, where+/// nothing is to be started.+fn heard_for_panel(view: u64, event: PanelEvent) {+ let news = match event {+ PanelEvent::Frame { frame } => match frame.read::<Frame>() {+ Ok(frame) => PanelNews::Frame(frame),+ Err(err) => {+ log::warn!("plugin panel {view} sent a frame that does not read: {err}");+ let session = SHARED.lock().session.clone();+ if let Some(session) = session {+ session.panel(view, PanelRequest::Shown);+ }+ return;+ }+ },+ PanelEvent::Rows { rows } => match rows.read::<Rows>() {+ Ok(rows) => PanelNews::Rows(rows),+ Err(err) => {+ log::warn!("plugin panel {view} sent rows that do not read: {err}");+ return;+ }+ },+ PanelEvent::Closed { reason, again } => PanelNews::Closed { reason, again },+ PanelEvent::Remote { id, machine, ask } => match ask.read::<Ask>() {+ Ok(ask) => PanelNews::Remote { id, machine, ask },+ Err(err) => {+ let why = format!("not something this ThinkTerm can do: {err}");+ answer(view, id, &thinkterm_plugin_panel::Answer::failed(why));+ return;+ }+ },+ };+ let window = SHARED+ .lock()+ .views+ .as_ref()+ .and_then(|views| views.get(&view).cloned());+ if let Some(window) = window {+ tell_panel_window(&window, view, news);+ }+}++/// Tells the plugin of panel `view` what came of what it asked, `id`.+pub fn answer(view: u64, id: u64, answer: &thinkterm_plugin_panel::Answer) {+ let session = SHARED.lock().session.clone();+ if let Some(session) = session {+ let answer = Raw::new(answer);+ session.panel(view, PanelRequest::Answer { id, answer });+ }+}++fn tell_panel_window(window: &Window, view: u64, news: PanelNews) {+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.plugin_panel_heard(view, news);+ })));+}+/// Asks for the list if what was last heard is out of date and nothing is/// asking already.fn ask_for_list() {@@ -287,6 +500,7 @@ fn listed(answer: Answer) {if let Some(plugins) = heard {promise::spawn::spawn_into_main_thread(async move {follow_snippets_switch(&plugins);+ follow_panels(&plugins);}).detach();}@@ -294,6 +508,32 @@ fn listed(answer: Answer) {list_changed();}+/// At start, whether any plugin is installed, looked at off the GUI thread:+/// if one is, the list is asked for, which brings the panels plugins add to+/// the sidebar up to date; if none is, the panels kept from an earlier run+/// are let go. A machine with no plugin installed starts no plugin host.+/// The host is kept up from then on while a plugin runs always.+pub fn look_for_panels() {+ thinkterm_plugin_channel::client::keep_host_up();+ let dir = thinkterm_plugin_channel::paths::plugins_dir();+ let looking = std::thread::Builder::new()+ .name("plugin-look".into())+ .spawn(move || {+ let installed = thinkterm_plugin_channel::paths::any_installed(&dir);+ promise::spawn::spawn_into_main_thread(async move {+ if installed {+ refresh();+ } else {+ follow_panels(&[]);+ }+ })+ .detach();+ });+ if let Err(err) = looking {+ log::warn!("cannot look for installed plugins: {err}");+ }+}+/// 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.@@ -357,6 +597,47 @@ pub fn set_enabled(id: &str, enabled: bool) {list_changed();}+/// How long plugin `id` runs unused as it is to be shown: the choice on its+/// way, if one is.+pub fn choosing(id: &str) -> Option<Background> {+ SHARED+ .lock()+ .choosing+ .iter()+ .find(|(choosing, _)| choosing == id)+ .map(|(_, background)| *background)+}++/// Lets plugin `id` run unused as `background` says; its manifest's+/// `default` is kept as no choice at all. Shown at once, and as it was if+/// the host refuses.+pub fn set_background(id: &str, background: Background, default: Background) {+ {+ let mut shared = in_use();+ shared.refused = None;+ shared.choosing.retain(|(choosing, _)| choosing != id);+ shared.choosing.push((id.to_string(), background));+ }+ let request = api::Request::SetBackground {+ id: id.to_string(),+ background: (background != default).then_some(background),+ };+ let id = id.to_string();+ call(api::PLUGIN, to_body(&request), move |answer| {+ {+ let mut shared = SHARED.lock();+ shared.choosing.retain(|(choosing, _)| *choosing != id);+ if let Err(why) = answer {+ shared.refused = Some(why);+ }+ 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;@@ -391,6 +672,7 @@ fn follow_snippets_switch(plugins: &[Info]) {if let Err(err) = crate::native_settings::save(&settings) {log::warn!("saving the Snippets switch: {err:#}");}+ crate::settings_window::refresh_open_settings_window_chrome();if enabled {let request = api::Request::SetEnabled {id: thinkterm_snippets::wire::PLUGIN.into(),@@ -407,6 +689,52 @@ fn follow_snippets_switch(plugins: &[Info]) {if let Err(err) = crate::native_settings::save(&settings) {log::warn!("saving the Snippets switch: {err:#}");}+ // An open settings window holds the settings as they were, and would+ // write them back so.+ crate::settings_window::refresh_open_settings_window_chrome();+ 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();+ })));+ }+ }+}++/// The plugins' panels the right sidebar offers: those of the plugins that+/// are on and not broken. The desktop keeps them as last heard, so they are+/// offered from the start, without asking the host; its word wins when it+/// comes. On the GUI thread, with the settings.+fn follow_panels(plugins: &[Info]) {+ let panels: Vec<crate::native_settings::NativePluginPanel> = plugins+ .iter()+ .filter(|plugin| plugin.usable())+ .filter_map(|plugin| {+ Some(crate::native_settings::NativePluginPanel {+ id: plugin.id.clone(),+ name: plugin.name.clone(),+ icon: plugin.panel.as_ref()?.icon.clone(),+ })+ })+ .collect();+ let mut settings = crate::native_settings::load();+ // The width kept for a plugin's extended view goes with the plugin.+ let widths = settings.chrome.plugin_extended_widths.len();+ settings+ .chrome+ .plugin_extended_widths+ .retain(|id, _| plugins.iter().any(|plugin| plugin.id == *id));+ let forgotten = settings.chrome.plugin_extended_widths.len() != widths;+ if settings.chrome.plugin_panels == panels && !forgotten {+ return;+ }+ settings.chrome.plugin_panels = panels;+ if let Err(err) = crate::native_settings::save(&settings) {+ log::warn!("saving the plugins' panels: {err:#}");+ }+ crate::settings_window::refresh_open_settings_window_chrome();if let Some(front_end) = crate::frontend::try_front_end() {for gui_window in front_end.gui_windows() {gui_windowdiff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rsindex 7702048d..0dcbf66e 100644--- a/wezterm-gui/src/settings_window.rs+++ b/wezterm-gui/src/settings_window.rs@@ -9294,6 +9294,7 @@ impl SettingsWindow {Panel::Tasks => &mut chrome.right_sidebar_notes_enabled,Panel::Snippets => &mut chrome.right_sidebar_snippets_enabled,Panel::Agents => &mut chrome.agent_panel_enabled,+ Panel::Plugin(_) => unreachable!("a plugin's panel is switched with its plugin"),}}@@ -9313,6 +9314,7 @@ impl SettingsWindow {Panel::Tasks => "right-mode-notes",Panel::Snippets => "right-mode-snippets",Panel::Agents => "right-mode-agents",+ Panel::Plugin(_) => unreachable!("a plugin's panel is listed with its plugin"),})}@@ -9323,6 +9325,7 @@ impl SettingsWindow {Panel::Tasks => "settings-sidebar-notes-description",Panel::Snippets => "settings-sidebar-snippets-description",Panel::Agents => "settings-agent-panel-description",+ Panel::Plugin(_) => unreachable!("a plugin's panel is listed with its plugin"),})}diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex 23c01397..c3e2b282 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -856,6 +856,21 @@ pub enum UIItemType {/// A row in the transfer strip. Clicking cancels it while it runs and/// dismisses it once it has finished.RightSidebarRemoteTransfer(u64),+ /// The area a plugin's panel draws in: the pointer and the wheel over it+ /// go to the panel's player.+ RightSidebarPluginPanel,+ /// The same, for the panel's extended view.+ RightSidebarPluginExtended,+ /// The close button at the extended view's top left, ThinkTerm's own+ /// whatever the plugin draws.+ RightSidebarPluginExtendedClose,+ /// The button a plugin's view -- the extended one with `true` -- shows+ /// while its plugin waits for ThinkTerm to connect to the machine beside+ /// it.+ RightSidebarPluginConnect(bool),+ /// The line between a plugin's extended view and its panel, dragged to+ /// share the room between them.+ RightSidebarPluginExtendedResize,ContextMenuBackdrop,ContextMenuItem(Vec<usize>),/// Backdrop of the command palette; the palette routes its own pointer@@ -877,6 +892,44 @@ pub enum RightSidebarMode {/// Agent status panel; only offered while the agent-panel feature/// toggle is on (`crate::agent_status::enabled`).Agents,+ /// The panel the plugin with this id draws.+ Plugin(PanelId),+}++/// A plugin's id, held in place so that a mode naming it stays `Copy`: at+/// most 64 bytes, as the plugin host takes them.+#[derive(Clone, Copy, PartialEq, Eq)]+pub struct PanelId {+ len: u8,+ bytes: [u8; PanelId::LIMIT],+}++impl PanelId {+ const LIMIT: usize = 64;++ /// `None` for an id longer than the host takes.+ pub fn new(id: &str) -> Option<Self> {+ let len = id.len();+ if len > Self::LIMIT {+ return None;+ }+ let mut bytes = [0; Self::LIMIT];+ bytes[..len].copy_from_slice(id.as_bytes());+ Some(Self {+ len: len as u8,+ bytes,+ })+ }++ pub fn as_str(&self) -> &str {+ std::str::from_utf8(&self.bytes[..self.len as usize]).expect("made from a str")+ }+}++impl std::fmt::Debug for PanelId {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ self.as_str().fmt(f)+ }}#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -2854,6 +2907,18 @@ pub struct TermWindow {/// This window's view of the snippets: the rows the plugin host sent/// for its search, and when to ask again.right_sidebar_snippet_listing: thinkterm_snippets::view::Listing,+ /// The plugin panel on show in this window, while one is.+ pub(crate) right_sidebar_plugin: Option<ui::plugin_panel::PluginPanel>,+ /// Whether each domain whose panes the plugin panel was beside runs+ /// them on this machine: `None` while a look off this thread finds out.+ /// The answer is the domain's, so another pane of one looked at already+ /// has it at once. One entry a domain, dropped with the panel.+ pub(crate) plugin_panel_domains: Vec<(DomainId, Option<bool>)>,+ /// How the machine the pane in focus runs on is reached when that is+ /// another, for the plugin panel, and when that was found: for one+ /// pane, found again every few seconds.+ pub(crate) plugin_panel_reach:+ Option<(PaneId, Instant, Result<ui::plugin_panel::Reach, String>)>,/// A save from this window's editor is on its way.right_sidebar_snippet_saving: bool,right_sidebar_note: crate::markdown_editor::NoteHostState,@@ -4394,6 +4459,9 @@ impl TermWindow {right_sidebar_snippet_scroll_offset: 0.0,right_sidebar_snippet_scrollbar_visible_until: None,right_sidebar_snippet_listing: Default::default(),+ right_sidebar_plugin: None,+ plugin_panel_domains: Vec::new(),+ plugin_panel_reach: None,right_sidebar_snippet_saving: false,right_sidebar_note: crate::markdown_editor::NoteHostState::default(),right_sidebar_note_view: RightSidebarNoteView::Editor,@@ -11371,6 +11439,7 @@ impl Drop for TermWindow {// from leaving its Space permanently marked as occupied.crate::workspace_threads::release_window_space(self.space_owner_id);crate::input_diagnostics::remove_gauges_for_source(self.space_owner_id);+ self.close_plugin_panel();self.clear_gui_recovery_intent();gpu_debug(format!("drop main_window backend={} size={}x{} dpi={}",diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex 97f529de..c4a255b9 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -1481,6 +1481,26 @@ impl super::TermWindow {}}+ if let super::RightSidebarMode::Plugin(_) = self.right_sidebar_mode {+ // Across a list wider than the panel: the trackpad's own, or+ // the wheel with Shift.+ let shift_vertical = matches!(event.kind, WMEK::VertWheel(_))+ && event.modifiers.contains(::window::Modifiers::SHIFT);+ let (dx, dy) = match event.kind {+ WMEK::HorzWheel(_) => (self.sidebar_horizontal_scroll_delta(event), None),+ WMEK::VertWheel(_) if shift_vertical => {+ (self.sidebar_vertical_scroll_delta(event), None)+ }+ WMEK::VertWheel(_) => (None, self.sidebar_vertical_scroll_delta(event)),+ _ => return false,+ };+ let (dx, dy) = (dx.unwrap_or(0.0), dy.unwrap_or(0.0));+ if (dx != 0.0 || dy != 0.0) && self.plugin_panel_wheel(event, dx, dy) {+ context.invalidate();+ }+ return true;+ }+let delta = match event.kind {WMEK::VertWheel(_) => self.sidebar_vertical_scroll_delta(event).unwrap_or(0.0),WMEK::HorzWheel(_) => return true,@@ -1538,6 +1558,8 @@ impl super::TermWindow {context.invalidate();}}+ // Taken, both ways, above.+ super::RightSidebarMode::Plugin(_) => {}}true}@@ -1557,6 +1579,14 @@ impl super::TermWindow {UIItemType::TabBar(_) | UIItemType::TerminalBar(_) => {self.update_title_post_status();}+ UIItemType::RightSidebarPluginPanel | UIItemType::RightSidebarPluginExtended => {+ let extended = item.item_type == UIItemType::RightSidebarPluginExtended;+ if self.plugin_panel_pointer_left(extended) {+ if let Some(window) = self.window.as_ref() {+ window.invalidate();+ }+ }+ }UIItemType::CloseTab(_)| UIItemType::PaneNav { .. }| UIItemType::ProjectNew@@ -1589,6 +1619,9 @@ impl super::TermWindow {| UIItemType::RightSidebarResize| UIItemType::RightSidebarFilePreviewResize| UIItemType::RightSidebarNotePaneResize+ | UIItemType::RightSidebarPluginExtendedResize+ | UIItemType::RightSidebarPluginExtendedClose+ | UIItemType::RightSidebarPluginConnect(_)| UIItemType::RightSidebarNotePaneToggle| UIItemType::RightSidebarAgent(_)| UIItemType::RightSidebarSnippetNew@@ -1714,8 +1747,13 @@ impl super::TermWindow {| UIItemType::RightSidebarResize| UIItemType::RightSidebarFilePreviewResize| UIItemType::RightSidebarNotePaneResize+ | UIItemType::RightSidebarPluginExtendedResize| UIItemType::RightSidebarNotePaneToggle| UIItemType::RightSidebarAgent(_)+ | UIItemType::RightSidebarPluginPanel+ | UIItemType::RightSidebarPluginExtended+ | UIItemType::RightSidebarPluginExtendedClose+ | UIItemType::RightSidebarPluginConnect(_)| UIItemType::RightSidebarSnippetNew| UIItemType::RightSidebarSnippetBack| UIItemType::RightSidebarSnippetSave@@ -2117,6 +2155,19 @@ impl super::TermWindow {}) {self.persist_right_sidebar_note_pane_width();}+ if completed_drag.as_ref().is_some_and(|(item, _)| {+ item.item_type == UIItemType::RightSidebarPluginExtendedResize+ || (item.item_type == UIItemType::RightSidebarResize+ && self.right_sidebar_plugin_extended_rect().is_some())+ }) {+ self.persist_right_sidebar_plugin_extended_width();+ }+ if completed_drag.as_ref().is_some_and(|(item, _)| {+ item.item_type == UIItemType::RightSidebarPluginExtendedResize+ }) {+ // The panel beside it gave or took what it did.+ self.persist_right_sidebar_width();+ }if completed_drag.as_ref().is_some_and(|(item, _)| matches!(item.item_type, UIItemType::Split(_)))@@ -2818,6 +2869,9 @@ impl super::TermWindow {UIItemType::RightSidebarNotePaneResize => {self.drag_right_sidebar_note_pane_resize(item, start_event, event, context);}+ UIItemType::RightSidebarPluginExtendedResize => {+ self.drag_right_sidebar_plugin_extended_resize(item, start_event, event, context);+ }UIItemType::RightSidebarSnippetScrollThumb => {self.drag_right_sidebar_snippet_scroll_thumb(item, start_event, event, context);}@@ -3614,6 +3668,8 @@ impl super::TermWindow {self.set_right_sidebar_file_preview_total_width(width);} else if self.right_sidebar_note_pane_rect().is_some() {self.set_right_sidebar_note_pane_total_width(width);+ } else if self.right_sidebar_plugin_extended_rect().is_some() {+ self.set_right_sidebar_plugin_extended_total_width(width);} else {self.set_right_sidebar_width(width);}@@ -3650,6 +3706,20 @@ impl super::TermWindow {self.dragging.replace((item, start_event));}+ fn drag_right_sidebar_plugin_extended_resize(+ &mut self,+ item: UIItem,+ start_event: MouseEvent,+ event: MouseEvent,+ context: &dyn WindowOps,+ ) {+ if self.set_right_sidebar_plugin_extended_split_x(event.coords.x) {+ context.invalidate();+ }+ context.set_cursor(Some(MouseCursor::SizeLeftRight));+ self.dragging.replace((item, start_event));+ }+fn mouse_event_ui_item(&mut self,item: UIItem,@@ -3808,6 +3878,10 @@ impl super::TermWindow {UIItemType::RightSidebarNotePaneResize => {self.mouse_event_right_sidebar_note_pane_resize(item, event, context);}+ UIItemType::RightSidebarPluginExtendedResize => {+ // Pressed, it is dragged as the Note pane's line is.+ self.mouse_event_right_sidebar_note_pane_resize(item, event, context);+ }UIItemType::RightSidebarSnippetScrollTrack => {self.mouse_event_right_sidebar_snippet_scroll_track(item, event, context);}@@ -3854,6 +3928,24 @@ impl super::TermWindow {UIItemType::RightSidebarAgent(_) => {self.mouse_event_right_sidebar_agent(item.clone(), event, context);}+ UIItemType::RightSidebarPluginPanel => {+ self.mouse_event_plugin_panel(event, context, false);+ }+ UIItemType::RightSidebarPluginExtended => {+ self.mouse_event_plugin_panel(event, context, true);+ }+ UIItemType::RightSidebarPluginExtendedClose => {+ context.set_cursor(Some(MouseCursor::Hand));+ if event.kind == WMEK::Press(MousePress::Left) {+ self.dismiss_plugin_extended();+ }+ }+ UIItemType::RightSidebarPluginConnect(extended) => {+ context.set_cursor(Some(MouseCursor::Hand));+ if event.kind == WMEK::Press(MousePress::Left) {+ self.plugin_panel_connect(extended);+ }+ }UIItemType::RightSidebarNoteMenu| UIItemType::RightSidebarNoteChooseVault| UIItemType::RightSidebarNoteCreateVault@@ -4384,6 +4476,10 @@ impl super::TermWindow {UIItemType::RightSidebarNotePaneResize => {self.mouse_event_right_sidebar_note_pane_resize(item, event, context);}+ UIItemType::RightSidebarPluginExtendedResize => {+ // Pressed, it is dragged as the Note pane's line is.+ self.mouse_event_right_sidebar_note_pane_resize(item, event, context);+ }UIItemType::RightSidebarSnippetScrollTrack => {self.mouse_event_right_sidebar_snippet_scroll_track(item, event, context);}@@ -4430,6 +4526,24 @@ impl super::TermWindow {UIItemType::RightSidebarAgent(_) => {self.mouse_event_right_sidebar_agent(item.clone(), event, context);}+ UIItemType::RightSidebarPluginPanel => {+ self.mouse_event_plugin_panel(event, context, false);+ }+ UIItemType::RightSidebarPluginExtended => {+ self.mouse_event_plugin_panel(event, context, true);+ }+ UIItemType::RightSidebarPluginExtendedClose => {+ context.set_cursor(Some(MouseCursor::Hand));+ if event.kind == WMEK::Press(MousePress::Left) {+ self.dismiss_plugin_extended();+ }+ }+ UIItemType::RightSidebarPluginConnect(extended) => {+ context.set_cursor(Some(MouseCursor::Hand));+ if event.kind == WMEK::Press(MousePress::Left) {+ self.plugin_panel_connect(extended);+ }+ }UIItemType::RightSidebarNoteMenu| UIItemType::RightSidebarNoteChooseVault| UIItemType::RightSidebarNoteCreateVaultdiff --git a/wezterm-gui/src/termwindow/remote_files.rs b/wezterm-gui/src/termwindow/remote_files.rsindex 75831a7d..d97d0cab 100644--- a/wezterm-gui/src/termwindow/remote_files.rs+++ b/wezterm-gui/src/termwindow/remote_files.rs@@ -224,6 +224,26 @@ pub(crate) struct RemoteFileBytes {pub truncated: bool,}+/// What a program run over the connection printed, whether it printed more+/// than was kept, and the status it ended with: `None` when it was killed.+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct RemoteRun {+ pub out: Vec<u8>,+ pub cut: bool,+ pub status: Option<u32>,+}++/// What is at a remote path, a link not followed.+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct RemoteStat {+ pub kind: RemoteFileKind,+ pub size: u64,+ /// When it last changed, in seconds since 1970.+ pub modified: Option<u64>,+ /// Where a link points.+ pub target: Option<String>,+}+/// Bytes moved per round trip. SFTP is request/response over a single/// channel, so a bigger chunk means fewer round trips; this matches the read/// path's buffer and still leaves a cancel responsive on a slow link.@@ -742,6 +762,21 @@ pub(crate) trait RemoteFileBackend: Send + Sync {Box::pin(async { Err("This connection cannot create directories".to_string()) })}+ /// Runs `command`, a line for the remote user's shell, keeping at most+ /// `limit` bytes of what it prints; killed once it has run for `wait`.+ /// For a plugin's panel beside a terminal there (`plugin_panel`). The+ /// default refuses, as the other operations beyond reading do.+ fn run(&self, command: String, limit: usize, wait: Duration) -> RemoteFuture<RemoteRun> {+ let _ = (command, limit, wait);+ Box::pin(async { Err("This connection cannot run programs".to_string()) })+ }++ /// What is at `path`, a link not followed: `None` when nothing is.+ fn stat(&self, path: String) -> RemoteFuture<Option<RemoteStat>> {+ let _ = path;+ Box::pin(async { Err("This connection cannot look at files".to_string()) })+ }+/// Every file under `root` for search, listed on the remote host by/// `thinkterm list-files` under the rules the local index uses.fn list_project_files(@@ -791,6 +826,95 @@ fn shell_quote(value: &str) -> String {format!("'{}'", value.replace('\'', "'\\''"))}+/// The command line that runs `args` -- a program and its arguments -- in+/// the directory `cwd` on the remote host: under `sh`, whatever the login+/// shell is, every word quoted for the shell that reads the line. The+/// program reads nothing: the channel's input stays open while it runs+/// ([`close_remote_exec`]), and one that read it would wait.+pub(crate) fn run_command_line(cwd: &str, args: &[String]) -> String {+ let mut line = String::from("sh -c 'cd \"$1\" && shift && exec \"$@\" </dev/null' sh ");+ line.push_str(&shell_quote(cwd));+ for arg in args {+ line.push(' ');+ line.push_str(&shell_quote(arg));+ }+ line+}++/// How long a program on another machine that was killed -- it printed+/// too much, or ran too long -- is given to be done with before its channel+/// is closed on it. A server that takes the kill ends the channel within+/// this, once what it still holds has been read; one closed sooner is left+/// holding that, and keeps the channel open. Where the kill does nothing --+/// ssh2 sends no signals, nor does every server take them -- the close cuts+/// the program off, and it stops at its next write.+const REMOTE_KILL_GRACE: Duration = Duration::from_secs(10);++/// Lets go of the input of an exec channel, which closes the channel:+/// wezterm-ssh closes one whose input ends, and what the program prints+/// after that is lost, so the input is held until the program is done+/// with. One that was `killed` is given [`REMOTE_KILL_GRACE`] first.+fn close_remote_exec(stdin: wezterm_ssh::FileDescriptor, killed: bool) {+ if !killed {+ return drop(stdin);+ }+ let _ = std::thread::Builder::new()+ .name("remote-exec-close".into())+ .spawn(move || {+ std::thread::sleep(REMOTE_KILL_GRACE);+ drop(stdin);+ });+}++/// Reads what is left of `from`, a stream of an exec channel, to its end on+/// a thread of its own: the channel ends only once all it carries is read.+fn drain_remote(mut from: wezterm_ssh::FileDescriptor) {+ let _ = std::thread::Builder::new()+ .name("remote-exec-drain".into())+ .spawn(move || {+ let _ = std::io::copy(&mut from, &mut std::io::sink());+ });+}++/// Reads what a program run on an exec channel prints, keeping at most+/// `limit` bytes and killing it past that, and how it ended. Blocking: call+/// it off the UI thread. Its standard error drains on a thread of its own,+/// so a program that writes much there cannot stall it, and so does the+/// rest of what a program killed so prints.+fn read_remote_run(+ mut stdout: wezterm_ssh::FileDescriptor,+ stderr: wezterm_ssh::FileDescriptor,+ mut child: wezterm_ssh::SshChildProcess,+ limit: usize,+) -> Result<RemoteRun, String> {+ use portable_pty::{Child as _, ChildKiller as _};+ use std::io::Read;+ drain_remote(stderr);+ let mut out = Vec::new();+ (&mut stdout)+ .take(limit as u64 + 1)+ .read_to_end(&mut out)+ .map_err(|err| format!("Reading what it printed failed: {err}"))?;+ let cut = out.len() > limit;+ if cut {+ out.truncate(limit);+ let _ = child.kill();+ drain_remote(stdout);+ return Ok(RemoteRun {+ out,+ cut,+ status: None,+ });+ }+ // One killed by a signal has no status of its own.+ let status = child+ .wait()+ .ok()+ .filter(|status| status.signal().is_none())+ .map(|status| status.exit_code());+ Ok(RemoteRun { out, cut, status })+}+/// The command that lists `root` on the remote host: the host's configured/// `remote_wezterm_path` when there is one, as the mux proxy runs it; else/// `thinkterm` from where the proxy and the mobile probe look (an exec's shell@@ -845,19 +969,17 @@ fn interpret_remote_listing(})}-/// Run the listing on an exec channel of `session` and read it back. Blocking:-/// call it off the UI thread. stderr drains on a thread of its own, so a-/// remote that writes a lot there cannot stall the listing.-fn run_remote_listing(exec: wezterm_ssh::ExecResult) -> Result<RemoteProjectListing, String> {+/// Run the listing on an exec channel of `session` and read it back, and+/// whether the listing program was killed. Blocking: call it off the UI+/// thread. stderr drains on a thread of its own, so a remote that writes a+/// lot there cannot stall the listing.+fn run_remote_listing(+ mut stdout: wezterm_ssh::FileDescriptor,+ mut stderr: wezterm_ssh::FileDescriptor,+ mut child: wezterm_ssh::SshChildProcess,+) -> (Result<RemoteProjectListing, String>, bool) {use portable_pty::{Child as _, ChildKiller as _};use std::io::Read;- let wezterm_ssh::ExecResult {- stdin,- stdout,- mut stderr,- mut child,- } = exec;- drop(stdin);let stderr = std::thread::spawn(move || {let mut err = Vec::new();let _ = (&mut stderr).take(16 * 1024).read_to_end(&mut err);@@ -865,24 +987,35 @@ fn run_remote_listing(exec: wezterm_ssh::ExecResult) -> Result<RemoteProjectListerr});let mut out = Vec::new();- let read = stdout+ let read = (&mut stdout).take(REMOTE_LISTING_MAX_BYTES + 1).read_to_end(&mut out).map_err(|err| format!("{REMOTE_LISTING_READ_FAILED}: {err}"));if read.is_err() || out.len() as u64 > REMOTE_LISTING_MAX_BYTES {let _ = child.kill();- read?;- return Err("The remote file listing is too large".to_string());+ drain_remote(stdout);+ let failed = read.and(Err("The remote file listing is too large".to_string()));+ return (failed, true);}let err = stderr.join().unwrap_or_default();let exit_code = child.wait().ok().map(|status| status.exit_code());- interpret_remote_listing(&out, &String::from_utf8_lossy(&err), exit_code)+ let listing = interpret_remote_listing(&out, &String::from_utf8_lossy(&err), exit_code);+ (listing, false)}#[cfg(test)]mod listing_tests {use super::*;+ #[test]+ fn a_program_run_there_is_quoted_word_by_word() {+ let args = ["git".to_string(), "it's".to_string(), "$HOME".to_string()];+ assert_eq!(+ run_command_line("/srv/a b", &args),+ "sh -c 'cd \"$1\" && shift && exec \"$@\" </dev/null' sh '/srv/a b' 'git' 'it'\\''s' '$HOME'"+ );+ }+#[test]fn roots_are_quoted_for_the_shell() {assert_eq!(shell_quote("/srv/app"), "'/srv/app'");@@ -1112,6 +1245,79 @@ struct SftpRemoteFileBackend {}impl RemoteFileBackend for SftpRemoteFileBackend {+ fn run(&self, command: String, limit: usize, wait: Duration) -> RemoteFuture<RemoteRun> {+ // An exec channel on the session this backend already holds, as the+ // search listing's.+ let session = self._session.clone();+ let sftp = self.sftp.clone();+ Box::pin(async move {+ let wezterm_ssh::ExecResult {+ stdin,+ stdout,+ stderr,+ child,+ } = session+ .exec(&command, None)+ .await+ .map_err(|err| format!("Unable to run it there: {err:#}"))?;+ let mut killer = portable_pty::ChildKiller::clone_killer(&child);+ let ran = smol::unblock(move || read_remote_run(stdout, stderr, child, limit));+ let ran = async { Some(ran.await) };+ let timeout = async {+ smol::Timer::after(wait).await;+ let _ = killer.kill();+ None+ };+ let ran = smol::future::or(ran, timeout).await;+ // Killed when it printed too much, or ran out of time.+ let killed = matches!(&ran, None | Some(Ok(RemoteRun { cut: true, .. })));+ close_remote_exec(stdin, killed);+ let ran = ran.unwrap_or_else(|| Err(format!("It ran longer than {wait:?}")))?;+ // A channel that ends with no status -- the connection went --+ // is said by wezterm-ssh to have ended with 1: told apart by+ // whether the connection still answers.+ if ran.status == Some(1) && sftp.symlink_metadata(".".to_string()).await.is_err() {+ return Err("The connection closed while it ran".to_string());+ }+ Ok(ran)+ })+ }++ fn stat(&self, path: String) -> RemoteFuture<Option<RemoteStat>> {+ let sftp = self.sftp.clone();+ Box::pin(async move {+ let metadata = match sftp.symlink_metadata(path.clone()).await {+ Ok(metadata) => metadata,+ Err(err) if sftp_error_is_missing(&err) => return Ok(None),+ Err(err) => return Err(format!("Unable to look at {path}: {err}")),+ };+ let kind = if metadata.is_symlink() {+ RemoteFileKind::Symlink+ } else if metadata.is_dir() {+ RemoteFileKind::Directory+ } else if metadata.is_file() {+ RemoteFileKind::File+ } else {+ RemoteFileKind::Other+ };+ let target = match kind {+ RemoteFileKind::Symlink => sftp+ .read_link(path.clone())+ .await+ .map(|target| target.to_string())+ .map_err(|err| format!("Unable to read the link {path}: {err}"))+ .map(Some)?,+ _ => None,+ };+ Ok(Some(RemoteStat {+ kind,+ size: metadata.size.unwrap_or(0),+ modified: metadata.modified,+ target,+ }))+ })+ }+fn list_project_files(&self,root: RemotePath,@@ -1122,23 +1328,30 @@ impl RemoteFileBackend for SftpRemoteFileBackend {let session = self._session.clone();let command = list_files_command(&root, respect_gitignore, self.remote_command.as_deref());Box::pin(async move {- let exec = session+ let wezterm_ssh::ExecResult {+ stdin,+ stdout,+ stderr,+ child,+ } = session.exec(&command, None).await.map_err(|err| format!("{REMOTE_LISTING_EXEC_FAILED}: {err:#}"))?;// The remote walk stops itself at its time limit, but only between// entries; one stuck on a dead mount must not hold the search.- let mut killer = portable_pty::ChildKiller::clone_killer(&exec.child);- let listing = smol::unblock(move || run_remote_listing(exec));+ let mut killer = portable_pty::ChildKiller::clone_killer(&child);+ let listing = smol::unblock(move || run_remote_listing(stdout, stderr, child));let timeout = async {smol::Timer::after(Duration::from_secs(REMOTE_LISTING_TIME_LIMIT_SECS + REMOTE_LISTING_GRACE_SECS,)).await;let _ = killer.kill();- Err(REMOTE_LISTING_TIMED_OUT.to_string())+ (Err(REMOTE_LISTING_TIMED_OUT.to_string()), true)};- smol::future::or(listing, timeout).await+ let (listing, killed) = smol::future::or(listing, timeout).await;+ close_remote_exec(stdin, killed);+ listing})}diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rsindex 74371483..f7595692 100644--- a/wezterm-gui/src/termwindow/render/paint.rs+++ b/wezterm-gui/src/termwindow/render/paint.rs@@ -3531,6 +3531,8 @@ impl crate::TermWindow {return Ok(None);}let Some(progress) = self.right_sidebar_hover.progress(now) else {+ // Nothing of the sidebar shows: a plugin's panel is let go.+ self.close_plugin_panel();return Ok(None);};let ui_items_before = self.ui_items.len();diff --git a/wezterm-gui/src/termwindow/resize.rs b/wezterm-gui/src/termwindow/resize.rsindex 842f6c3d..c6a8307e 100644--- a/wezterm-gui/src/termwindow/resize.rs+++ b/wezterm-gui/src/termwindow/resize.rs@@ -2978,6 +2978,9 @@ impl super::TermWindow {rescale_ui_usize(self.right_sidebar_file_preview_width, old_dpi, new_dpi);self.right_sidebar_note_pane_width =rescale_ui_usize(self.right_sidebar_note_pane_width, old_dpi, new_dpi);+ if let Some(panel) = self.right_sidebar_plugin.as_mut() {+ panel.extended_width = rescale_ui_usize(panel.extended_width, old_dpi, new_dpi);+ }}if scale_changed {diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rsindex 6522f09e..64f07687 100644--- a/wezterm-gui/src/termwindow/ui/icons.rs+++ b/wezterm-gui/src/termwindow/ui/icons.rs@@ -4,6 +4,7 @@ use window::Image;#[allow(dead_code)]#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub enum SvgIcon {+ Activity,Archive,ArchiveRestore,ArrowDown,@@ -13,6 +14,10 @@ pub enum SvgIcon {Bell,Bot,Braces,+ Bug,+ Calendar,+ ChartCandlestick,+ ChartLine,Check,ChevronDown,ChevronRight,@@ -20,6 +25,8 @@ pub enum SvgIcon {CodeXml,ClipboardPaste,Copy,+ Cpu,+ Database,Download,Ellipsis,Expand,@@ -34,6 +41,9 @@ pub enum SvgIcon {FolderOpen,FolderPlus,FolderTree,+ Gauge,+ GitBranch,+ GitCompare,Globe,Grid2x2,House,@@ -44,6 +54,7 @@ pub enum SvgIcon {Loader,LoaderCircle,ListChecks,+ ListTodo,Maximize2,MemoryStick,MessageCircle,@@ -61,6 +72,7 @@ pub enum SvgIcon {Pin,PinOff,Plus,+ Puzzle,RotateCcw,RefreshCw,Redo,@@ -102,8 +114,47 @@ pub enum SvgIcon {}impl SvgIcon {+ /// The icon a plugin's panel names: one of those+ /// `thinkterm_plugin_panel::ICONS` lists, else the puzzle piece.+ pub fn for_panel(name: &str) -> Self {+ match name {+ "activity" => Self::Activity,+ "bug" => Self::Bug,+ "calendar" => Self::Calendar,+ "chart-candlestick" => Self::ChartCandlestick,+ "chart-line" => Self::ChartLine,+ "cpu" => Self::Cpu,+ "database" => Self::Database,+ "gauge" => Self::Gauge,+ "git-branch" => Self::GitBranch,+ "git-compare" => Self::GitCompare,+ "list-todo" => Self::ListTodo,+ _ => Self::Puzzle,+ }+ }+pub fn bytes(self) -> &'static [u8] {match self {+ Self::Activity => include_bytes!("../../../../third_party/lucide/icons/activity.svg"),+ Self::Bug => include_bytes!("../../../../third_party/lucide/icons/bug.svg"),+ Self::Calendar => include_bytes!("../../../../third_party/lucide/icons/calendar.svg"),+ Self::ChartCandlestick => {+ include_bytes!("../../../../third_party/lucide/icons/chart-candlestick.svg")+ }+ Self::ChartLine => {+ include_bytes!("../../../../third_party/lucide/icons/chart-line.svg")+ }+ Self::Cpu => include_bytes!("../../../../third_party/lucide/icons/cpu.svg"),+ Self::Database => include_bytes!("../../../../third_party/lucide/icons/database.svg"),+ Self::Gauge => include_bytes!("../../../../third_party/lucide/icons/gauge.svg"),+ Self::GitBranch => {+ include_bytes!("../../../../third_party/lucide/icons/git-branch.svg")+ }+ Self::GitCompare => {+ include_bytes!("../../../../third_party/lucide/icons/git-compare.svg")+ }+ Self::ListTodo => include_bytes!("../../../../third_party/lucide/icons/list-todo.svg"),+ Self::Puzzle => include_bytes!("../../../../third_party/lucide/icons/puzzle.svg"),Self::Archive => include_bytes!("../../../../third_party/lucide/icons/archive.svg"),Self::ArchiveRestore => {include_bytes!("../../../../third_party/lucide/icons/archive-restore.svg")@@ -700,6 +751,19 @@ mod tests {SvgIcon::Terminal,SvgIcon::Trash2,SvgIcon::X,+ // What a plugin's panel is shown by in the selector.+ SvgIcon::Activity,+ SvgIcon::Bug,+ SvgIcon::Calendar,+ SvgIcon::ChartCandlestick,+ SvgIcon::ChartLine,+ SvgIcon::Cpu,+ SvgIcon::Database,+ SvgIcon::Gauge,+ SvgIcon::GitBranch,+ SvgIcon::GitCompare,+ SvgIcon::ListTodo,+ SvgIcon::Puzzle,// The agent marks come from a different upstream than the// rest, sized in `em` rather than pixels: keep them covered so// a re-vendored file that usvg cannot size fails here.diff --git a/wezterm-gui/src/termwindow/ui/mod.rs b/wezterm-gui/src/termwindow/ui/mod.rsindex 40add428..e1fc30ea 100644--- a/wezterm-gui/src/termwindow/ui/mod.rs+++ b/wezterm-gui/src/termwindow/ui/mod.rs@@ -4,6 +4,7 @@ pub mod context_menu;pub mod folder_problem;pub mod icons;pub mod platform_chrome;+pub mod plugin_panel;pub mod right_sidebar;pub mod recording_overlay;pub mod sidebar;diff --git a/wezterm-gui/src/termwindow/ui/plugin_panel.rs b/wezterm-gui/src/termwindow/ui/plugin_panel.rsnew file mode 100644index 00000000..fb5c7899--- /dev/null+++ b/wezterm-gui/src/termwindow/ui/plugin_panel.rs@@ -0,0 +1,1939 @@+//! A plugin's panel in the right sidebar: the view the plugin host serves+//! this window, the player that shows it, and how the player's items are+//! painted with the sidebar's own quads, fonts and colours.+//!+//! Every item is recorded into a heap first and laid on the frame cut to+//! its region, which is how a row half out of a list comes out half drawn.+//! Lines and filled areas become columns a pixel wide, only where they+//! show: the quads the renderer draws are upright rectangles, and cutting a+//! column is cutting a rectangle. What was recorded is kept, and laid again+//! frame after frame while the panel stays as it was: a terminal busy+//! beside it repaints the window, not the panel.+//!+//! The panel is opened when it comes on show and closed when it goes: a+//! plugin runs, and keeps its data, only while someone looks at it.+//!+//! A panel whose frames ask for it has an extended view as well, left of+//! the sidebar, as wide as the user drags it (`right_sidebar`): a second+//! view the host serves this window, with a player of its own, opened on+//! each opening of the panel once the panel is drawn on it, and closed+//! when the panel stops asking.+//!+//! Beside a terminal on another machine reached over SSH, a panel is told+//! which, and its plugin asks this window to run programs and read files+//! there: over the connection Files reaches that machine with, and only+//! once the user has let ThinkTerm connect to it -- in Files, or with the+//! button the panel shows in place of what the plugin drew until then.++use crate::plugins::{self, PanelNews};+use crate::quad::{HeapQuadAllocator, QuadClipRect, QuadTrait, TripleLayerQuadAllocator};+use crate::termwindow::remote_files::{+ authorize_remote_source, remote_connection_key, remote_connection_manager,+ remote_source_is_authorized, run_command_line, RemoteAcquireError, RemoteFileKind,+ RemoteFilesState, RemotePath,+};+use crate::termwindow::render::corners::{+ BOTTOM_LEFT_ROUNDED_CORNER_OUTLINE, BOTTOM_RIGHT_ROUNDED_CORNER_OUTLINE,+ TOP_LEFT_ROUNDED_CORNER_OUTLINE, TOP_RIGHT_ROUNDED_CORNER_OUTLINE,+};+use crate::termwindow::{TermWindow, TermWindowNotif, UIItem, UIItemType};+use crate::ui::UiPalette;+use crate::utilsprites::RenderMetrics;+use crate::workspace_threads;+use anyhow::Context;+use mux::domain::{Domain, DomainId};+use mux::pane::{CachePolicy, Pane, PaneId};+use mux::Mux;+use std::collections::hash_map::RandomState;+use std::convert::TryFrom;+use std::hash::BuildHasher;+use std::rc::Rc;+use std::sync::{Arc, OnceLock};+use std::time::{Duration, Instant};+use thinkterm_plugin_channel::wire::{PanelRequest, Raw};+use thinkterm_plugin_panel::{+ Align, Answer, Area, Ask, Bounds, Button, Bytes, CloseButton, Color, Cursor, Draw, Drawn,+ Entry, EntryKind, Env, Font, Input, Line, Mods, MonoMetrics, Player, Rect, Remote, Size, Text,+ TextMetrics, Token,+};+use url::Url;+use wezterm_font::LoadedFont;+use window::color::LinearRgba;+use window::{MouseCursor, MouseEvent, MouseEventKind as WMEK, MousePress, RectF, WindowOps};++/// How long a panel the host closed, but may serve again, waits before it+/// is opened anew: a restart is under way.+const REOPEN_AFTER: Duration = Duration::from_millis(400);+/// A plugin's panel draws everything on the text layer, in its own order:+/// a rectangle drawn after text covers it.+const LAYER: usize = 2;+/// The least time between two sizes told to a plugin: a window being+/// resized changes its panel's size each frame, and each is drawn anew.+const ENV_EVERY: Duration = Duration::from_millis(100);+/// The most quads a painting is recorded with: a glyph each, a column for+/// each pixel a line or an area crosses. What is beyond it is left out.+const QUAD_LIMIT: usize = 100_000;+/// The most a plugin's ask brings back from another machine: with the+/// answer carried as base64, it fits in a frame to the plugin.+const ASK_BYTES: usize = 8 * 1024 * 1024;+/// How long a program a plugin runs on another machine may take.+const ASK_RUN_WAIT: Duration = Duration::from_secs(20);+/// How long how the machine beside the panel is reached is kept before it+/// is found again.+const REACH_AGAIN: Duration = Duration::from_secs(3);++pub(crate) struct PluginPanel {+ plugin: String,+ /// The panel in the sidebar.+ shown: Shown,+ /// Counts the panel's openings: its extended view is opened on one, and+ /// again on the next.+ opening: u32,+ /// Its extended view, and the opening of the panel it was opened on.+ extended: Option<(Shown, u32)>,+ /// How wide the user made the extended view, in window pixels; 0 for+ /// the width it starts at.+ pub(crate) extended_width: usize,+ /// The user closed the extended view with its close button: it is not+ /// opened again until the panel's frames have stopped asking for it.+ dismissed: bool,+}++/// A view the host serves this window -- a panel, or its extended view --+/// and the player that shows it.+struct Shown {+ view: u64,+ player: Player,+ status: Status,+ /// Where it was last painted, in window pixels, and pixels to a unit:+ /// for turning the pointer into its units.+ origin: (f32, f32),+ scale: f32,+ /// What was last recorded, and what it was recorded for.+ painted: Option<Painted>,+ /// When the plugin was last told its size, and whether the player has+ /// one since that it is still to be told: rows asked for meanwhile,+ /// which are drawn for it, wait until it is.+ env_told: Instant,+ env_due: bool,+ /// Its plugin asked something of the machine beside it, which ThinkTerm+ /// may not connect to yet: shown instead of what it drew.+ connect: Option<Connect>,+}++/// A machine a plugin needs ThinkTerm connected to, and the source Files+/// knows it by, which the user lets ThinkTerm connect to.+struct Connect {+ host: String,+ /// The machine, as the view's env names it ([`Reach::machine`]).+ machine: String,+ source_key: String,+}++/// Where the terminal beside the panel is, as far as is known.+enum Beside {+ /// On this machine, in this directory.+ Here(String),+ /// On another, in a directory there.+ There(Remote),+ /// Not known yet: the panel stays where it was until it is.+ Unknown,+ /// Where no plugin can follow: a terminal whose directory names nothing+ /// a plugin can reach, or on a machine that cannot be reached.+ Nowhere,+}++/// How the machine beside the panel is reached: the connection Files keeps+/// to it.+#[derive(Clone)]+pub(crate) struct Reach {+ /// The machine, by the name the user is shown.+ host: String,+ /// The connection, by the word its plugin is told ([`machine_word`]).+ machine: String,+ source_key: String,+ connection_key: String,+ config: config::SshDomain,+}++impl Shown {+ fn new(view: u64, player: Player) -> Self {+ Self {+ view,+ player,+ status: Status::Opening,+ origin: (0.0, 0.0),+ scale: 1.0,+ painted: None,+ env_told: Instant::now(),+ env_due: false,+ connect: None,+ }+ }++ /// Whether the pointer at `x`, `y` in window pixels is over it, and+ /// where in its units.+ fn under(&self, x: f32, y: f32) -> Option<(f32, f32)> {+ let x = (x - self.origin.0) / self.scale;+ let y = (y - self.origin.1) / self.scale;+ let env = self.player.env();+ (x >= 0.0 && y >= 0.0 && x < env.width && y < env.height).then_some((x, y))+ }+}++impl PluginPanel {+ pub(crate) fn plugin(&self) -> &str {+ &self.plugin+ }++ /// Whether the panel's frames ask for its extended view, and it is to+ /// have one: not once it cannot be served.+ pub(crate) fn wants_extended(&self) -> bool {+ self.shown.player.shown()+ && self.shown.player.extend()+ && !self.dismissed+ && !matches!(self.shown.status, Status::Stopped(_))+ }+}++/// A painting recorded as quads, a heap for each region it is cut to.+struct Painted {+ key: PaintKey,+ regions: Vec<(Bounds, HeapQuadAllocator)>,+}++/// Everything a recorded painting depends on: the same key paints the same.+#[derive(PartialEq)]+struct PaintKey {+ revision: u64,+ origin: (f32, f32),+ scale: f32,+ window: (usize, usize),+ /// Bumped when the glyphs the quads point into may have moved.+ shapes: usize,+ chrome: UiPalette,+ sizes: [f64; 3],+ mono_size: f64,+}++enum Status {+ /// Opened, and nothing drawn yet.+ Opening,+ Open,+ /// The host closed it, and it is opened again at this time.+ Again(Instant),+ /// The host cannot serve it, for this reason.+ Stopped(String),+ /// The host cannot be reached, for this reason: it is opened again once+ /// it can, and keeps its room meanwhile -- an extended view's too.+ Lost(String),+}++/// What a panel and its extended view are painted with in one frame: the+/// fonts, pixels to a unit, and where the terminal beside them is -- its+/// directory here, or the other machine it runs on.+pub(crate) struct PanelPaint {+ fonts: PanelFonts,+ scale: f32,+ cwd: Option<String>,+ remote: Option<Remote>,+}++/// The fonts a panel's text is set in, for one paint.+struct PanelFonts {+ small: (Rc<LoadedFont>, RenderMetrics),+ body: (Rc<LoadedFont>, RenderMetrics),+ title: (Rc<LoadedFont>, RenderMetrics),+ small_bold: (Rc<LoadedFont>, RenderMetrics),+ body_bold: (Rc<LoadedFont>, RenderMetrics),+ title_bold: (Rc<LoadedFont>, RenderMetrics),+ mono: (Rc<LoadedFont>, RenderMetrics),+ sizes: [f64; 3],+ mono_size: f64,+}++impl PanelFonts {+ fn of(&self, text: &Text) -> &(Rc<LoadedFont>, RenderMetrics) {+ match (text.font, text.size, text.bold) {+ (Font::Mono, ..) => &self.mono,+ (Font::Ui, Size::Small, false) => &self.small,+ (Font::Ui, Size::Body, false) => &self.body,+ (Font::Ui, Size::Title, false) => &self.title,+ (Font::Ui, Size::Small, true) => &self.small_bold,+ (Font::Ui, Size::Body, true) => &self.body_bold,+ (Font::Ui, Size::Title, true) => &self.title_bold,+ }+ }+}++/// Physical pixels to one of a panel's units: a point, as a browser's CSS+/// pixel is, so a panel is laid out alike on the desktop and on a page.+pub(crate) fn panel_scale(dpi: usize) -> f32 {+ let points = if cfg!(target_os = "macos") {+ 72.0+ } else {+ 96.0+ };+ (dpi.max(1) as f32 / points).max(0.25)+}++/// The colours a panel names, in the chrome's palette. The palette has no+/// green or amber, so those are fixed, a shade apart for dark and light.+/// The grounds are solid: laid on the panel's own ground beforehand, since+/// a see-through green blends in linear light and reads twice as strong.+pub(crate) fn token_color(chrome: &UiPalette, token: Token) -> LinearRgba {+ let dark = chrome.is_dark();+ let pick = |dark_rgb: (u8, u8, u8), light_rgb: (u8, u8, u8)| {+ let (r, g, b) = if dark { dark_rgb } else { light_rgb };+ LinearRgba::with_srgba(r, g, b, 255)+ };+ let positive = pick((63, 185, 80), (26, 127, 55));+ let negative = pick((248, 81, 73), (207, 34, 46));+ let ground = chrome.workspace_sidebar_bg;+ let (faint, strong) = if dark { (0.16, 0.34) } else { (0.12, 0.26) };+ match token {+ Token::Text => chrome.text,+ Token::TextMuted => chrome.secondary_text,+ Token::TextFaint => chrome.muted_text,+ Token::Bg => chrome.workspace_sidebar_bg,+ Token::BgRaised => chrome.sidebar_button_bg,+ Token::BgHover => chrome.sidebar_row_hover_bg,+ Token::BgSelected => chrome.sidebar_row_active_bg,+ Token::Border => chrome.separator,+ Token::Accent => chrome.accent,+ Token::OnAccent => chrome.on_accent,+ Token::Positive => positive,+ Token::Negative => negative,+ Token::Warning => pick((210, 153, 34), (154, 103, 0)),+ Token::PositiveBg => mixed(ground, positive, faint),+ Token::NegativeBg => mixed(ground, negative, faint),+ Token::PositiveBgStrong => mixed(ground, positive, strong),+ Token::NegativeBgStrong => mixed(ground, negative, strong),+ }+}++/// `over` laid on `ground` at `amount`, mixed as sRGB is.+fn mixed(ground: LinearRgba, over: LinearRgba, amount: f32) -> LinearRgba {+ let (r0, g0, b0, _) = ground.srgba_pixel().as_rgba();+ let (r1, g1, b1, _) = over.srgba_pixel().as_rgba();+ let mix = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * amount).round() as u8;+ LinearRgba::with_srgba(mix(r0, r1), mix(g0, g1), mix(b0, b1), 255)+}++fn color(chrome: &UiPalette, color: Color) -> LinearRgba {+ match color {+ Color::Token(token) => token_color(chrome, token),+ Color::Rgba([r, g, b, a]) => LinearRgba::with_srgba(r, g, b, a),+ }+}++impl TermWindow {+ /// What a panel and its extended view are painted with in a frame,+ /// worked out once for both.+ pub(crate) fn plugin_panel_paint(&mut self) -> anyhow::Result<PanelPaint> {+ let (cwd, remote) = match self.plugin_panel_beside() {+ Beside::Here(cwd) => (Some(cwd), None),+ Beside::There(remote) => (None, Some(remote)),+ Beside::Nowhere => (None, None),+ // Where it was, for now: told nothing new, the plugin keeps+ // what it shows.+ Beside::Unknown => match &self.right_sidebar_plugin {+ Some(panel) => {+ let env = panel.shown.player.env();+ (env.cwd.clone(), env.remote.clone())+ }+ None => (None, None),+ },+ };+ Ok(PanelPaint {+ fonts: self.plugin_panel_fonts()?,+ scale: panel_scale(self.dimensions.dpi),+ remote,+ cwd,+ })+ }++ /// Paints plugin `plugin`'s panel in the content area, opening it first+ /// if this window does not show it yet.+ #[allow(clippy::too_many_arguments)]+ pub(crate) fn paint_plugin_panel(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ plugin: &str,+ paint: &PanelPaint,+ ui_font: &Rc<LoadedFont>,+ ui_metrics: RenderMetrics,+ chrome: UiPalette,+ content_x: usize,+ content_top: usize,+ content_width: usize,+ content_bottom: usize,+ ) -> anyhow::Result<()> {+ let height = content_bottom.saturating_sub(content_top);+ if content_width == 0 || height == 0 {+ return Ok(());+ }+ let PanelPaint {+ fonts,+ scale,+ cwd,+ remote,+ } = paint;+ let scale = *scale;+ let mut env = panel_env(fonts, &chrome, content_width as f32, height as f32, scale);+ env.cwd = cwd.clone();+ env.remote = remote.clone();+ env.can_extend = self.right_sidebar_plugin_can_extend();+ self.follow_plugin_panel(plugin, env);+ // The extended view goes once nothing asks for it, or there is no+ // room left for it.+ if self.right_sidebar_plugin_extended_rect().is_none() {+ self.close_plugin_extended();+ }+ self.ui_items.push(UIItem {+ x: content_x,+ y: content_top,+ width: content_width,+ height,+ item_type: UIItemType::RightSidebarPluginPanel,+ });+ let Some(mut panel) = self.right_sidebar_plugin.take() else {+ return Ok(());+ };+ let area = (content_x, content_top, content_width);+ let painted = self.paint_plugin_view(+ layers,+ &mut panel.shown,+ false,+ area,+ scale,+ ui_font,+ ui_metrics,+ fonts,+ &chrome,+ );+ self.right_sidebar_plugin = Some(panel);+ painted+ }++ /// Paints the extended view of the panel on show in its area, opening+ /// it first when it is not open on the panel's opening. `close` is the+ /// close button the caller draws over it, in window pixels -- left,+ /// top, side -- which its plugin is told of.+ #[allow(clippy::too_many_arguments)]+ pub(crate) fn paint_plugin_panel_extended(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ paint: &PanelPaint,+ ui_font: &Rc<LoadedFont>,+ ui_metrics: RenderMetrics,+ chrome: UiPalette,+ content_x: usize,+ content_top: usize,+ content_width: usize,+ content_bottom: usize,+ close: (usize, usize, usize),+ ) -> anyhow::Result<()> {+ let height = content_bottom.saturating_sub(content_top);+ if content_width == 0 || height == 0 {+ return Ok(());+ }+ let PanelPaint {+ fonts,+ scale,+ cwd,+ remote,+ } = paint;+ let scale = *scale;+ let mut env = panel_env(fonts, &chrome, content_width as f32, height as f32, scale);+ env.cwd = cwd.clone();+ env.remote = remote.clone();+ let (x, y, size) = close;+ env.close = Some(CloseButton {+ x: (x as f32 - content_x as f32) / scale,+ y: (y as f32 - content_top as f32) / scale,+ size: size as f32 / scale,+ });+ self.follow_plugin_extended(env);+ self.ui_items.push(UIItem {+ x: content_x,+ y: content_top,+ width: content_width,+ height,+ item_type: UIItemType::RightSidebarPluginExtended,+ });+ let Some(mut panel) = self.right_sidebar_plugin.take() else {+ return Ok(());+ };+ let area = (content_x, content_top, content_width);+ let painted = match panel.extended.as_mut() {+ Some((extended, _)) => self.paint_plugin_view(+ layers, extended, true, area, scale, ui_font, ui_metrics, fonts, &chrome,+ ),+ None => Ok(()),+ };+ self.right_sidebar_plugin = Some(panel);+ painted+ }++ /// Paints one view from the top left corner of `area`, `width` wide:+ /// what its player draws, or what it says instead while it has nothing+ /// to show -- or the button that lets ThinkTerm connect to the machine+ /// beside it, while its plugin waits for that.+ #[allow(clippy::too_many_arguments)]+ fn paint_plugin_view(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ shown: &mut Shown,+ extended: bool,+ area: (usize, usize, usize),+ scale: f32,+ ui_font: &Rc<LoadedFont>,+ ui_metrics: RenderMetrics,+ fonts: &PanelFonts,+ chrome: &UiPalette,+ ) -> anyhow::Result<()> {+ let (x, y, width) = area;+ shown.origin = (x as f32, y as f32);+ shown.scale = scale;+ // What the pointer is over is settled here as well as on each move:+ // leaving the view for another part of the window sends it no event.+ let pointer = self+ .current_mouse_event+ .as_ref()+ .and_then(|event| shown.under(event.coords.x as f32, event.coords.y as f32));+ match pointer {+ Some((x, y)) => {+ shown.player.pointer_moved(x, y);+ }+ None => {+ shown.player.pointer_left();+ }+ }++ // Wanted no longer once the terminal beside it is elsewhere, or the+ // user let ThinkTerm connect, in Files say.+ let wanted = shown.connect.as_ref().is_some_and(|connect| {+ let beside = shown.player.env().remote.as_ref();+ beside.is_some_and(|remote| remote.machine == connect.machine)+ && !remote_source_is_authorized(&connect.source_key)+ });+ if !wanted {+ shown.connect = None;+ }+ if let Some(connect) = &shown.connect {+ let inset = (8.0 * scale) as usize;+ let lead = shown+ .player+ .env()+ .close+ .map_or(0, |close| ((close.x + close.size) * scale) as usize);+ let left = x + lead + inset;+ let room = width.saturating_sub(lead + inset * 2);+ let mut args = fluent_bundle::FluentArgs::new();+ args.set("host", connect.host.clone());+ let needs = crate::i18n::tr_args("right-plugin-connect", &args);+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ &needs,+ left,+ y + inset,+ room,+ chrome.secondary_text,+ )?;+ let button_top = y + inset * 2 + ui_metrics.cell_size.height as usize;+ let button_width = room.min(self.ui_px(160));+ return self.paint_remote_files_connect_button(+ layers,+ ui_font,+ ui_metrics,+ *chrome,+ left,+ button_top,+ button_width,+ &crate::i18n::tr("right-connect"),+ true,+ UIItemType::RightSidebarPluginConnect(extended),+ );+ }++ let message = match &shown.status {+ Status::Opening | Status::Again(_) if !shown.player.shown() => {+ Some(crate::i18n::tr("right-plugin-starting"))+ }+ Status::Stopped(reason) | Status::Lost(reason) => {+ let mut args = fluent_bundle::FluentArgs::new();+ args.set("reason", reason.clone());+ Some(crate::i18n::tr_args("right-plugin-stopped", &args))+ }+ _ => None,+ };+ if let Some(message) = message {+ let inset = (8.0 * scale) as usize;+ // Right of an extended view's close button.+ let lead = shown+ .player+ .env()+ .close+ .map_or(0, |close| ((close.x + close.size) * scale) as usize);+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ &message,+ x + lead + inset,+ y + inset,+ width.saturating_sub(lead + inset * 2),+ chrome.secondary_text,+ )?;+ return Ok(());+ }+ self.paint_plugin_panel_items(layers, shown, fonts, chrome)+ }++ /// Opens plugin `plugin`'s panel for `env` unless this window shows it+ /// already, closing any other; tells the plugin a size or theme that+ /// changed, the last of those within [`ENV_EVERY`]; and opens a panel+ /// the host closed again once it is time.+ fn follow_plugin_panel(&mut self, plugin: &str, env: Env) {+ if self+ .right_sidebar_plugin+ .as_ref()+ .is_some_and(|panel| panel.plugin != plugin)+ {+ self.close_plugin_panel();+ }+ let Some(panel) = self.right_sidebar_plugin.as_mut() else {+ let Some(window) = self.window.clone() else {+ return;+ };+ let view = plugins::open_panel(plugin, &env, None, &window);+ let extended_width = super::right_sidebar::right_sidebar_plugin_extended_width_for(+ plugin,+ self.dimensions.dpi,+ );+ self.right_sidebar_plugin = Some(PluginPanel {+ plugin: plugin.to_string(),+ shown: Shown::new(view, Player::new(env)),+ opening: 0,+ extended: None,+ extended_width,+ dismissed: false,+ });+ return;+ };+ let now = Instant::now();+ let shown = &mut panel.shown;+ if let Status::Again(at) = shown.status {+ if now >= at {+ shown.player.set_env(env);+ shown.player.restarted();+ shown.status = Status::Opening;+ shown.env_told = now;+ shown.env_due = false;+ panel.opening = panel.opening.wrapping_add(1);+ plugins::reopen_panel(shown.view, &panel.plugin, shown.player.env());+ } else {+ self.update_next_frame_time(Some(at));+ }+ return;+ }+ if let Some(due) = tell_env(shown, env, now) {+ self.update_next_frame_time(Some(due));+ }+ }++ /// Opens the extended view of the panel on show for `env` unless it is+ /// open on the panel's opening -- once the panel is drawn on that, one+ /// opened on an earlier showing what it last had meanwhile -- and tells+ /// the plugin a size or theme that changed, as for the panel.+ fn follow_plugin_extended(&mut self, env: Env) {+ let Some(window) = self.window.clone() else {+ return;+ };+ let Some(panel) = self.right_sidebar_plugin.as_mut() else {+ return;+ };+ let opening = panel.opening;+ match panel.extended.as_mut() {+ Some((extended, on)) if *on == opening => {+ if let Some(due) = tell_env(extended, env, Instant::now()) {+ self.update_next_frame_time(Some(due));+ }+ }+ _ if !matches!(panel.shown.status, Status::Open) => {}+ _ => {+ let player = match panel.extended.take() {+ Some((stale, _)) => {+ plugins::close_panel(stale.view);+ let mut player = stale.player;+ player.set_env(env);+ player.restarted();+ player+ }+ None => Player::new(env),+ };+ let view = plugins::open_panel(+ &panel.plugin,+ player.env(),+ Some(panel.shown.view),+ &window,+ );+ panel.extended = Some((Shown::new(view, player), opening));+ }+ }+ }++ /// Opens the right sidebar on plugin `plugin`'s panel, if the sidebar+ /// offers it.+ pub(crate) fn show_plugin_panel(&mut self, plugin: &str) {+ let Some(id) = crate::termwindow::PanelId::new(plugin) else {+ log::warn!("no plugin is named {plugin:?}");+ return;+ };+ let mode = crate::termwindow::RightSidebarMode::Plugin(id);+ if !mode.panel_enabled() {+ log::warn!("the right sidebar offers no panel of plugin {plugin}");+ return;+ }+ self.right_sidebar_mode = mode;+ if self.right_sidebar_collapsed {+ self.expand_right_sidebar();+ }+ if let Some(window) = self.window.as_ref().cloned() {+ let dimensions = self.dimensions;+ self.apply_dimensions(&dimensions, None, &window);+ window.invalidate();+ }+ }++ /// Lets go of the panel on show, if one is, and of its extended view:+ /// the plugin is told, and what they held is freed.+ pub(crate) fn close_plugin_panel(&mut self) {+ if let Some(panel) = self.right_sidebar_plugin.take() {+ if let Some((extended, _)) = panel.extended {+ plugins::close_panel(extended.view);+ }+ plugins::close_panel(panel.shown.view);+ }+ self.plugin_panel_domains.clear();+ self.plugin_panel_reach = None;+ }++ /// The extended view's close button pressed: the view goes at once,+ /// its plugin is told the user closed it, and the panel gets none until+ /// its frames have stopped asking for one.+ pub(crate) fn dismiss_plugin_extended(&mut self) {+ let before = self.right_sidebar_width();+ let Some(panel) = self.right_sidebar_plugin.as_mut() else {+ return;+ };+ panel.dismissed = true;+ if let Some((extended, _)) = panel.extended.take() {+ let input = Raw::new(&Input::Close);+ plugins::tell_panel(extended.view, PanelRequest::Input { input });+ plugins::close_panel(extended.view);+ }+ if let Some(window) = self.window.as_ref() {+ window.invalidate();+ }+ self.reflow_right_sidebar_if_width_changed(before);+ }++ /// Lets go of the extended view of the panel on show, if it has one.+ fn close_plugin_extended(&mut self) {+ let extended = self+ .right_sidebar_plugin+ .as_mut()+ .and_then(|panel| panel.extended.take());+ if let Some((extended, _)) = extended {+ plugins::close_panel(extended.view);+ }+ }++ /// Where the terminal of the pane in focus in this window is, for the+ /// plugin panel: its directory here, once a look off this thread said+ /// it runs on this machine, where the plugin does -- the path of one on+ /// a host reached over SSH names nothing here -- or the other machine+ /// and its directory there. Not known yet while the look is on its way,+ /// or the terminal has not said where it is -- a tab just opened, whose+ /// shell has only begun -- or while the window has no pane in focus, as+ /// on the way to a new tab's.+ fn plugin_panel_beside(&mut self) -> Beside {+ let Some(pane) = self.get_active_pane_no_overlay() else {+ return Beside::Unknown;+ };+ match self.plugin_pane_runs_here(pane.domain_id()) {+ None => Beside::Unknown,+ Some(true) => match pane.get_current_working_dir(CachePolicy::AllowStale) {+ None => Beside::Unknown,+ Some(url) => local_path(&url).map_or(Beside::Nowhere, Beside::Here),+ },+ Some(false) => self.plugin_panel_remote(pane.pane_id(), &pane),+ }+ }++ /// Whether the panes of domain `domain_id` run on this machine: `None`+ /// until a look off this thread says, once for the domain. Another tab+ /// of a domain the panel was beside already is known at once, so the+ /// panel's directory does not go missing while the answer comes, and+ /// its plugin does not let go of what it shows there.+ fn plugin_pane_runs_here(&mut self, domain_id: DomainId) -> Option<bool> {+ if let Some((_, here)) = self+ .plugin_panel_domains+ .iter()+ .find(|(id, _)| *id == domain_id)+ {+ return *here;+ }+ match Mux::get().get_domain(domain_id) {+ Some(domain) => {+ self.plugin_panel_domains.push((domain_id, None));+ self.look_where_domain_runs(domain_id, domain);+ None+ }+ None => {+ self.plugin_panel_domains.push((domain_id, Some(false)));+ Some(false)+ }+ }+ }++ /// The other machine pane `pane_id`, `pane`, runs on, reached over SSH,+ /// and its directory there, for the plugin panel: once a look off this+ /// thread said the pane does not run here. The machine is found the way+ /// Files finds it, once for each pane.+ fn plugin_panel_remote(&mut self, pane_id: PaneId, pane: &Arc<dyn Pane>) -> Beside {+ let (host, machine) = match self.plugin_panel_reach_of(pane_id) {+ Ok(reach) => (reach.host.clone(), reach.machine.clone()),+ Err(_) => return Beside::Nowhere,+ };+ match pane.get_current_working_dir(CachePolicy::AllowStale) {+ None => Beside::Unknown,+ Some(url) => remote_path(&url).map_or(Beside::Nowhere, |cwd| {+ Beside::There(Remote { host, machine, cwd })+ }),+ }+ }++ /// How the machine the pane in focus runs on is reached.+ fn plugin_panel_reach(&mut self) -> Result<Reach, String> {+ let pane_id = self+ .get_active_pane_no_overlay()+ .ok_or_else(|| "no terminal is beside the panel".to_string())?+ .pane_id();+ self.plugin_panel_reach_of(pane_id).clone()+ }++ /// How the machine pane `pane_id` runs on is reached: found for the+ /// pane when it comes beside the panel, as Files finds it, and again+ /// off this thread once it is [`REACH_AGAIN`] old, so that a host+ /// edited in the host list, or a domain not yet there when it was+ /// first looked for, is followed. Each frame takes only its names.+ fn plugin_panel_reach_of(&mut self, pane_id: PaneId) -> &Result<Reach, String> {+ match &self.plugin_panel_reach {+ Some((id, found, _)) if *id == pane_id => {+ if found.elapsed() >= REACH_AGAIN {+ self.find_plugin_panel_reach_again(pane_id);+ }+ }+ _ => {+ let reach = self.plugin_remote_reach();+ self.plugin_panel_reach = Some((pane_id, Instant::now(), reach));+ }+ }+ match &self.plugin_panel_reach {+ Some((_, _, reach)) => reach,+ None => unreachable!("just found"),+ }+ }++ /// Finds how the machine pane `pane_id` runs on is reached again, on a+ /// thread of its own: the connection's settings are read from disk,+ /// which a frame is not to wait for. Kept while the pane is still the+ /// one beside the panel, which is painted again if its machine is now+ /// another.+ fn find_plugin_panel_reach_again(&mut self, pane_id: PaneId) {+ let target = match self.active_remote_project_for_files() {+ Ok(Some(target)) => target,+ found => {+ let why = found.err().unwrap_or_else(|| {+ "the terminal beside the panel runs on this machine".to_string()+ });+ self.plugin_panel_reach = Some((pane_id, Instant::now(), Err(why)));+ return;+ }+ };+ // Not looked for again until this look is as old.+ if let Some((_, found, _)) = &mut self.plugin_panel_reach {+ *found = Instant::now();+ }+ let Some(window) = self.window.clone() else {+ return;+ };+ promise::spawn::spawn(async move {+ let reach = promise::spawn::spawn_into_new_thread(move || Ok(Self::reach_of(&target)))+ .await+ .unwrap_or_else(|err| Err(format!("{err:#}")));+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ let Some((id, found, before)) = &mut term_window.plugin_panel_reach else {+ return;+ };+ if *id != pane_id {+ return;+ }+ let moved = match (&*before, &reach) {+ (Ok(before), Ok(now)) => {+ (&before.host, &before.machine) != (&now.host, &now.machine)+ }+ (Err(_), Err(_)) => false,+ _ => true,+ };+ *found = Instant::now();+ *before = reach;+ if moved {+ if let Some(window) = term_window.window.as_ref() {+ window.invalidate();+ }+ }+ })));+ })+ .detach();+ }++ /// How the machine the pane in focus runs on is reached: the project's,+ /// as Files reaches it.+ fn plugin_remote_reach(&self) -> Result<Reach, String> {+ let target = self+ .active_remote_project_for_files()?+ .ok_or_else(|| "the terminal beside the panel runs on this machine".to_string())?;+ Self::reach_of(&target)+ }++ /// How `target`, a project's machine, is reached. Reads the connection's+ /// settings from disk -- the host list, ~/.ssh/config, the key a saved+ /// password is kept under -- so any thread may call it.+ fn reach_of(target: &workspace_threads::RemoteFilesTarget) -> Result<Reach, String> {+ let config = Self::ssh_config_for_remote_files_target(target)?;+ let source_key = RemoteFilesState::source_key(&target.source);+ let connection_key = remote_connection_key(&source_key, &config);+ Ok(Reach {+ host: host_name(&config.remote_address),+ machine: machine_word(&connection_key),+ source_key,+ connection_key,+ config,+ })+ }++ /// Does what the plugin of view `view` asked of the machine beside its+ /// panel, over the connection Files reaches it with, and answers. One+ /// the user has not let ThinkTerm open is not opened for a plugin: the+ /// view shows a button that lets it instead, and the plugin is told to+ /// ask again after.+ fn plugin_panel_ask(&mut self, view: u64, id: u64, machine: String, ask: Ask) {+ let reach = match self.plugin_panel_reach() {+ Ok(reach) => reach,+ Err(why) => return plugins::answer(view, id, &Answer::failed(why)),+ };+ // Asked for the terminal's machine before it moved to another: not+ // done where it is now.+ if reach.machine != machine {+ let why = "the terminal beside the panel is on another machine now";+ return plugins::answer(view, id, &Answer::failed(why));+ }+ if !remote_source_is_authorized(&reach.source_key) {+ let why = format!("ThinkTerm is not connected to {}", reach.host);+ let connect = Connect {+ host: reach.host,+ machine: reach.machine,+ source_key: reach.source_key,+ };+ if let Some(shown) = self.plugin_view_numbered(view) {+ shown.connect = Some(connect);+ }+ if let Some(window) = self.window.as_ref() {+ window.invalidate();+ }+ return plugins::answer(view, id, &Answer::Failed { why, connect: true });+ }+ promise::spawn::spawn(async move {+ let answer = ask_there(reach, ask).await;+ plugins::answer(view, id, &answer);+ })+ .detach();+ }++ /// The button a view shows while its plugin waits for a connection,+ /// pressed: ThinkTerm may connect to that machine from now on, as when+ /// Files was let, and the plugin's next ask does.+ pub(crate) fn plugin_panel_connect(&mut self, extended: bool) {+ let connect = self+ .plugin_view_mut(extended)+ .and_then(|shown| shown.connect.take());+ if let Some(connect) = connect {+ authorize_remote_source(&connect.source_key);+ }+ if let Some(window) = self.window.as_ref() {+ window.invalidate();+ }+ }++ /// The view of this window's panel numbered `view`: the panel, or its+ /// extended view.+ fn plugin_view_numbered(&mut self, view: u64) -> Option<&mut Shown> {+ let panel = self.right_sidebar_plugin.as_mut()?;+ if panel.shown.view == view {+ return Some(&mut panel.shown);+ }+ panel+ .extended+ .as_mut()+ .map(|(extended, _)| extended)+ .filter(|extended| extended.view == view)+ }++ /// Finds out, on a thread of its own, whether the panes of `domain`,+ /// `domain_id`, run on this machine, and paints the panel again once it+ /// knows: on Windows, telling a WSL domain from a plain one asks WSL.+ fn look_where_domain_runs(&self, domain_id: DomainId, domain: Arc<dyn Domain>) {+ let Some(window) = self.window.clone() else {+ return;+ };+ promise::spawn::spawn(async move {+ let here = promise::spawn::spawn_into_new_thread(move || Ok(runs_here(&domain)))+ .await+ .unwrap_or(false);+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ // Gone with the panel meanwhile, and asked again with the next.+ let looked = term_window+ .plugin_panel_domains+ .iter_mut()+ .find(|(id, _)| *id == domain_id);+ if let Some((_, known)) = looked {+ *known = Some(here);+ if let Some(window) = term_window.window.as_ref() {+ window.invalidate();+ }+ }+ })));+ })+ .detach();+ }++ /// What the host said about the view `view`: the panel on show, or its+ /// extended view. The terminal is laid out again when the sidebar's+ /// width changed with it.+ pub(crate) fn plugin_panel_heard(&mut self, view: u64, news: PanelNews) {+ let news = match news {+ PanelNews::Remote { id, machine, ask } => {+ if self.plugin_view_numbered(view).is_none() {+ // A view this window let go of meanwhile.+ return plugins::answer(view, id, &Answer::failed("the panel closed"));+ }+ return self.plugin_panel_ask(view, id, machine, ask);+ }+ news => news,+ };+ let before = self.right_sidebar_width();+ let Some(panel) = self.right_sidebar_plugin.as_mut() else {+ return;+ };+ if panel.shown.view == view {+ let shown = &mut panel.shown;+ match news {+ PanelNews::Reconnected => {+ shown.player.restarted();+ shown.status = Status::Opening;+ shown.env_told = Instant::now();+ shown.env_due = false;+ panel.opening = panel.opening.wrapping_add(1);+ plugins::reopen_panel(view, &panel.plugin, shown.player.env());+ }+ news => heard(shown, &panel.plugin, news),+ }+ // Once its frames stop asking, the next that asks opens it.+ if panel.shown.player.shown() && !panel.shown.player.extend() {+ panel.dismissed = false;+ }+ } else if let Some((extended, _)) = panel+ .extended+ .as_mut()+ .filter(|(extended, _)| extended.view == view)+ {+ // One the host no longer serves stays as it is until the panel's+ // next opening, when it is opened anew.+ heard(extended, &panel.plugin, news);+ } else {+ // A view this window let go of meanwhile.+ return;+ }+ if let Some(window) = self.window.as_ref() {+ window.invalidate();+ }+ self.reflow_right_sidebar_if_width_changed(before);+ }++ /// The pointer over the panel, or its extended view: a hover tints at+ /// once, a press goes to the plugin.+ pub(crate) fn mouse_event_plugin_panel(+ &mut self,+ event: MouseEvent,+ context: &dyn WindowOps,+ extended: bool,+ ) {+ let Some(shown) = self.plugin_view_mut(extended) else {+ context.set_cursor(Some(MouseCursor::Arrow));+ return;+ };+ let x = (event.coords.x as f32 - shown.origin.0) / shown.scale;+ let y = (event.coords.y as f32 - shown.origin.1) / shown.scale;+ let mut repaint = shown.player.pointer_moved(x, y);+ let button = match event.kind {+ WMEK::Press(MousePress::Left) => Some(Button::Left),+ WMEK::Press(MousePress::Middle) => Some(Button::Middle),+ WMEK::Press(MousePress::Right) => Some(Button::Right),+ _ => None,+ };+ if let Some(button) = button {+ let count = match &self.last_mouse_click {+ Some(click) if click.streak > 1 && button == Button::Left => click.streak as u32,+ _ => 1,+ };+ let mods = Mods {+ shift: event.modifiers.contains(::window::Modifiers::SHIFT),+ ctrl: event.modifiers.contains(::window::Modifiers::CTRL),+ alt: event.modifiers.contains(::window::Modifiers::ALT),+ cmd: event.modifiers.contains(::window::Modifiers::SUPER),+ };+ let shown = self.plugin_view_mut(extended).expect("found above");+ if let Some(input) = shown.player.click(x, y, button, count, mods) {+ let input = Raw::new(&input);+ plugins::tell_panel(shown.view, PanelRequest::Input { input });+ repaint = true;+ }+ }+ let cursor = self+ .plugin_view_mut(extended)+ .and_then(|shown| shown.player.cursor());+ context.set_cursor(Some(match cursor {+ Some(Cursor::Pointer) => MouseCursor::Hand,+ Some(Cursor::Arrow) | None => MouseCursor::Arrow,+ }));+ if repaint {+ context.invalidate();+ }+ }++ /// The wheel turned `dx` pixels across and `dy` down over the panel or+ /// its extended view, whichever the pointer is over. True when+ /// something in it scrolled.+ pub(crate) fn plugin_panel_wheel(&mut self, event: &MouseEvent, dx: f32, dy: f32) -> bool {+ let Some(panel) = self.right_sidebar_plugin.as_mut() else {+ return false;+ };+ let (px, py) = (event.coords.x as f32, event.coords.y as f32);+ let extended = panel+ .extended+ .as_mut()+ .map(|(extended, _)| extended)+ .filter(|extended| extended.under(px, py).is_some());+ let shown = extended.unwrap_or(&mut panel.shown);+ let x = (px - shown.origin.0) / shown.scale;+ let y = (py - shown.origin.1) / shown.scale;+ let moved = shown.player.wheel(x, y, dx / shown.scale, dy / shown.scale);+ if moved {+ send_wanted(shown);+ }+ moved+ }++ /// The pointer left the panel, or its extended view.+ pub(crate) fn plugin_panel_pointer_left(&mut self, extended: bool) -> bool {+ self.plugin_view_mut(extended)+ .is_some_and(|shown| shown.player.pointer_left())+ }++ /// The panel on show, or its extended view.+ fn plugin_view_mut(&mut self, extended: bool) -> Option<&mut Shown> {+ let panel = self.right_sidebar_plugin.as_mut()?;+ if extended {+ panel.extended.as_mut().map(|(extended, _)| extended)+ } else {+ Some(&mut panel.shown)+ }+ }++ fn plugin_panel_fonts(&self) -> anyhow::Result<PanelFonts> {+ let settings = crate::native_settings::load_shared();+ let body = crate::native_settings::right_sidebar_font_size(&settings);+ let sizes = [(body - 1.5).max(8.0), body, body + 2.0];+ let with = |font: Rc<LoadedFont>| {+ let metrics = RenderMetrics::with_font_metrics(&font.metrics());+ (font, metrics)+ };+ let plain =+ |size: f64| -> anyhow::Result<_> { Ok(with(self.fonts.title_font_with_size(size)?)) };+ let bold = |size: f64| -> anyhow::Result<_> {+ Ok(with(self.fonts.title_font_with_size_and_weight(size, 700)?))+ };+ let mono = self+ .fonts+ .resolve_font(&self.config.font)+ .context("plugin panel monospaced font")?;+ Ok(PanelFonts {+ small: plain(sizes[0])?,+ body: plain(sizes[1])?,+ title: plain(sizes[2])?,+ small_bold: bold(sizes[0])?,+ body_bold: bold(sizes[1])?,+ title_bold: bold(sizes[2])?,+ mono: with(mono),+ sizes,+ mono_size: self.config.font_size,+ })+ }++ /// The player's items, each laid on the frame cut to its region:+ /// recorded anew when the view changed, laid again as they were when it+ /// did not.+ fn paint_plugin_panel_items(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ shown: &mut Shown,+ fonts: &PanelFonts,+ chrome: &UiPalette,+ ) -> anyhow::Result<()> {+ let key = PaintKey {+ revision: shown.player.revision(),+ origin: shown.origin,+ scale: shown.scale,+ window: (self.dimensions.pixel_width, self.dimensions.pixel_height),+ shapes: self.shape_generation,+ chrome: *chrome,+ sizes: fonts.sizes,+ mono_size: fonts.mono_size,+ };+ if shown+ .painted+ .as_ref()+ .is_none_or(|painted| painted.key != key)+ {+ // Let go of the last before the next is recorded.+ shown.painted = None;+ let regions = self.record_plugin_panel(shown, fonts, chrome)?;+ shown.painted = Some(Painted { key, regions });+ }+ let painted = shown.painted.as_ref().expect("recorded above");+ for (clip, heap) in &painted.regions {+ self.lay_plugin_panel_heap(layers, heap, shown, *clip)?;+ }+ Ok(())+ }++ fn record_plugin_panel(+ &self,+ shown: &Shown,+ fonts: &PanelFonts,+ chrome: &UiPalette,+ ) -> anyhow::Result<Vec<(Bounds, HeapQuadAllocator)>> {+ let mut regions: Vec<(Bounds, HeapQuadAllocator)> = Vec::new();+ let mut budget = QUAD_LIMIT;+ for draw in &shown.player.draw() {+ if regions.last().is_none_or(|(clip, _)| *clip != draw.clip) {+ regions.push((draw.clip, HeapQuadAllocator::default()));+ }+ let (_, heap) = regions.last_mut().expect("pushed above");+ let mut recorded = TripleLayerQuadAllocator::Heap(heap);+ self.paint_plugin_panel_draw(&mut recorded, shown, draw, fonts, chrome, &mut budget)?;+ }+ Ok(regions)+ }++ fn lay_plugin_panel_heap(+ &self,+ layers: &mut TripleLayerQuadAllocator,+ heap: &HeapQuadAllocator,+ shown: &Shown,+ clip: Bounds,+ ) -> anyhow::Result<()> {+ let (x, y, scale) = (shown.origin.0, shown.origin.1, shown.scale);+ let clip = QuadClipRect::from_top_left_pixels(+ x + clip.left * scale,+ y + clip.top * scale,+ x + clip.right * scale,+ y + clip.bottom * scale,+ &self.dimensions,+ );+ heap.apply_to_clipped(layers, clip, 1.0)+ }++ fn paint_plugin_panel_draw(+ &self,+ layers: &mut TripleLayerQuadAllocator,+ shown: &Shown,+ draw: &Draw<'_>,+ fonts: &PanelFonts,+ chrome: &UiPalette,+ budget: &mut usize,+ ) -> anyhow::Result<()> {+ let scale = shown.scale;+ // What of the window the draw shows in, across.+ let across = (+ shown.origin.0 + draw.clip.left * scale,+ shown.origin.0 + draw.clip.right * scale,+ );+ let spent = match draw.what {+ Drawn::Rect(_) | Drawn::Hover(_) | Drawn::Thumb(_) => spend(budget, 1),+ Drawn::Text(_) | Drawn::Line(_) | Drawn::Area(_) => true,+ };+ if !spent {+ return Ok(());+ }+ // A box in the item's units, in window pixels.+ let place = |x: f32, y: f32, w: f32, h: f32| -> RectF {+ euclid::rect(+ shown.origin.0 + (x + draw.dx) * scale,+ shown.origin.1 + (y + draw.dy) * scale,+ w.max(0.0) * scale,+ h.max(0.0) * scale,+ )+ };+ match draw.what {+ Drawn::Rect(Rect {+ x,+ y,+ w,+ h,+ fill,+ radius,+ border,+ }) => {+ let fill = fill.map(|fill| color(chrome, fill));+ let border = border.map(|border| color(chrome, border));+ self.paint_panel_rect(layers, place(*x, *y, *w, *h), fill, border, radius * scale)+ }+ Drawn::Hover(hit) => {+ let tint = color(chrome, hit.hover.unwrap_or_default());+ let area = place(hit.x, hit.y, hit.w, hit.h);+ self.paint_panel_rect(layers, area, Some(tint), None, hit.radius * scale)+ }+ Drawn::Text(text) => {+ let area = place(text.x, text.y, text.w, text.h);+ let text_color = color(chrome, text.color);+ self.paint_panel_text(layers, text, area, fonts, text_color, across, budget)+ }+ Drawn::Line(Line {+ points,+ width,+ color: line_color,+ }) => {+ let at = |x: f32, y: f32| {+ (+ shown.origin.0 + (x + draw.dx) * scale,+ shown.origin.1 + (y + draw.dy) * scale,+ )+ };+ let points: Vec<(f32, f32)> = points+ .as_chunks::<2>()+ .0+ .iter()+ .map(|[x, y]| at(*x, *y))+ .collect();+ let line_color = color(chrome, *line_color);+ self.paint_panel_line(layers, &points, width * scale, line_color, across, budget)+ }+ Drawn::Area(Area {+ points,+ base,+ color: fill,+ fade,+ }) => {+ let at = |x: f32, y: f32| {+ (+ shown.origin.0 + (x + draw.dx) * scale,+ shown.origin.1 + (y + draw.dy) * scale,+ )+ };+ let points: Vec<(f32, f32)> = points+ .as_chunks::<2>()+ .0+ .iter()+ .map(|[x, y]| at(*x, *y))+ .collect();+ let base = shown.origin.1 + (base + draw.dy) * scale;+ let fill = color(chrome, *fill);+ self.paint_panel_area(layers, &points, base, fill, *fade, across, budget)+ }+ Drawn::Thumb(thumb) => {+ let area: RectF = euclid::rect(+ shown.origin.0 + thumb.left * scale,+ shown.origin.1 + thumb.top * scale,+ thumb.width() * scale,+ thumb.height() * scale,+ );+ // A thumb across is as round as one down.+ let radius = area.width().min(area.height()) / 2.0;+ self.paint_panel_rect(layers, area, Some(chrome.scrollbar_thumb), None, radius)+ }+ }+ }++ fn paint_panel_rect(+ &self,+ layers: &mut TripleLayerQuadAllocator,+ area: RectF,+ fill: Option<LinearRgba>,+ border: Option<LinearRgba>,+ radius: f32,+ ) -> anyhow::Result<()> {+ if area.width() <= 0.0 || area.height() <= 0.0 {+ return Ok(());+ }+ let stroke = self.ui_f32(1.0).max(1.0);+ match (fill, border) {+ (Some(fill), Some(border)) => self.fill_rounded_rectangle_with_border(+ layers, LAYER, area, fill, border, radius, stroke,+ ),+ (Some(fill), None) => self.fill_rounded_rectangle(layers, LAYER, area, fill, radius),+ (None, Some(border)) => self.stroke_panel_rect(layers, area, border, radius, stroke),+ (None, None) => Ok(()),+ }+ }++ /// A rounded outline with nothing inside: arcs at the corners, strips+ /// between them.+ fn stroke_panel_rect(+ &self,+ layers: &mut TripleLayerQuadAllocator,+ area: RectF,+ border: LinearRgba,+ radius: f32,+ stroke: f32,+ ) -> anyhow::Result<()> {+ let radius = radius+ .min(area.width() / 2.0)+ .min(area.height() / 2.0)+ .round()+ .max(0.0);+ if radius >= 1.0 {+ let size = euclid::size2(radius, radius);+ for (x, y, polys) in [+ (area.min_x(), area.min_y(), TOP_LEFT_ROUNDED_CORNER_OUTLINE),+ (+ area.max_x() - radius,+ area.min_y(),+ TOP_RIGHT_ROUNDED_CORNER_OUTLINE,+ ),+ (+ area.min_x(),+ area.max_y() - radius,+ BOTTOM_LEFT_ROUNDED_CORNER_OUTLINE,+ ),+ (+ area.max_x() - radius,+ area.max_y() - radius,+ BOTTOM_RIGHT_ROUNDED_CORNER_OUTLINE,+ ),+ ] {+ self.poly_quad(layers, LAYER, euclid::point2(x, y), polys, 0, size, border)?+ .set_grayscale();+ }+ }+ let edges: [RectF; 4] = [+ euclid::rect(+ area.min_x() + radius,+ area.min_y(),+ area.width() - radius * 2.0,+ stroke,+ ),+ euclid::rect(+ area.min_x() + radius,+ area.max_y() - stroke,+ area.width() - radius * 2.0,+ stroke,+ ),+ euclid::rect(+ area.min_x(),+ area.min_y() + radius,+ stroke,+ area.height() - radius * 2.0,+ ),+ euclid::rect(+ area.max_x() - stroke,+ area.min_y() + radius,+ stroke,+ area.height() - radius * 2.0,+ ),+ ];+ for edge in edges {+ if edge.width() > 0.0 && edge.height() > 0.0 {+ self.filled_rectangle(layers, LAYER, edge, border)?;+ }+ }+ Ok(())+ }++ /// One line of text in its box: centred in its height, placed across+ /// it as asked, and cut to it -- with an ellipsis in the interface+ /// font, at the edge in the monospaced one.+ /// Only the glyphs within `across`, the draw's left and right edges, are+ /// laid: a line far wider than a list scrolled sideways costs what shows.+ #[allow(clippy::too_many_arguments)]+ fn paint_panel_text(+ &self,+ layers: &mut TripleLayerQuadAllocator,+ text: &Text,+ area: RectF,+ fonts: &PanelFonts,+ color: LinearRgba,+ across: (f32, f32),+ budget: &mut usize,+ ) -> anyhow::Result<()> {+ let (clip_left, clip_right) = (area.min_x().max(across.0), area.max_x().min(across.1));+ if text.text.is_empty() || area.width() < 1.0 || clip_right <= clip_left {+ return Ok(());+ }+ let (font, metrics) = fonts.of(text);+ let top = area.min_y() + (area.height() - metrics.cell_size.height as f32) / 2.0;+ let shown = match text.font {+ Font::Ui => self.ellipsize_ui_text(font, &text.text, area.width() as usize)?,+ Font::Mono => std::borrow::Cow::Borrowed(text.text.as_str()),+ };+ if shown.is_empty() {+ return Ok(());+ }+ let (shaped, _) = self.cached_ui_shape(font, metrics, &shown)?;+ let width: f32 = shaped+ .iter()+ .map(|info| info.glyph.x_advance.get() as f32)+ .sum();+ let left = match text.align {+ Align::Left => area.min_x(),+ Align::Center => area.min_x() + (area.width() - width) / 2.0,+ Align::Right => area.max_x() - width,+ }+ .max(area.min_x());+ // The glyphs laid are those that show.+ let mut x = left;+ let showing = shaped+ .iter()+ .filter(|info| {+ let advance = info.glyph.x_advance.get() as f32;+ let shows = x < clip_right && x + advance > clip_left;+ x += advance;+ shows+ })+ .count();+ if !spend(budget, showing) {+ return Ok(());+ }+ match text.font {+ Font::Ui => self.paint_cached_ui_shape_clipped(+ layers,+ metrics,+ &shaped,+ left,+ top,+ clip_left,+ clip_right,+ |_| color,+ ),+ Font::Mono => self.paint_cached_ui_shape_pixel_clipped(+ layers,+ metrics,+ &shaped,+ left,+ top,+ clip_left,+ clip_right,+ |_| color,+ ),+ }+ .map(drop)+ }++ /// A line through `points`, in window pixels, as a column a pixel wide+ /// for each pixel it runs across, tall enough to reach the next: only+ /// those within `across`, the draw's left and right edges.+ #[allow(clippy::too_many_arguments)]+ fn paint_panel_line(+ &self,+ layers: &mut TripleLayerQuadAllocator,+ points: &[(f32, f32)],+ width: f32,+ color: LinearRgba,+ across: (f32, f32),+ budget: &mut usize,+ ) -> anyhow::Result<()> {+ let width = width.max(1.0);+ for pair in points.windows(2) {+ // Walked left to right.+ let ((x0, y0), (x1, y1)) = if pair[0].0 <= pair[1].0 {+ (pair[0], pair[1])+ } else {+ (pair[1], pair[0])+ };+ let run = x1 - x0;+ // A column is widened where the line is steep: one just beyond+ // an edge shows.+ let (from, to) = (x0.max(across.0 - width), x1.min(across.1 + width));+ if from > to {+ continue;+ }+ let y_at = |x: f32| y0 + (y1 - y0) * (x - x0) / run;+ let steps = (to - from).ceil().max(1.0) as usize;+ for step in 0..steps {+ if !spend(budget, 1) {+ return Ok(());+ }+ let xa = from + (to - from) * step as f32 / steps as f32;+ let xb = from + (to - from) * (step + 1) as f32 / steps as f32;+ // Upright, it is one column from end to end.+ let (ya, yb) = if run > 0.0 {+ (y_at(xa), y_at(xb))+ } else {+ (y0, y1)+ };+ let wide = (xb - xa).max(1.0);+ let rise = (yb - ya).abs();+ // Steep, it is widened as well, or it would thin to a pixel.+ let (left, wide) = if rise > wide {+ (xa - (width - 1.0) / 2.0, wide + width - 1.0)+ } else {+ (xa, wide)+ };+ let top = ya.min(yb) - width / 2.0;+ let column: RectF = euclid::rect(left, top, wide, rise + width);+ self.filled_rectangle(layers, LAYER, column, color)?;+ }+ }+ Ok(())+ }++ /// What lies between a line through `points` and the level `base`, as+ /// columns a pixel wide, only those within `across`; with `fade`, clear+ /// at `base` and as strong as `color` at the area's highest point.+ #[allow(clippy::too_many_arguments)]+ fn paint_panel_area(+ &self,+ layers: &mut TripleLayerQuadAllocator,+ points: &[(f32, f32)],+ base: f32,+ color: LinearRgba,+ fade: bool,+ across: (f32, f32),+ budget: &mut usize,+ ) -> anyhow::Result<()> {+ let highest = points.iter().map(|(_, y)| *y).fold(base, f32::min);+ let depth = (base - highest).max(1.0);+ for pair in points.windows(2) {+ let ((x0, y0), (x1, y1)) = (pair[0], pair[1]);+ let run = x1 - x0;+ let (from, to) = (x0.max(across.0), x1.min(across.1));+ if run <= 0.0 || from >= to {+ continue;+ }+ let steps = (to - from).ceil().max(1.0) as usize;+ for step in 0..steps {+ let left = from + (to - from) * step as f32 / steps as f32;+ let right = from + (to - from) * (step + 1) as f32 / steps as f32;+ let y = y0 + (y1 - y0) * ((left + right) / 2.0 - x0) / run;+ let (top, bottom) = (y.min(base), y.max(base));+ if bottom - top < 0.5 {+ continue;+ }+ if !spend(budget, 1) {+ return Ok(());+ }+ let column: RectF = euclid::rect(left, top, (right - left).max(1.0), bottom - top);+ let mut quad = self.filled_rectangle(layers, LAYER, column, color)?;+ if fade {+ let strength = ((base - top) / depth).clamp(0.0, 1.0);+ let clear = color.mul_alpha(0.0);+ if y <= base {+ quad.set_vertical_gradient(color.mul_alpha(strength), clear);+ } else {+ quad.set_vertical_gradient(clear, color.mul_alpha(strength));+ }+ }+ }+ }+ Ok(())+ }+}++/// Takes `cost` quads from `budget`; none, and false, when it has not that+/// many left.+fn spend(budget: &mut usize, cost: usize) -> bool {+ match budget.checked_sub(cost) {+ Some(left) => {+ *budget = left;+ true+ }+ None => false,+ }+}++/// Whether `domain` runs its programs on this machine, so the directory of+/// one of its panes is a directory here: a plain local terminal, or one the+/// local session server keeps -- not WSL, a serial port or a remote host.+fn runs_here(domain: &Arc<dyn Domain>) -> bool {+ domain+ .downcast_ref::<mux::domain::LocalDomain>()+ .is_some_and(mux::domain::LocalDomain::is_plain_local)+ || domain+ .downcast_ref::<wezterm_client::domain::ClientDomain>()+ .is_some_and(|client| client.is_local_session_host())+}++/// The path a pane's directory `url` names on the other machine it runs on.+fn remote_path(url: &Url) -> Option<String> {+ if url.scheme() != "file" {+ return None;+ }+ let path = percent_encoding::percent_decode_str(url.path())+ .decode_utf8()+ .ok()?;+ (!path.is_empty()).then(|| path.into_owned())+}++/// The path a pane's directory `url` names on this machine.+fn local_path(url: &Url) -> Option<String> {+ if url.scheme() != "file" {+ return None;+ }+ let path = percent_encoding::percent_decode_str(url.path())+ .decode_utf8()+ .ok()?;+ // `/C:/Users/...` on Windows.+ let path = match path.strip_prefix('/') {+ Some(rest) if cfg!(windows) && rest.as_bytes().get(1) == Some(&b':') => rest,+ _ => &path,+ };+ (!path.is_empty()).then(|| path.to_string())+}++/// What the plugin is told of a panel this big, set in `fonts`.+fn panel_env(fonts: &PanelFonts, chrome: &UiPalette, width: f32, height: f32, scale: f32) -> Env {+ let text = |(_, metrics): &(Rc<LoadedFont>, RenderMetrics), size: f64| TextMetrics {+ size: size as f32,+ line: metrics.cell_size.height as f32 / scale,+ };+ let (_, mono) = &fonts.mono;+ Env {+ width: width / scale,+ height: height / scale,+ scale,+ dark: chrome.is_dark(),+ small: text(&fonts.small, fonts.sizes[0]),+ body: text(&fonts.body, fonts.sizes[1]),+ title: text(&fonts.title, fonts.sizes[2]),+ mono: MonoMetrics {+ size: fonts.mono_size as f32,+ line: mono.cell_size.height as f32 / scale,+ advance: mono.cell_size.width as f32 / scale,+ },+ locale: crate::i18n::current_locale().to_string(),+ cwd: None,+ remote: None,+ can_extend: false,+ close: None,+ }+}++/// Sends the plugin what the view's lists need next, once it is told the+/// size they are drawn for.+fn send_wanted(shown: &mut Shown) {+ if shown.env_due {+ return;+ }+ for wanted in shown.player.wanted() {+ let wanted = Raw::new(&wanted);+ plugins::tell_panel(shown.view, PanelRequest::Rows { wanted });+ }+}++/// Tells the plugin a size, fonts or theme of `shown` that changed, the+/// last of those within [`ENV_EVERY`]: the time to come back when it is not+/// time yet.+fn tell_env(shown: &mut Shown, env: Env, now: Instant) -> Option<Instant> {+ shown.env_due |= shown.player.set_env(env);+ if !shown.env_due {+ return None;+ }+ let due = shown.env_told + ENV_EVERY;+ if now < due {+ return Some(due);+ }+ shown.env_told = now;+ shown.env_due = false;+ let env = Raw::new(shown.player.env());+ plugins::tell_panel(shown.view, PanelRequest::Env { env });+ send_wanted(shown);+ None+}++/// What the host said about `shown`, a view of plugin `plugin`. One the+/// host closed but may serve again shows what it last had meanwhile: a+/// panel is opened again in a while, an extended view on its panel's next+/// opening.+fn heard(shown: &mut Shown, plugin: &str, news: PanelNews) {+ match news {+ PanelNews::Frame(frame) => {+ shown.player.frame(frame);+ shown.status = Status::Open;+ plugins::tell_panel(shown.view, PanelRequest::Shown);+ send_wanted(shown);+ }+ PanelNews::Rows(rows) => {+ shown.player.rows(rows);+ send_wanted(shown);+ }+ PanelNews::Closed { reason, again } => {+ shown.status = if again {+ Status::Again(Instant::now() + REOPEN_AFTER)+ } else {+ log::info!("plugin panel {plugin}: {reason}");+ Status::Stopped(reason)+ };+ }+ PanelNews::Unreachable(why) => {+ shown.status = Status::Lost(why);+ }+ // An extended view's: it goes with its panel, which is opened again.+ PanelNews::Reconnected => {}+ // Answered by the window, before it gets here.+ PanelNews::Remote { .. } => {}+ }+}++/// Does `ask` on the machine `reach` names, and says what came of it.+async fn ask_there(reach: Reach, ask: Ask) -> Answer {+ let lease = match remote_connection_manager()+ .acquire(reach.connection_key, reach.config, true)+ .await+ {+ Ok(lease) => lease,+ Err(RemoteAcquireError::Failed(why)) => return Answer::failed(why),+ Err(RemoteAcquireError::NotConnected) => {+ return Answer::failed(format!("ThinkTerm is not connected to {}", reach.host))+ }+ };+ let backend = lease.backend();+ let within = |limit: u64| usize::try_from(limit).unwrap_or(usize::MAX).min(ASK_BYTES);+ match ask {+ Ask::Run { args, cwd, limit } => {+ let line = run_command_line(&cwd, &args);+ match backend.run(line, within(limit), ASK_RUN_WAIT).await {+ Ok(ran) => Answer::Ran {+ status: ran.status.and_then(|status| i32::try_from(status).ok()),+ out: Bytes(ran.out),+ cut: ran.cut,+ },+ Err(why) => Answer::failed(why),+ }+ }+ Ask::Read { path, limit } => {+ let path = match RemotePath::from_server_absolute(&path) {+ Ok(path) => path,+ Err(why) => return Answer::failed(why),+ };+ match backend.read_file(path, within(limit)).await {+ Ok(read) => Answer::Read {+ bytes: Bytes(read.bytes),+ cut: read.truncated,+ },+ Err(why) => Answer::failed(why),+ }+ }+ Ask::Stat { path } => match backend.stat(path).await {+ Ok(found) => Answer::Stat {+ entry: found.map(|stat| Entry {+ kind: match stat.kind {+ RemoteFileKind::File => EntryKind::File,+ RemoteFileKind::Directory => EntryKind::Dir,+ RemoteFileKind::Symlink => EntryKind::Link,+ RemoteFileKind::Other => EntryKind::Other,+ },+ len: stat.size,+ modified: stat.modified,+ target: stat.target,+ }),+ },+ Err(why) => Answer::failed(why),+ },+ }+}++/// The word a plugin is told the connection `connection_key` names its+/// machine by. The key holds a digest of the password, so it is hashed+/// again under a key of this process's own: nothing of it leaves, and the+/// word is the same for every window.+fn machine_word(connection_key: &str) -> String {+ static KEY: OnceLock<RandomState> = OnceLock::new();+ format!(+ "{:016x}",+ KEY.get_or_init(RandomState::new).hash_one(connection_key)+ )+}++/// The machine an SSH address names, without the user or the port.+fn host_name(address: &str) -> String {+ let address = address.rsplit_once('@').map_or(address, |(_, host)| host);+ if let Some((host, _)) = address+ .strip_prefix('[')+ .and_then(|rest| rest.split_once(']'))+ {+ return host.to_string();+ }+ match address.rsplit_once(':') {+ Some((host, port)) if !host.contains(':') && port.bytes().all(|b| b.is_ascii_digit()) => {+ host.to_string()+ }+ _ => address.to_string(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_directory_is_its_path_here() {+ let url = |text: &str| Url::parse(text).unwrap();+ assert_eq!(+ local_path(&url("file://devbox/home/user/my%20project")).as_deref(),+ Some("/home/user/my project")+ );+ assert_eq!(local_path(&url("https://example.com/a")), None);+ assert_eq!(+ local_path(&url("file://devbox")).as_deref(),+ Some("/"),+ "the root"+ );+ }++ #[test]+ fn a_remote_directory_is_its_path_there_and_a_host_its_name() {+ let url = Url::parse("file://server-a/C:/work/my%20app").unwrap();+ assert_eq!(+ remote_path(&url).as_deref(),+ Some("/C:/work/my app"),+ "as it is there"+ );+ assert_eq!(host_name("devbox"), "devbox");+ assert_eq!(host_name("user@devbox:2222"), "devbox");+ assert_eq!(host_name("[fe80::1]:22"), "fe80::1");+ assert_eq!(host_name("fe80::1"), "fe80::1");+ }++ #[test]+ fn a_unit_is_a_point() {+ let retina = if cfg!(target_os = "macos") { 144 } else { 192 };+ assert_eq!(panel_scale(retina), 2.0);+ assert_eq!(panel_scale(0), panel_scale(1));+ }+}diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rsindex 295a8db0..c516fdec 100644--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs@@ -35,7 +35,7 @@ use crate::termwindow::ui::tokens::{WINDOW_TAB_LEADING_ACTION_BUTTON_SIZE, WINDOW_TAB_LEADING_ACTION_GAP,};use crate::termwindow::{- NoteEditorCommand, PendingLocalCopy, PendingRemoteConfirm, RightSidebarFileCharBag,+ NoteEditorCommand, PanelId, PendingLocalCopy, PendingRemoteConfirm, RightSidebarFileCharBag,RightSidebarFileDirCache, RightSidebarFileDirEntry, RightSidebarFileField,RightSidebarFileIndex, RightSidebarFileIndexEntry, RightSidebarFileIndexStatus,RightSidebarFilePreviewImage, RightSidebarFilePreviewLine, RightSidebarFilePreviewSelection,@@ -86,6 +86,11 @@ const RIGHT_SIDEBAR_CLOSE_ICON_SIZE: usize = 27;const RIGHT_SIDEBAR_CLOSE_BUTTON_X_ADJUST: usize = 8;const RIGHT_SIDEBAR_CLOSE_BUTTON_Y_ADJUST: usize = 16;const RIGHT_SIDEBAR_MODE_HEIGHT: usize = 72;+/// The most panels the selector names the active one of: past this its+/// label has no room, and every panel is its icon alone, the active one+/// told by its pill. The browser's selector does the same+/// (thinkterm-web/src/agents.rs).+const RIGHT_SIDEBAR_LABELED_MODES: usize = 5;const RIGHT_SIDEBAR_EMPTY_HEIGHT: usize = 88;#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -330,6 +335,11 @@ const FILE_PREVIEW_PANE_MIN_WIDTH: usize = 360;const FILE_PREVIEW_PANE_DEFAULT_WIDTH: usize = 560;const NOTE_PANE_MIN_WIDTH: usize = FILE_PREVIEW_PANE_MIN_WIDTH;const NOTE_PANE_DEFAULT_WIDTH: usize = FILE_PREVIEW_PANE_DEFAULT_WIDTH;+/// A plugin's extended view: 360 and 560 points at the least and to start+/// with, as in a browser. Twice the file preview's: it is there for what a+/// sidebar has no room for.+const PLUGIN_EXTENDED_MIN_WIDTH: usize = FILE_PREVIEW_PANE_MIN_WIDTH * 2;+const PLUGIN_EXTENDED_DEFAULT_WIDTH: usize = FILE_PREVIEW_PANE_DEFAULT_WIDTH * 2;const FILE_PREVIEW_SLICE_CACHE_CAPACITY: usize = 256;// Lines up to this many columns are shaped whole (once, cached) so horizontal// scrolling is pure translation of the cached glyph run instead of re-shaping a@@ -1346,14 +1356,21 @@ impl RightSidebarMode {const ALL: [Self; 4] = [Self::Chat, Self::Tasks, Self::Snippets, Self::Agents];/// The panels the selector offers, in order. Reading the toggles here- /// rather than hard-coding the list is what lets Settings hide a panel --- /// and is the seam a future plugin would extend.+ /// rather than hard-coding the list is what lets Settings hide a panel;+ /// the plugins' panels follow ThinkTerm's own, as the plugin host last+ /// listed them.pub(crate) fn enabled_panels() -> Vec<Self> {let toggles = crate::native_settings::right_sidebar_panel_toggles();+ let plugins = crate::native_settings::plugin_panels();Self::ALL.iter().copied().filter(|panel| panel.enabled_with(&toggles))+ .chain(+ plugins+ .iter()+ .filter_map(|panel| Some(Self::Plugin(PanelId::new(&panel.id)?))),+ ).collect()}@@ -1363,7 +1380,7 @@ impl RightSidebarMode {/// stops at the first panel that is on.pub(crate) fn any_panel_enabled() -> bool {let toggles = crate::native_settings::right_sidebar_panel_toggles();- Self::ALL.iter().any(|panel| panel.enabled_with(&toggles))+ toggles.plugins || Self::ALL.iter().any(|panel| panel.enabled_with(&toggles))}pub(crate) fn panel_enabled(self) -> bool {@@ -1381,15 +1398,29 @@ impl RightSidebarMode {// last, where the short-circuit in `any_panel_enabled` reaches it// only when the other three are off.Self::Agents => crate::agent_status::enabled(),+ Self::Plugin(_) => toggles.plugins && self.plugin_panel().is_some(),}}+ /// The plugin panel this mode shows, as last heard.+ pub(crate) fn plugin_panel(self) -> Option<crate::native_settings::NativePluginPanel> {+ let Self::Plugin(id) = self else {+ return None;+ };+ crate::native_settings::plugin_panels()+ .into_iter()+ .find(|panel| panel.id == id.as_str())+ }+fn icon(self) -> SvgIcon {match self {Self::Chat => SvgIcon::FolderTree,Self::Tasks => SvgIcon::NotebookTabs,Self::Snippets => SvgIcon::CodeXml,Self::Agents => SvgIcon::Bot,+ Self::Plugin(_) => self+ .plugin_panel()+ .map_or(SvgIcon::Puzzle, |panel| SvgIcon::for_panel(&panel.icon)),}}@@ -1399,6 +1430,10 @@ impl RightSidebarMode {Self::Tasks => crate::i18n::tr("right-mode-notes"),Self::Snippets => crate::i18n::tr("right-mode-snippets"),Self::Agents => crate::i18n::tr("right-mode-agents"),+ Self::Plugin(_) => self+ .plugin_panel()+ .map(|panel| panel.name)+ .unwrap_or_default(),}}}@@ -1430,6 +1465,13 @@ pub fn right_sidebar_note_pane_width_for_dpi(dpi: usize) -> usize {.max(min_width)}+/// How wide the user made plugin `plugin`'s extended view, in window+/// pixels at `dpi`; 0 when they never did.+pub fn right_sidebar_plugin_extended_width_for(plugin: &str, dpi: usize) -> usize {+ crate::native_settings::plugin_extended_width(plugin)+ .map_or(0, |width| scale_ui_usize(width, dpi))+}+fn file_preview_close_requires_reflow(preview_was_visible: bool,previous_width: usize,@@ -1543,6 +1585,49 @@ impl crate::TermWindow {Some(configured_width.clamp(self.ui_px(NOTE_PANE_MIN_WIDTH), max_pane_width))}+ /// Whether the sidebar shows a plugin's panel that asks for its+ /// extended view. Only the panel of the plugin its mode names: one left+ /// open from the mode before, until the next paint lets it go, would+ /// keep its room for it, and the switch would not lay the terminal out+ /// again.+ fn right_sidebar_plugin_extended_active(&self) -> bool {+ let RightSidebarMode::Plugin(id) = self.right_sidebar_mode else {+ return false;+ };+ self.right_sidebar_presented()+ && self+ .right_sidebar_plugin+ .as_ref()+ .is_some_and(|panel| panel.plugin() == id.as_str() && panel.wants_extended())+ }++ /// The most a plugin's extended view can have beside the sidebar; none+ /// when that is less than it takes.+ fn right_sidebar_plugin_extended_room(&self) -> Option<usize> {+ let max = self+ .right_sidebar_pane_total_max_width()+ .saturating_sub(self.right_sidebar_tree_width());+ (max >= self.ui_px(PLUGIN_EXTENDED_MIN_WIDTH)).then_some(max)+ }++ /// Whether a plugin's panel would get its extended view were it to ask+ /// for one: there is room for it beside the sidebar.+ pub(crate) fn right_sidebar_plugin_can_extend(&self) -> bool {+ self.right_sidebar_plugin_extended_room().is_some()+ }++ fn right_sidebar_plugin_extended_width(&self) -> Option<usize> {+ if !self.right_sidebar_plugin_extended_active() {+ return None;+ }+ let max = self.right_sidebar_plugin_extended_room()?;+ let chosen = match self.right_sidebar_plugin.as_ref()?.extended_width {+ 0 => self.ui_px(PLUGIN_EXTENDED_DEFAULT_WIDTH),+ width => width,+ };+ Some(chosen.clamp(self.ui_px(PLUGIN_EXTENDED_MIN_WIDTH), max))+ }+/// Whether the sidebar has anything to show. Turning off every panel in/// Settings hides it outright rather than leaving an empty selector: the/// terminal reclaims the space through the same zero-width path collapse@@ -1567,11 +1652,13 @@ impl crate::TermWindow {if !self.right_sidebar_has_panels() {return 0;}- // The file preview pane and the Note pane are mutually exclusive- // (different sidebar modes); at most one is non-zero.+ // The file preview pane, the Note pane and a plugin's extended view+ // are mutually exclusive (different sidebar modes); at most one is+ // non-zero.let pane_width = self.right_sidebar_file_preview_width().or_else(|| self.right_sidebar_note_pane_width())+ .or_else(|| self.right_sidebar_plugin_extended_width()).unwrap_or(0);self.right_sidebar_tree_width().saturating_add(pane_width)@@ -1714,6 +1801,7 @@ impl crate::TermWindow {if self.right_sidebar_mode == RightSidebarMode::Tasks {self.clear_right_sidebar_text_focus();}+ self.close_plugin_panel();self.schedule_right_sidebar_file_memory_release();self.release_right_sidebar_remote_files_if_hidden();self.schedule_right_sidebar_note_memory_release();@@ -2300,7 +2388,7 @@ impl crate::TermWindow {RightSidebarMode::Chat => self.right_sidebar_file_focus.is_some(),RightSidebarMode::Snippets => self.right_sidebar_snippet_focus.is_some(),RightSidebarMode::Tasks => self.right_sidebar_note.view.focused,- RightSidebarMode::Agents => false,+ RightSidebarMode::Agents | RightSidebarMode::Plugin(_) => false,}}@@ -5102,7 +5190,7 @@ impl crate::TermWindow {self.right_sidebar_snippet_scroll_offset = 0.0;}}- RightSidebarMode::Tasks | RightSidebarMode::Agents => {}+ RightSidebarMode::Tasks | RightSidebarMode::Agents | RightSidebarMode::Plugin(_) => {}}}@@ -6398,7 +6486,9 @@ impl crate::TermWindow {Some(RightSidebarSnippetField::Body) => Some(&self.right_sidebar_snippet_body),None => None,},- RightSidebarMode::Tasks | RightSidebarMode::Agents => None,+ RightSidebarMode::Tasks | RightSidebarMode::Agents | RightSidebarMode::Plugin(_) => {+ None+ }}}@@ -6418,7 +6508,9 @@ impl crate::TermWindow {Some(RightSidebarSnippetField::Body) => Some(&mut self.right_sidebar_snippet_body),None => None,},- RightSidebarMode::Tasks | RightSidebarMode::Agents => None,+ RightSidebarMode::Tasks | RightSidebarMode::Agents | RightSidebarMode::Plugin(_) => {+ None+ }}}@@ -6580,6 +6672,98 @@ impl crate::TermWindow {old_pane != self.right_sidebar_note_pane_width || old_tree != self.right_sidebar_width}+ /// Where a plugin's extended view goes: the left of the sidebar, as the+ /// Note pane does.+ pub(crate) fn right_sidebar_plugin_extended_rect(&self) -> Option<RightSidebarRect> {+ let sidebar = self.right_sidebar_rect()?;+ let width = self.right_sidebar_plugin_extended_width()?;+ if sidebar.width <= width {+ return None;+ }+ Some(RightSidebarRect {+ x: sidebar.x,+ y: sidebar.y,+ width,+ height: sidebar.height,+ })+ }++ /// The line between a plugin's extended view and its panel dragged to+ /// `split_x`: the one grows as much as the other shrinks.+ pub(crate) fn set_right_sidebar_plugin_extended_split_x(&mut self, split_x: isize) -> bool {+ let Some(total_rect) = self.right_sidebar_rect() else {+ return false;+ };+ if self.right_sidebar_plugin_extended_rect().is_none() {+ return false;+ }++ let total_left = total_rect.x;+ let total_right = total_rect.x.saturating_add(total_rect.width);+ let min_extended = self.ui_px(PLUGIN_EXTENDED_MIN_WIDTH);+ let max_extended = total_rect+ .width+ .saturating_sub(self.ui_px(RIGHT_SIDEBAR_MIN_WIDTH));+ let min_panel = self.ui_px(RIGHT_SIDEBAR_MIN_WIDTH);+ let max_panel = self.right_sidebar_max_width().min(total_rect.width);+ let min_split = total_left+ .saturating_add(min_extended)+ .max(total_right.saturating_sub(max_panel));+ let max_split = total_right+ .saturating_sub(min_panel)+ .min(total_left.saturating_add(max_extended));+ if min_split > max_split {+ return false;+ }++ let split_x = split_x.clamp(min_split as isize, max_split as isize) as usize;+ let extended_width = split_x.saturating_sub(total_left);+ let panel_width = total_right.saturating_sub(split_x);+ let Some(panel) = self.right_sidebar_plugin.as_mut() else {+ return false;+ };+ let old_extended = std::mem::replace(&mut panel.extended_width, extended_width);+ let old_panel = self.right_sidebar_width;+ self.set_right_sidebar_width(panel_width);+ old_extended != extended_width || old_panel != self.right_sidebar_width+ }++ /// The sidebar's outer edge dragged to make it `width` wide while a+ /// plugin's extended view is on show: the view takes what the panel+ /// does not.+ pub(crate) fn set_right_sidebar_plugin_extended_total_width(&mut self, width: usize) -> bool {+ if self.right_sidebar_plugin_extended_rect().is_none() {+ return false;+ }+ let panel_width = self.right_sidebar_tree_width();+ let min = self.ui_px(PLUGIN_EXTENDED_MIN_WIDTH);+ let Some(max) = self.right_sidebar_plugin_extended_room() else {+ return false;+ };+ let Some(panel) = self.right_sidebar_plugin.as_mut() else {+ return false;+ };+ let extended_width = width.saturating_sub(panel_width).clamp(min, max);+ std::mem::replace(&mut panel.extended_width, extended_width) != extended_width+ }++ /// Keeps how wide the extended view of the plugin on show is, for the+ /// next time it is.+ pub fn persist_right_sidebar_plugin_extended_width(&self) {+ let Some(panel) = self.right_sidebar_plugin.as_ref() else {+ return;+ };+ let width = self+ .right_sidebar_plugin_extended_width()+ .unwrap_or(panel.extended_width)+ .max(self.ui_px(PLUGIN_EXTENDED_MIN_WIDTH));+ let width = unscale_ui_usize(width, self.dimensions.dpi);+ if let Err(err) = crate::native_settings::save_plugin_extended_width(panel.plugin(), width)+ {+ log::warn!("failed to save the width of a plugin's extended view: {err:#}");+ }+ }+pub fn persist_right_sidebar_note_pane_width(&self) {let width = self.right_sidebar_note_pane_width()@@ -7114,6 +7298,42 @@ impl crate::TermWindow {.context("right sidebar note pane left separator")?;}+ // A plugin's extended view: its ground and edge here, what the+ // plugin draws in it with the panel's, below.+ if let Some(extended_rect) = self.right_sidebar_plugin_extended_rect() {+ self.filled_rectangle(+ layers,+ 0,+ euclid::rect(+ extended_rect.x as f32,+ 0.0,+ extended_rect.width as f32,+ extended_rect.y.saturating_add(extended_rect.height) as f32,+ ),+ sidebar_bg,+ )+ .context("right sidebar plugin extended view background")?;+ self.ui_items.push(UIItem {+ x: extended_rect.x,+ y: 0,+ width: extended_rect.width,+ height: extended_rect.y.saturating_add(extended_rect.height),+ item_type: UIItemType::RightSidebarBackground,+ });+ self.filled_rectangle(+ layers,+ 1,+ euclid::rect(+ extended_rect.x as f32,+ extended_rect.y as f32,+ 1.0,+ extended_rect.height as f32,+ ),+ chrome.separator,+ )+ .context("right sidebar plugin extended view left separator")?;+ }+if rect.y > 0 {self.filled_rectangle(layers,@@ -7180,6 +7400,17 @@ impl crate::TermWindow {item_type: UIItemType::RightSidebarNotePaneResize,});}+ if self.right_sidebar_plugin_extended_rect().is_some() {+ self.ui_items.push(UIItem {+ x: rect+ .x+ .saturating_sub(self.ui_px(SIDEBAR_RESIZE_HANDLE_WIDTH) / 2),+ y: rect.y,+ width: self.ui_px(SIDEBAR_RESIZE_HANDLE_WIDTH),+ height: rect.height,+ item_type: UIItemType::RightSidebarPluginExtendedResize,+ });+ }let content_x = rect.x + self.ui_px(SIDEBAR_INSET) * 2;let content_width = rect.width.saturating_sub(self.ui_px(SIDEBAR_INSET) * 4);@@ -7307,27 +7538,36 @@ impl crate::TermWindow {.clamp(self.ui_px(24), self.ui_px(30)).min(mode_height.saturating_sub(self.ui_px(22))).max(1);- let active_mode_label = self.right_sidebar_mode.label();- let active_label_target_width = self- .sidebar_text_width(&ui_font, &active_mode_label)?- .ceil() as usize- + self.ui_px(MODE_LABEL_CLIP_SLOP);+ let labeled = modes.len() <= RIGHT_SIDEBAR_LABELED_MODES;+ let active_label_target_width = if labeled {+ let active_mode_label = self.right_sidebar_mode.label();+ self.sidebar_text_width(&ui_font, &active_mode_label)?+ .ceil() as usize+ + self.ui_px(MODE_LABEL_CLIP_SLOP)+ } else {+ 0+ };let inactive_segment_min_width = (mode_icon_size + self.ui_px(SIDEBAR_INSET) * 4).max(self.ui_px(70)).min((content_width / modes.len()).max(1));let inactive_segment_count = modes.len().saturating_sub(1);let inactive_segments_min_width =inactive_segment_min_width.saturating_mul(inactive_segment_count);- let active_segment_width = (mode_icon_size- + self.ui_px(SIDEBAR_ICON_GAP)- + active_label_target_width- + self.ui_px(SIDEBAR_INSET) * 6)- .min(- content_width- .saturating_sub(inactive_segments_min_width)- .max(1),- )- .max(1);+ let active_segment_width = if labeled {+ (mode_icon_size+ + self.ui_px(SIDEBAR_ICON_GAP)+ + active_label_target_width+ + self.ui_px(SIDEBAR_INSET) * 6)+ .min(+ content_width+ .saturating_sub(inactive_segments_min_width)+ .max(1),+ )+ .max(1)+ } else {+ // A share like the others'.+ (content_width / modes.len()).max(1)+ };let inactive_segments_width = content_width.saturating_sub(active_segment_width);let inactive_segment_width = if inactive_segment_count > 0 {inactive_segments_width / inactive_segment_count@@ -7369,17 +7609,33 @@ impl crate::TermWindow {item_type: UIItemType::RightSidebarMode(mode),});+ // The pill the active segment is filled with, and the hover:+ // the segment less an inset, or with icons alone, a circle+ // round the icon.+ let inner_inset = self.ui_px(5);+ let pill = if labeled {+ euclid::rect(+ (segment_x + inner_inset) as f32,+ (mode_y + inner_inset) as f32,+ segment_width.saturating_sub(inner_inset * 2) as f32,+ mode_height.saturating_sub(inner_inset * 2) as f32,+ )+ } else {+ let diameter = segment_width+ .min(mode_height)+ .saturating_sub(inner_inset * 2);+ euclid::rect(+ (segment_x + segment_width.saturating_sub(diameter) / 2) as f32,+ (mode_y + mode_height.saturating_sub(diameter) / 2) as f32,+ diameter as f32,+ diameter as f32,+ )+ };if active {- let inner_inset = self.ui_px(5);self.fill_rounded_rectangle_with_border(layers,2,- euclid::rect(- (segment_x + inner_inset) as f32,- (mode_y + inner_inset) as f32,- segment_width.saturating_sub(inner_inset * 2) as f32,- mode_height.saturating_sub(inner_inset * 2) as f32,- ),+ pill,chrome.control_bg,chrome.control_border,WINDOW_TAB_ADD_BUTTON_RADIUS,@@ -7390,19 +7646,14 @@ impl crate::TermWindow {self.fill_rounded_rectangle(layers,2,- euclid::rect(- (segment_x + self.ui_px(5)) as f32,- (mode_y + self.ui_px(5)) as f32,- segment_width.saturating_sub(self.ui_px(10)) as f32,- mode_height.saturating_sub(self.ui_px(10)) as f32,- ),+ pill,chrome.sidebar_button_hover_bg,WINDOW_TAB_ADD_BUTTON_RADIUS,).context("right sidebar hovered mode")?;}- let label_width = if active {+ let label_width = if active && labeled {segment_width.saturating_sub(mode_icon_size@@ -7413,7 +7664,7 @@ impl crate::TermWindow {} else {0};- let total_width = if active {+ let total_width = if label_width > 0 {mode_icon_size + self.ui_px(SIDEBAR_ICON_GAP) + label_width} else {mode_icon_size@@ -7456,6 +7707,11 @@ impl crate::TermWindow {self.fall_back_to_an_enabled_panel();return Ok(());}+ // A plugin's panel on show only while its mode is: the plugin is+ // told it went, and what it held is let go.+ if !matches!(self.right_sidebar_mode, RightSidebarMode::Plugin(_)) {+ self.close_plugin_panel();+ }match self.right_sidebar_mode {RightSidebarMode::Chat => {let file_font_size = self.right_sidebar_file_preview_font_size();@@ -7538,6 +7794,71 @@ impl crate::TermWindow {)?;return Ok(());}+ RightSidebarMode::Plugin(_) => {+ let Some(panel) = self.right_sidebar_mode.plugin_panel() else {+ self.fall_back_to_an_enabled_panel();+ return Ok(());+ };+ let stage = crate::input_diagnostics::StageTimer::begin("plugin_panel_paint");+ let result = self.plugin_panel_paint().and_then(|paint| {+ // The panel's own padding is the plugin's to draw.+ self.paint_plugin_panel(+ layers,+ &panel.id,+ &paint,+ &ui_font,+ ui_metrics,+ chrome,+ rect.x + self.ui_px(SIDEBAR_INSET),+ content_top,+ rect.width.saturating_sub(self.ui_px(SIDEBAR_INSET) * 2),+ rect.y.saturating_add(rect.height),+ )?;+ // Its extended view from the top, as the file preview+ // is, with the preview's close button where the preview+ // has it: ThinkTerm's, over what the plugin draws.+ let Some(extended_rect) = self.right_sidebar_plugin_extended_rect() else {+ return Ok(());+ };+ let close_x = extended_rect.x + self.ui_px(SIDEBAR_INSET) * 2;+ let close_y = extended_rect.y+ + self.ui_px(SIDEBAR_INSET) * 2+ + self.ui_px(PREVIEW_HEADER_TOP_GAP);+ let close_size = self.ui_px(PREVIEW_HEADER_BUTTON).min(+ extended_rect+ .width+ .saturating_sub(self.ui_px(SIDEBAR_INSET) * 4),+ );+ self.paint_plugin_panel_extended(+ layers,+ &paint,+ &ui_font,+ ui_metrics,+ chrome,+ extended_rect.x + self.ui_px(SIDEBAR_INSET),+ extended_rect.y + self.ui_px(SIDEBAR_INSET) * 2,+ extended_rect+ .width+ .saturating_sub(self.ui_px(SIDEBAR_INSET) * 2),+ extended_rect.y.saturating_add(extended_rect.height),+ (close_x, close_y, close_size),+ )?;+ self.paint_files_preview_header_icon_button(+ layers,+ chrome,+ foreground,+ muted_fg,+ close_x,+ close_y,+ close_size,+ SvgIcon::X,+ UIItemType::RightSidebarPluginExtendedClose,+ )+ });+ stage.finish(result.is_ok());+ result?;+ return Ok(());+ }}}@@ -11029,6 +11350,7 @@ impl crate::TermWindow {content_width,label,enabled,+ UIItemType::RightSidebarRemoteFileConnect,)?;}Ok(())@@ -11062,7 +11384,8 @@ impl crate::TermWindow {/// as a primary button (accent fill) rather than reusing the neutral/// `sidebar_button_bg` that the surrounding message cards use — otherwise/// the only clickable thing on screen looks exactly like the text above it.- fn paint_remote_files_connect_button(+ /// A plugin's panel waiting to connect shows the same one (`item_type`).+ pub(crate) fn paint_remote_files_connect_button(&mut self,layers: &mut TripleLayerQuadAllocator,ui_font: &Rc<LoadedFont>,@@ -11073,6 +11396,7 @@ impl crate::TermWindow {width: usize,label: &str,enabled: bool,+ item_type: UIItemType,) -> anyhow::Result<()> {let height = self.ui_px(REMOTE_EMPTY_BUTTON_HEIGHT);let hovered = enabled && self.is_pointer_over_ui_rect(x, y, width, height);@@ -11099,7 +11423,7 @@ impl crate::TermWindow {y,width,height,- item_type: UIItemType::RightSidebarRemoteFileConnect,+ item_type,});}let label_width = self@@ -11796,7 +12120,7 @@ impl crate::TermWindow {}}- fn active_remote_project_for_files(+ pub(crate) fn active_remote_project_for_files(&self,) -> Result<Option<workspace_threads::RemoteFilesTarget>, String> {let mux = Mux::get();@@ -11842,7 +12166,7 @@ impl crate::TermWindow {/// without this the server (or a NAT) reaps it and the next browse fails.const REMOTE_FILES_KEEPALIVE_SECS: &'static str = "30";- fn ssh_config_for_remote_files_target(+ pub(crate) fn ssh_config_for_remote_files_target(target: &workspace_threads::RemoteFilesTarget,) -> Result<config::SshDomain, String> {let mut domain = Self::ssh_config_for_remote_files_source(target)?;