Skip to content

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

Add SSH hosts manager and runtime domains

RoversX09033ac9e41f
diff --git a/config/src/keyassignment.rs b/config/src/keyassignment.rs
index 9fed3239..3aa21ba9 100644
--- a/config/src/keyassignment.rs
+++ b/config/src/keyassignment.rs
@@ -652,6 +652,7 @@ pub enum KeyAssignment {
ResetTerminal,
OpenUri(String),
OpenSettings,
+ OpenSshHosts,
ActivateCommandPalette,
ActivateWindow(usize),
ActivateWindowRelative(isize),
diff --git a/mux/src/ssh.rs b/mux/src/ssh.rs
index a3e7055f..66825cf0 100644
--- a/mux/src/ssh.rs
+++ b/mux/src/ssh.rs
@@ -229,6 +229,19 @@ pub fn ssh_domain_to_ssh_config(ssh_dom: &SshDomain) -> anyhow::Result<ConfigMap
Ok(ssh_config)
}
+/// Parse the `ID=` value out of `/etc/os-release` contents (e.g. "ubuntu").
+fn parse_os_release_id(text: &str) -> Option<String> {
+ for line in text.lines() {
+ if let Some(rest) = line.trim().strip_prefix("ID=") {
+ let value = rest.trim().trim_matches('"').to_string();
+ if !value.is_empty() {
+ return Some(value);
+ }
+ }
+ }
+ None
+}
+
impl RemoteSshDomain {
pub fn with_ssh_domain(dom: &SshDomain) -> anyhow::Result<Self> {
let id = alloc_domain_id();
@@ -240,6 +253,26 @@ impl RemoteSshDomain {
})
}
+ /// Run a one-shot, read-only `cat /etc/os-release` over the already
+ /// established session and return the parsed distro `ID` (e.g. "ubuntu").
+ /// Returns `None` on any error (no session, command failure, etc).
+ pub async fn detect_os_release(&self) -> Option<String> {
+ let session = self.session.lock().unwrap().as_ref().cloned()?;
+ let exec = session
+ .exec("cat /etc/os-release 2>/dev/null", None)
+ .await
+ .ok()?;
+ let mut stdout = exec.stdout;
+ // Read on a blocking thread so we don't stall the async executor.
+ let text = smol::unblock(move || {
+ let mut buf = String::new();
+ let _ = stdout.read_to_string(&mut buf);
+ buf
+ })
+ .await;
+ parse_os_release_id(&text)
+ }
+
pub fn ssh_config(&self) -> anyhow::Result<ConfigMap> {
ssh_domain_to_ssh_config(&self.dom)
}
diff --git a/wezterm-gui/src/commands.rs b/wezterm-gui/src/commands.rs
index 4fe66936..9433828a 100644
--- a/wezterm-gui/src/commands.rs
+++ b/wezterm-gui/src/commands.rs
@@ -750,6 +750,14 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Comm
menubar: &["ThinkTerm"],
icon: Some("cod_settings_gear"),
},
+ OpenSshHosts => CommandDef {
+ brief: "SSH Hosts...".into(),
+ doc: "Opens the ThinkTerm SSH host manager".into(),
+ keys: vec![],
+ args: &[ArgType::ActiveWindow],
+ menubar: &["Shell"],
+ icon: Some("md_server_network"),
+ },
SpawnWindow => CommandDef {
brief: "New Window".into(),
doc: "Launches the default program into a new window".into(),
@@ -2125,6 +2133,7 @@ fn compute_default_actions() -> Vec<KeyAssignment> {
#[cfg(target_os = "macos")]
QuitApplication,
// ----------------- Shell
+ OpenSshHosts,
SpawnTab(SpawnTabDomain::CurrentPaneDomain),
SpawnWindow,
SplitVertical(SpawnCommand {
diff --git a/wezterm-gui/src/glyphcache.rs b/wezterm-gui/src/glyphcache.rs
index 3e6909b5..af16e353 100644
--- a/wezterm-gui/src/glyphcache.rs
+++ b/wezterm-gui/src/glyphcache.rs
@@ -2,7 +2,7 @@ use super::utilsprites::RenderMetrics;
use crate::customglyph::*;
use crate::renderstate::RenderContext;
use crate::termwindow::render::paint::AllowImage;
-use crate::termwindow::ui::icons::SvgIcon;
+use crate::termwindow::ui::icons::{BrandIcon, SvgIcon};
use ::window::bitmaps::atlas::{Atlas, OutOfTextureSpace, Sprite};
use ::window::bitmaps::{BitmapImage, Image, ImageTexture, Texture2d};
use ::window::color::SrgbaPixel;
@@ -85,6 +85,12 @@ pub struct SizedRotatedSvgIconKey {
pub frame: u8,
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct SizedBrandIconKey {
+ pub icon: BrandIcon,
+ pub size: u16,
+}
+
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GlyphKey {
pub font_idx: usize,
@@ -580,6 +586,7 @@ pub struct GlyphCache {
line_glyphs: HashMap<LineKey, Sprite>,
pub block_glyphs: HashMap<SizedBlockKey, Sprite>,
pub svg_icons: HashMap<SizedSvgIconKey, Sprite>,
+ pub brand_icons: HashMap<SizedBrandIconKey, Sprite>,
pub cursor_glyphs: HashMap<(Option<CursorShape>, u8), Sprite>,
pub color: HashMap<(RgbColor, NotNan<f32>), Sprite>,
pub rotated_svg_icons: HashMap<SizedRotatedSvgIconKey, Sprite>,
@@ -634,6 +641,7 @@ impl GlyphCache {
line_glyphs: HashMap::new(),
block_glyphs: HashMap::new(),
svg_icons: HashMap::new(),
+ brand_icons: HashMap::new(),
rotated_svg_icons: HashMap::new(),
cursor_glyphs: HashMap::new(),
color: HashMap::new(),
@@ -665,6 +673,7 @@ impl GlyphCache {
line_glyphs: HashMap::new(),
block_glyphs: HashMap::new(),
svg_icons: HashMap::new(),
+ brand_icons: HashMap::new(),
rotated_svg_icons: HashMap::new(),
cursor_glyphs: HashMap::new(),
color: HashMap::new(),
@@ -1200,6 +1209,23 @@ impl GlyphCache {
Ok(sprite)
}
+ pub fn cached_brand_icon(&mut self, icon: BrandIcon, size: usize) -> anyhow::Result<Sprite> {
+ let size = size.max(1).min(u16::MAX as usize);
+ let key = SizedBrandIconKey {
+ icon,
+ size: size as u16,
+ };
+
+ if let Some(sprite) = self.brand_icons.get(&key) {
+ return Ok(sprite.clone());
+ }
+
+ let image = icon.rasterize(size)?;
+ let sprite = self.atlas.allocate(&image)?;
+ self.brand_icons.insert(key, sprite.clone());
+ Ok(sprite)
+ }
+
pub fn cached_rotated_svg_icon(
&mut self,
icon: SvgIcon,
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index 40d7f35d..94e4379c 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -54,6 +54,7 @@ mod selection;
mod settings_window;
mod shapecache;
mod spawn;
+mod ssh_hosts;
mod stats;
mod tabbar;
mod termwindow;
@@ -700,6 +701,9 @@ fn setup_mux(
mux.set_active_workspace(&default_workspace_name);
crate::update::load_last_release_info_and_set_banner();
update_mux_domains(config)?;
+ // Register ThinkTerm's saved SSH hosts as runtime mux domains so that
+ // reconnecting / restoring remote sessions can resolve them by name.
+ crate::ssh_hosts::register_saved_hosts();
let default_name =
default_domain_name.unwrap_or(config.default_domain.as_deref().unwrap_or("local"));
diff --git a/wezterm-gui/src/project_sessions.rs b/wezterm-gui/src/project_sessions.rs
index ce20c951..b76a6558 100644
--- a/wezterm-gui/src/project_sessions.rs
+++ b/wezterm-gui/src/project_sessions.rs
@@ -35,6 +35,48 @@ pub struct Project {
pub active_session_id: Option<SessionId>,
#[serde(default)]
pub sessions_collapsed: bool,
+ /// When set, this "project" is a remote SSH host rather than a local
+ /// folder. Local projects leave this `None`.
+ #[serde(default)]
+ pub remote: Option<SshHostSpec>,
+}
+
+/// Stored SSH host definition. A remote [`Project`] carries one of these; the
+/// connection layer (`ssh_hosts.rs`) turns it into a live `config::SshDomain`.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct SshHostSpec {
+ /// Display name shown on the host card / sidebar row.
+ pub label: String,
+ /// Hostname or IP address of the remote server.
+ pub host: String,
+ #[serde(default)]
+ pub port: Option<u16>,
+ #[serde(default)]
+ pub username: Option<String>,
+ /// Path to an SSH identity (private key) file, if any.
+ #[serde(default)]
+ pub identity_file: Option<String>,
+ /// Extra `ssh_config` option overrides (key -> value).
+ #[serde(default)]
+ pub ssh_options: HashMap<String, String>,
+ /// Use WezTerm's multiplexed SSH (persistent, reconnecting) when true,
+ /// otherwise connect directly like `ssh`.
+ #[serde(default = "default_true")]
+ pub multiplexing: bool,
+ /// Override the default `ssh:<host>` workspace name.
+ #[serde(default)]
+ pub default_workspace: Option<String>,
+ /// When true, run a one-shot `cat /etc/os-release` after connecting to
+ /// detect the distro and pick its icon. User-controlled (opt-in).
+ #[serde(default = "default_true")]
+ pub detect_os: bool,
+ /// `/etc/os-release` `ID` detected after connecting; drives the OS icon.
+ #[serde(default)]
+ pub detected_distro: Option<String>,
+}
+
+fn default_true() -> bool {
+ true
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -93,6 +135,10 @@ pub struct ProjectView {
pub is_active: bool,
pub sessions_collapsed: bool,
pub sessions: Vec<SessionView>,
+ /// True when this project is a remote SSH host rather than a local folder.
+ pub is_remote: bool,
+ /// Detected `/etc/os-release` `ID` for remote hosts, used to pick an OS icon.
+ pub distro: Option<String>,
}
#[derive(Debug, Clone)]
@@ -228,6 +274,7 @@ pub fn current_project_from_cwd() -> Project {
sessions: vec![],
active_session_id: None,
sessions_collapsed: false,
+ remote: None,
}
}
@@ -270,6 +317,124 @@ pub fn create_project_from_path(path: &str) -> Result<SessionId> {
Ok(session_id)
}
+/// Return every stored SSH host (remote project) as `(project_id, spec)`.
+pub fn list_hosts() -> Vec<(ProjectId, SshHostSpec)> {
+ let store = SESSION_STORE.lock();
+ store
+ .projects
+ .iter()
+ .filter_map(|project| {
+ project
+ .remote
+ .clone()
+ .map(|spec| (project.id.clone(), spec))
+ })
+ .collect()
+}
+
+/// Fetch the SSH host spec for a remote project, if it is one.
+pub fn host_spec(project_id: &str) -> Option<SshHostSpec> {
+ let store = SESSION_STORE.lock();
+ store
+ .projects
+ .iter()
+ .find(|project| project.id == project_id)
+ .and_then(|project| project.remote.clone())
+}
+
+/// Create (or update, when host+user+port already exist) an SSH host. Returns
+/// the remote project id. The host starts with no sessions; connecting creates
+/// them.
+pub fn create_host(spec: SshHostSpec) -> ProjectId {
+ let mut store = SESSION_STORE.lock();
+ let project_id = project_id_for_host(&spec);
+ if let Some(project) = store.projects.iter_mut().find(|p| p.id == project_id) {
+ project.name = spec.label.clone();
+ project.remote = Some(spec);
+ } else {
+ let path = PathBuf::from(format!("ssh://{}", host_display(&spec)));
+ store.projects.push(Project {
+ id: project_id.clone(),
+ name: spec.label.clone(),
+ path,
+ sessions: vec![],
+ active_session_id: None,
+ sessions_collapsed: false,
+ remote: Some(spec),
+ });
+ }
+ persist_locked(&store);
+ project_id
+}
+
+/// Update the spec of an existing remote project in place. Returns false when
+/// the project does not exist or is not a remote host.
+pub fn update_host(project_id: &str, spec: SshHostSpec) -> bool {
+ let mut store = SESSION_STORE.lock();
+ let Some(project) = store
+ .projects
+ .iter_mut()
+ .find(|p| p.id == project_id && p.remote.is_some())
+ else {
+ return false;
+ };
+ project.name = spec.label.clone();
+ project.remote = Some(spec);
+ persist_locked(&store);
+ true
+}
+
+/// Remove an SSH host (and any sessions under it). Delegates to the shared
+/// project-removal path so workspace cleanup is handled identically.
+pub fn remove_host(project_id: &str) -> Option<RemovedProject> {
+ remove_project(project_id)
+}
+
+/// Record the detected `/etc/os-release` `ID` for a host so the UI can show the
+/// matching OS icon. Returns true when the value changed.
+pub fn set_host_distro(project_id: &str, distro_id: &str) -> bool {
+ let mut store = SESSION_STORE.lock();
+ let Some(project) = store.projects.iter_mut().find(|p| p.id == project_id) else {
+ return false;
+ };
+ let Some(remote) = project.remote.as_mut() else {
+ return false;
+ };
+ let new_value = {
+ let trimmed = distro_id.trim();
+ (!trimmed.is_empty()).then(|| trimmed.to_string())
+ };
+ if remote.detected_distro == new_value {
+ return false;
+ }
+ remote.detected_distro = new_value;
+ persist_locked(&store);
+ true
+}
+
+/// Create a new session under a remote (SSH) project bound to `workspace_name`,
+/// mark it active, and return its id. Returns `None` if the project is missing
+/// or not a remote host.
+pub fn create_host_session(project_id: &str, workspace_name: &str) -> Option<SessionId> {
+ let mut store = SESSION_STORE.lock();
+ let project = store
+ .projects
+ .iter_mut()
+ .find(|p| p.id == project_id && p.remote.is_some())?;
+ let name = format!("Session {}", project.sessions.len() + 1);
+ let session = Session::new(
+ project_id.to_string(),
+ name,
+ Some(workspace_name.to_string()),
+ );
+ let session_id = session.id.clone();
+ project.active_session_id = Some(session_id.clone());
+ project.sessions.push(session);
+ store.active_project_id = Some(project_id.to_string());
+ persist_locked(&store);
+ Some(session_id)
+}
+
pub fn activate_session_record(
session_id: &str,
live_workspaces: &[String],
@@ -331,6 +496,7 @@ pub async fn materialize_session(
size: TerminalSize,
src_window_id: Option<MuxWindowId>,
term_config: Arc<dyn TerminalConfiguration>,
+ default_domain: SpawnTabDomain,
) -> Result<()> {
let mux = Mux::get();
if !mux.iter_windows_in_workspace(&workspace_name).is_empty() {
@@ -350,7 +516,7 @@ pub async fn materialize_session(
let (_tab, pane, _window_id) = mux
.spawn_tab_or_window(
None,
- SpawnTabDomain::DefaultDomain,
+ default_domain,
None,
initial_cwd,
size,
@@ -569,6 +735,11 @@ impl SessionStore {
.into_iter()
.filter(|session| !session.is_pinned)
.collect(),
+ is_remote: project.remote.is_some(),
+ distro: project
+ .remote
+ .as_ref()
+ .and_then(|spec| spec.detected_distro.clone()),
})
.collect();
ProjectSessionView {
@@ -655,6 +826,7 @@ impl SessionStore {
sessions: vec![],
active_session_id: None,
sessions_collapsed: false,
+ remote: None,
};
let session = Session::new(project_id.clone(), "main".to_string(), None);
let session_id = session.id.clone();
@@ -1439,6 +1611,35 @@ fn project_id_for_path(path: &Path) -> ProjectId {
format!("project-{hash:x}")
}
+fn fnv1a(input: &str) -> u64 {
+ let mut hash = 0xcbf29ce484222325u64;
+ for byte in input.bytes() {
+ hash ^= byte as u64;
+ hash = hash.wrapping_mul(0x100000001b3);
+ }
+ hash
+}
+
+/// `user@host` (or just `host`) for display / synthetic paths.
+fn host_display(spec: &SshHostSpec) -> String {
+ match &spec.username {
+ Some(user) if !user.is_empty() => format!("{user}@{}", spec.host),
+ _ => spec.host.clone(),
+ }
+}
+
+/// Stable id for a remote project, derived from user@host:port so re-adding the
+/// same host maps back to the same project.
+fn project_id_for_host(spec: &SshHostSpec) -> ProjectId {
+ let key = format!(
+ "ssh:{}@{}:{}",
+ spec.username.as_deref().unwrap_or(""),
+ spec.host,
+ spec.port.unwrap_or(22)
+ );
+ format!("ssh-{:x}", fnv1a(&key))
+}
+
fn normalize_project_path(path: &str) -> Result<PathBuf> {
let trimmed = path.trim();
ensure!(!trimmed.is_empty(), "project path is empty");
@@ -1505,6 +1706,7 @@ mod tests {
)],
active_session_id: None,
sessions_collapsed: false,
+ remote: None,
};
store.active_project_id = Some(project.id.clone());
store.projects.push(project);
@@ -1528,6 +1730,7 @@ mod tests {
sessions: vec![session],
active_session_id: None,
sessions_collapsed: false,
+ remote: None,
});
save_session_store_to_path(&path, &store).unwrap();
@@ -1560,6 +1763,7 @@ mod tests {
)],
active_session_id: None,
sessions_collapsed: false,
+ remote: None,
};
let session_id = project.sessions[0].id.clone();
store.projects.push(project);
@@ -1621,6 +1825,7 @@ mod tests {
)],
active_session_id: None,
sessions_collapsed: false,
+ remote: None,
};
let session_id = project.sessions[0].id.clone();
store.projects.push(project);
@@ -1651,6 +1856,7 @@ mod tests {
sessions: vec![session.clone()],
active_session_id: Some(session_id),
sessions_collapsed: false,
+ remote: None,
};
store.projects.push(project);
store.snapshot_workspace_layout(
@@ -1679,6 +1885,7 @@ mod tests {
sessions: vec![first],
active_session_id: Some(first_id),
sessions_collapsed: false,
+ remote: None,
});
store.projects.push(Project {
id: "project-2".to_string(),
@@ -1687,6 +1894,7 @@ mod tests {
sessions: vec![second],
active_session_id: Some(second_id),
sessions_collapsed: false,
+ remote: None,
});
store.active_project_id = Some("project-2".to_string());
@@ -1711,6 +1919,7 @@ mod tests {
sessions: vec![first],
active_session_id: Some(first_id),
sessions_collapsed: false,
+ remote: None,
});
store.projects.push(Project {
id: "project-2".to_string(),
@@ -1719,6 +1928,7 @@ mod tests {
sessions: vec![second],
active_session_id: Some(second_id.clone()),
sessions_collapsed: false,
+ remote: None,
});
store.active_project_id = Some("project-2".to_string());
@@ -1753,6 +1963,7 @@ mod tests {
sessions: vec![first, second, third],
active_session_id: Some(first_id.clone()),
sessions_collapsed: false,
+ remote: None,
});
assert!(store.rename_session(&second_id, "Review".to_string()));
diff --git a/wezterm-gui/src/ssh_hosts.rs b/wezterm-gui/src/ssh_hosts.rs
new file mode 100644
index 00000000..0de6ff3c
--- /dev/null
+++ b/wezterm-gui/src/ssh_hosts.rs
@@ -0,0 +1,106 @@
+//! Runtime SSH host -> mux domain plumbing for the ThinkTerm host manager.
+//!
+//! ThinkTerm stores SSH hosts as "remote projects" (see
+//! [`crate::project_sessions::SshHostSpec`]). Unlike WezTerm's Lua
+//! `ssh_domains`, these are registered with the mux **at runtime** via
+//! [`mux::Mux::add_domain`]. No engine changes are required: building a domain
+//! from a struct (`RemoteSshDomain::with_ssh_domain`) and adding it is exactly
+//! what `wezterm ssh` already does in `main.rs`.
+
+use crate::project_sessions::{self, SshHostSpec};
+use anyhow::Result;
+use config::{SshDomain, SshMultiplexing};
+use mux::domain::Domain;
+use mux::ssh::RemoteSshDomain;
+use mux::Mux;
+use std::collections::HashMap;
+use std::sync::Arc;
+
+/// `user@host` (or `host`, with `:port` when non-default) used for the
+/// human-readable domain / workspace identifiers.
+fn endpoint(spec: &SshHostSpec) -> String {
+ let host = match spec.port {
+ Some(port) if port != 22 => format!("{}:{port}", spec.host),
+ _ => spec.host.clone(),
+ };
+ match &spec.username {
+ Some(user) if !user.is_empty() => format!("{user}@{host}"),
+ _ => host,
+ }
+}
+
+/// Deterministic mux domain name for a host. Stable across restarts so that a
+/// snapshotted SSH layout (which records the pane's domain name) can be
+/// re-materialized after [`register_saved_hosts`] re-registers the domain.
+pub fn ssh_domain_name(spec: &SshHostSpec) -> String {
+ format!("ssh:{}", endpoint(spec))
+}
+
+/// Default workspace a connection lands in: `ssh:<endpoint>`, unless the host
+/// overrides it.
+pub fn default_workspace_name(spec: &SshHostSpec) -> String {
+ spec.default_workspace
+ .clone()
+ .filter(|name| !name.trim().is_empty())
+ .unwrap_or_else(|| format!("ssh:{}", endpoint(spec)))
+}
+
+/// Translate a stored host spec into a `config::SshDomain`.
+pub fn build_ssh_domain(spec: &SshHostSpec) -> SshDomain {
+ let mut ssh_option = HashMap::new();
+ for (key, value) in &spec.ssh_options {
+ ssh_option.insert(key.to_lowercase(), value.clone());
+ }
+ if let Some(identity) = &spec.identity_file {
+ if !identity.trim().is_empty() {
+ ssh_option.insert("identityfile".to_string(), identity.clone());
+ }
+ }
+
+ let remote_address = match spec.port {
+ Some(port) => format!("{}:{port}", spec.host),
+ None => spec.host.clone(),
+ };
+
+ SshDomain {
+ name: ssh_domain_name(spec),
+ remote_address,
+ username: spec.username.clone(),
+ multiplexing: if spec.multiplexing {
+ SshMultiplexing::WezTerm
+ } else {
+ SshMultiplexing::None
+ },
+ ssh_option,
+ ..Default::default()
+ }
+}
+
+/// Ensure the host's SSH domain is registered with the mux, building and adding
+/// it on first use. Returns the domain name to spawn into. The actual SSH
+/// connection is established lazily by the domain's `spawn_pane`, so this is
+/// cheap and does not block on the network.
+pub fn ensure_ssh_domain_registered(spec: &SshHostSpec) -> Result<String> {
+ let name = ssh_domain_name(spec);
+ let mux = Mux::get();
+ if mux.get_domain_by_name(&name).is_none() {
+ let dom = build_ssh_domain(spec);
+ let domain: Arc<dyn Domain> = Arc::new(RemoteSshDomain::with_ssh_domain(&dom)?);
+ mux.add_domain(&domain);
+ }
+ Ok(name)
+}
+
+/// Register every saved SSH host as a mux domain. Called once at startup so
+/// that re-activating a previously-connected remote session (whose saved layout
+/// references the domain by name) works without re-opening the host manager.
+pub fn register_saved_hosts() {
+ for (_project_id, spec) in project_sessions::list_hosts() {
+ if let Err(err) = ensure_ssh_domain_registered(&spec) {
+ log::warn!(
+ "failed to register saved SSH host {:?}: {err:#}",
+ spec.label
+ );
+ }
+ }
+}
diff --git a/wezterm-gui/src/termwindow/box_model.rs b/wezterm-gui/src/termwindow/box_model.rs
index 27a5fde1..f1f91f9a 100644
--- a/wezterm-gui/src/termwindow/box_model.rs
+++ b/wezterm-gui/src/termwindow/box_model.rs
@@ -3,7 +3,7 @@ use crate::color::LinearRgba;
use crate::customglyph::{BlockKey, Poly};
use crate::glyphcache::CachedGlyph;
use crate::quad::{QuadImpl, QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};
-use crate::termwindow::ui::icons::SvgIcon;
+use crate::termwindow::ui::icons::{BrandIcon, SvgIcon};
use crate::termwindow::{
ColorEase, MouseCapture, RenderState, TermWindowNotif, UIItem, UIItemType,
};
@@ -396,6 +396,7 @@ pub enum ElementContent {
Children(Vec<Element>),
Poly { line_width: isize, poly: SizedPoly },
Icon { icon: SvgIcon, size: Dimension },
+ BrandIcon { icon: BrandIcon, size: Dimension },
}
pub struct LayoutContext<'a> {
@@ -444,6 +445,7 @@ impl ComputedElement {
ComputedElementContent::Text(_) => {}
ComputedElementContent::Poly { .. } => {}
ComputedElementContent::Icon { .. } => {}
+ ComputedElementContent::BrandIcon { .. } => {}
}
}
@@ -473,6 +475,7 @@ impl ComputedElement {
}
ComputedElementContent::Poly { .. } => {}
ComputedElementContent::Icon { .. } => {}
+ ComputedElementContent::BrandIcon { .. } => {}
}
}
}
@@ -489,6 +492,10 @@ pub enum ComputedElementContent {
icon: SvgIcon,
size: f32,
},
+ BrandIcon {
+ icon: BrandIcon,
+ size: f32,
+ },
}
#[derive(Debug, Clone)]
@@ -848,6 +855,26 @@ impl super::TermWindow {
content: ComputedElementContent::Icon { icon: *icon, size },
})
}
+ ElementContent::BrandIcon { icon, size } => {
+ let size = size.evaluate_as_pixels(context.height).max(1.0);
+ let content_rect = euclid::rect(0., 0., size.max(min_width), size.max(min_height));
+ let rects = element.compute_rects(context, content_rect);
+
+ Ok(ComputedElement {
+ item_type: element.item_type.clone(),
+ zindex: element.zindex + context.zindex,
+ baseline,
+ border,
+ border_corners,
+ colors: element.colors.clone(),
+ hover_colors: element.hover_colors.clone(),
+ bounds: rects.bounds,
+ border_rect: rects.border_rect,
+ padding: rects.padding,
+ content_rect: rects.content_rect,
+ content: ComputedElementContent::BrandIcon { icon: *icon, size },
+ })
+ }
}
}
@@ -988,6 +1015,28 @@ impl super::TermWindow {
quad.set_hsv(None);
quad.set_grayscale();
}
+ ComputedElementContent::BrandIcon { icon, size } => {
+ // Brand icons bake their (brand) color into the sprite, so we
+ // render them full-color rather than tinting by text color.
+ let size = (*size).round().max(1.0) as usize;
+ let sprite = gl_state
+ .glyph_cache
+ .borrow_mut()
+ .cached_brand_icon(*icon, size)?
+ .texture_coords();
+ let mut quad = layers.allocate(2)?;
+ let icon_size = size as f32;
+ quad.set_position(
+ element.content_rect.min_x() + left,
+ element.content_rect.min_y() + top,
+ element.content_rect.min_x() + left + icon_size,
+ element.content_rect.min_y() + top + icon_size,
+ );
+ quad.set_texture(sprite);
+ quad.set_hsv(None);
+ quad.set_has_color(true);
+ quad.set_fg_color(LinearRgba::with_components(1.0, 1.0, 1.0, 1.0));
+ }
}
Ok(())
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index 9be33e17..54299c53 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -94,6 +94,7 @@ pub mod render;
pub mod resize;
mod selection;
pub mod spawn;
+pub mod ssh_hosts_modal;
pub mod ui;
pub mod webgpu;
@@ -234,6 +235,33 @@ pub enum UIItemType {
ScrollThumb,
BelowScrollThumb,
Split(PositionedSplit),
+ SshHosts(SshHostsAction),
+}
+
+/// Clickable targets inside the SSH host manager modal
+/// (see `termwindow/ssh_hosts_modal.rs`).
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum SshHostsAction {
+ /// Connect to the host with this remote-project id.
+ Connect(String),
+ /// Open the edit form for this host.
+ Edit(String),
+ /// Delete this host.
+ Delete(String),
+ /// Open the empty "new host" form.
+ New,
+ /// Focus the form field at this index.
+ FocusField(usize),
+ /// Toggle the "detect OS on connect" switch in the form.
+ ToggleDetect,
+ /// Save the form (create/update) and return to the grid.
+ Save,
+ /// Save the form and immediately connect.
+ SaveAndConnect,
+ /// Discard the form and return to the grid.
+ Cancel,
+ /// Click on the dimmed backdrop: dismiss the modal.
+ Background,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -3838,6 +3866,10 @@ impl TermWindow {
OpenSettings => {
crate::settings_window::show();
}
+ OpenSshHosts => {
+ let modal = crate::termwindow::ssh_hosts_modal::SshHostsModal::new();
+ self.set_modal(Rc::new(modal));
+ }
ActivateCommandPalette => {
let modal = crate::termwindow::palette::CommandPalette::new(self);
self.set_modal(Rc::new(modal));
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index 90b92d50..d0813a95 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -8,9 +8,10 @@ use crate::termwindow::ui::tokens::{
WINDOW_TAB_FULLSCREEN_SIDEBAR_BUTTON_SIZE, WINDOW_TAB_FULLSCREEN_SIDEBAR_BUTTON_X,
WINDOW_TAB_GAP, WINDOW_TAB_LEADING_ACTION_BUTTON_SIZE, WINDOW_TAB_LEADING_ACTION_GAP,
};
+use crate::termwindow::ssh_hosts_modal::SshHostsModal;
use crate::termwindow::{
- GuiWin, MouseCapture, PaneNavAction, PositionedSplit, ScrollHit, TabWheelSurface,
- TermWindowNotif, UIItem, UIItemType, TMB,
+ GuiWin, MouseCapture, PaneNavAction, PositionedSplit, ScrollHit, SshHostsAction,
+ TabWheelSurface, TermWindowNotif, UIItem, UIItemType, TMB,
};
use ::window::{
ContextMenuItem, MouseButtons as WMB, MouseCursor, MouseEvent, MouseEventKind as WMEK,
@@ -22,6 +23,7 @@ use config::keyassignment::{
};
use config::{MouseEventAltScreen, TermConfig};
use mux::pane::{Pane, WithPaneLines};
+use mux::ssh::RemoteSshDomain;
use mux::tab::{PositionedPane, SplitDirection};
use mux::Mux;
use mux_lua::MuxPane;
@@ -588,7 +590,8 @@ impl super::TermWindow {
| UIItemType::AboveScrollThumb
| UIItemType::BelowScrollThumb
| UIItemType::ScrollThumb
- | UIItemType::Split(_) => {}
+ | UIItemType::Split(_)
+ | UIItemType::SshHosts(_) => {}
}
}
@@ -615,7 +618,8 @@ impl super::TermWindow {
| UIItemType::AboveScrollThumb
| UIItemType::BelowScrollThumb
| UIItemType::ScrollThumb
- | UIItemType::Split(_) => {}
+ | UIItemType::Split(_)
+ | UIItemType::SshHosts(_) => {}
}
}
@@ -1132,6 +1136,74 @@ impl super::TermWindow {
UIItemType::WorkspaceSidebarNotifications => {
context.set_cursor(Some(MouseCursor::Hand));
}
+ UIItemType::SshHosts(action) => {
+ self.mouse_event_ssh_hosts(action, event, context);
+ }
+ }
+ }
+
+ /// Run `f` against the active SSH hosts modal, if it is the active modal.
+ fn with_ssh_hosts_modal<R>(&self, f: impl FnOnce(&SshHostsModal) -> R) -> Option<R> {
+ let modal = self.get_modal()?;
+ let modal = modal.downcast_ref::<SshHostsModal>()?;
+ Some(f(modal))
+ }
+
+ fn mouse_event_ssh_hosts(
+ &mut self,
+ action: SshHostsAction,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ context.set_cursor(Some(MouseCursor::Hand));
+ if event.kind != WMEK::Press(MousePress::Left) {
+ return;
+ }
+ match action {
+ SshHostsAction::Connect(id) => {
+ self.cancel_modal();
+ self.connect_ssh_host(id, None);
+ }
+ SshHostsAction::Edit(id) => {
+ self.with_ssh_hosts_modal(|m| m.enter_edit_form(&id));
+ self.invalidate_modal();
+ }
+ SshHostsAction::Delete(id) => {
+ crate::project_sessions::remove_host(&id);
+ self.invalidate_modal();
+ }
+ SshHostsAction::New => {
+ self.with_ssh_hosts_modal(|m| m.enter_new_form());
+ self.invalidate_modal();
+ }
+ SshHostsAction::FocusField(idx) => {
+ self.with_ssh_hosts_modal(|m| m.focus_field(idx));
+ self.invalidate_modal();
+ }
+ SshHostsAction::ToggleDetect => {
+ self.with_ssh_hosts_modal(|m| m.toggle_detect());
+ self.invalidate_modal();
+ }
+ SshHostsAction::Save => {
+ self.with_ssh_hosts_modal(|m| m.persist_form());
+ self.invalidate_modal();
+ }
+ SshHostsAction::SaveAndConnect => {
+ let id = self.with_ssh_hosts_modal(|m| m.persist_form()).flatten();
+ if let Some(id) = id {
+ self.cancel_modal();
+ self.connect_ssh_host(id, None);
+ } else {
+ self.invalidate_modal();
+ }
+ }
+ SshHostsAction::Cancel => {
+ self.with_ssh_hosts_modal(|m| m.cancel_to_grid());
+ self.invalidate_modal();
+ }
+ SshHostsAction::Background => {
+ self.cancel_modal();
+ }
}
}
@@ -1511,6 +1583,7 @@ impl super::TermWindow {
size,
None,
term_config,
+ config::keyassignment::SpawnTabDomain::DefaultDomain,
)
.await
{
@@ -1523,6 +1596,96 @@ impl super::TermWindow {
context.invalidate();
}
+ /// Connect to a stored SSH host: ensure its mux domain is registered, then
+ /// create/restore a session in the target workspace (default `ssh:<host>`)
+ /// whose panes spawn into that SSH domain. Mirrors
+ /// [`Self::activate_project_session`] but targets the SSH domain.
+ pub(crate) fn connect_ssh_host(&mut self, project_id: String, target_workspace: Option<String>) {
+ let window = self.window.clone();
+ let invalidate = |window: &_| {
+ if let Some(win) = window {
+ WindowOps::invalidate(win);
+ }
+ };
+
+ let Some(spec) = crate::project_sessions::host_spec(&project_id) else {
+ invalidate(&window);
+ return;
+ };
+ let domain_name = match crate::ssh_hosts::ensure_ssh_domain_registered(&spec) {
+ Ok(name) => name,
+ Err(err) => {
+ log::error!("failed to register SSH domain for {:?}: {err:#}", spec.label);
+ return;
+ }
+ };
+ let workspace_name = target_workspace
+ .filter(|name| !name.trim().is_empty())
+ .unwrap_or_else(|| crate::ssh_hosts::default_workspace_name(&spec));
+
+ let mux = Mux::get();
+ // Already live? Just switch to it rather than spawning a duplicate.
+ if !mux.iter_windows_in_workspace(&workspace_name).is_empty() {
+ if mux.active_workspace() != workspace_name {
+ front_end().switch_workspace(&workspace_name);
+ }
+ invalidate(&window);
+ return;
+ }
+
+ self.snapshot_active_project_session_layout();
+ let _ = crate::project_sessions::create_host_session(&project_id, &workspace_name);
+
+ let size = self.config.initial_size(
+ self.dimensions.dpi as u32,
+ crate::cell_pixel_dims(&self.config, self.dimensions.dpi as f64).ok(),
+ );
+ let term_config: Arc<dyn wezterm_term::TerminalConfiguration> =
+ Arc::new(TermConfig::with_config(self.config.clone()));
+ let switcher = crate::frontend::WorkspaceSwitcher::new(&workspace_name);
+ mux.set_active_workspace(&workspace_name);
+
+ let ws = workspace_name.clone();
+ let detect_os = spec.detect_os;
+ let detect_domain = domain_name.clone();
+ let detect_project = project_id.clone();
+ let detect_window = window.clone();
+ promise::spawn::spawn(async move {
+ if let Err(err) = crate::project_sessions::materialize_session(
+ ws,
+ None,
+ None,
+ size,
+ None,
+ term_config,
+ config::keyassignment::SpawnTabDomain::DomainName(domain_name),
+ )
+ .await
+ {
+ log::error!("failed to connect SSH session: {err:#}");
+ }
+ switcher.do_switch();
+
+ // Optional, user-controlled OS detection over the live session.
+ if detect_os {
+ if let Some(domain) = Mux::get().get_domain_by_name(&detect_domain) {
+ if let Some(ssh) = domain.as_ref().downcast_ref::<RemoteSshDomain>() {
+ if let Some(distro) = ssh.detect_os_release().await {
+ if crate::project_sessions::set_host_distro(&detect_project, &distro) {
+ if let Some(win) = detect_window.as_ref() {
+ win.invalidate();
+ }
+ }
+ }
+ }
+ }
+ }
+ })
+ .detach();
+
+ invalidate(&window);
+ }
+
fn pane_nav_tab_context_menu_items(&self, pane_id: mux::pane::PaneId) -> Vec<ContextMenuItem> {
vec![ContextMenuItem::item_with_icon(
"Rename Tab...",
diff --git a/wezterm-gui/src/termwindow/ssh_hosts_modal.rs b/wezterm-gui/src/termwindow/ssh_hosts_modal.rs
new file mode 100644
index 00000000..d4762f5c
--- /dev/null
+++ b/wezterm-gui/src/termwindow/ssh_hosts_modal.rs
@@ -0,0 +1,792 @@
+//! ThinkTerm SSH host manager — an in-window modal panel (Termius-style) that
+//! lists saved SSH hosts as clickable cards and lets you add/edit/connect them.
+//!
+//! Rendering & input follow the same pattern as the command palette
+//! (`palette.rs`): a box-model element tree built in [`Modal::computed_element`],
+//! keyboard handling in [`Modal::key_down`], and clickable cards carry a
+//! [`UIItemType::SshHosts`] item type so clicks are dispatched through the
+//! normal mouse path (`mouseevent.rs`).
+
+use crate::termwindow::box_model::*;
+use crate::termwindow::modal::Modal;
+use crate::termwindow::render::corners::{
+ BOTTOM_LEFT_ROUNDED_CORNER, BOTTOM_RIGHT_ROUNDED_CORNER, TOP_LEFT_ROUNDED_CORNER,
+ TOP_RIGHT_ROUNDED_CORNER,
+};
+use crate::termwindow::ui::icons::{distro_to_icon, SvgIcon};
+use crate::termwindow::{DimensionContext, SshHostsAction, TermWindow, UIItemType};
+use crate::utilsprites::RenderMetrics;
+use config::keyassignment::KeyAssignment;
+use config::Dimension;
+use std::cell::{Ref, RefCell};
+use std::rc::Rc;
+use wezterm_term::{KeyCode, KeyModifiers, MouseEvent};
+use window::color::LinearRgba;
+
+/// Field order in the host form.
+const FIELD_LABEL: usize = 0;
+const FIELD_HOST: usize = 1;
+const FIELD_PORT: usize = 2;
+const FIELD_USER: usize = 3;
+const FIELD_IDENTITY: usize = 4;
+const FIELD_WORKSPACE: usize = 5;
+const FIELD_COUNT: usize = 6;
+
+const FIELD_LABELS: [&str; FIELD_COUNT] = [
+ "Name",
+ "Host",
+ "Port",
+ "User",
+ "Identity file",
+ "Workspace",
+];
+
+#[derive(Default, Clone)]
+struct HostForm {
+ /// Remote project id when editing an existing host.
+ editing: Option<String>,
+ /// Preserved spec when editing, so non-form fields survive a save.
+ original: Option<crate::project_sessions::SshHostSpec>,
+ fields: [String; FIELD_COUNT],
+ focused: usize,
+ /// Whether to run engine OS detection (`/etc/os-release`) after connecting.
+ detect_os: bool,
+ error: Option<String>,
+}
+
+enum View {
+ Grid,
+ Form(HostForm),
+}
+
+struct State {
+ view: View,
+ search: String,
+ selected: usize,
+}
+
+pub struct SshHostsModal {
+ element: RefCell<Option<Vec<ComputedElement>>>,
+ state: RefCell<State>,
+}
+
+impl SshHostsModal {
+ pub fn new() -> Self {
+ Self {
+ element: RefCell::new(None),
+ state: RefCell::new(State {
+ view: View::Grid,
+ search: String::new(),
+ selected: 0,
+ }),
+ }
+ }
+
+ /// Hosts (project_id, spec) filtered by the current search text.
+ fn filtered_hosts(search: &str) -> Vec<(String, crate::project_sessions::SshHostSpec)> {
+ let needle = search.trim().to_ascii_lowercase();
+ crate::project_sessions::list_hosts()
+ .into_iter()
+ .filter(|(_, spec)| {
+ if needle.is_empty() {
+ return true;
+ }
+ let hay = format!(
+ "{} {} {}",
+ spec.label,
+ spec.host,
+ spec.username.as_deref().unwrap_or("")
+ )
+ .to_ascii_lowercase();
+ hay.contains(&needle)
+ })
+ .collect()
+ }
+
+ // --- Grid interactions -------------------------------------------------
+
+ pub fn push_search_char(&self, c: char) {
+ let mut state = self.state.borrow_mut();
+ state.search.push(c);
+ state.selected = 0;
+ self.element.borrow_mut().take();
+ }
+
+ pub fn backspace_search(&self) {
+ let mut state = self.state.borrow_mut();
+ state.search.pop();
+ state.selected = 0;
+ self.element.borrow_mut().take();
+ }
+
+ pub fn move_selection(&self, delta: isize) {
+ let mut state = self.state.borrow_mut();
+ let count = Self::filtered_hosts(&state.search).len();
+ if count == 0 {
+ state.selected = 0;
+ } else {
+ let max = count - 1;
+ let next = (state.selected as isize + delta).clamp(0, max as isize);
+ state.selected = next as usize;
+ }
+ self.element.borrow_mut().take();
+ }
+
+ /// The remote project id of the currently highlighted host, if any.
+ pub fn selected_host_id(&self) -> Option<String> {
+ let state = self.state.borrow();
+ Self::filtered_hosts(&state.search)
+ .into_iter()
+ .nth(state.selected)
+ .map(|(id, _)| id)
+ }
+
+ // --- Form interactions -------------------------------------------------
+
+ pub fn enter_new_form(&self) {
+ let mut state = self.state.borrow_mut();
+ let mut form = HostForm::default();
+ form.fields[FIELD_PORT] = "22".to_string();
+ form.detect_os = true;
+ state.view = View::Form(form);
+ self.element.borrow_mut().take();
+ }
+
+ pub fn enter_edit_form(&self, project_id: &str) {
+ let Some(spec) = crate::project_sessions::host_spec(project_id) else {
+ return;
+ };
+ let mut fields: [String; FIELD_COUNT] = Default::default();
+ fields[FIELD_LABEL] = spec.label.clone();
+ fields[FIELD_HOST] = spec.host.clone();
+ fields[FIELD_PORT] = spec.port.map(|p| p.to_string()).unwrap_or_default();
+ fields[FIELD_USER] = spec.username.clone().unwrap_or_default();
+ fields[FIELD_IDENTITY] = spec.identity_file.clone().unwrap_or_default();
+ fields[FIELD_WORKSPACE] = spec.default_workspace.clone().unwrap_or_default();
+ let mut state = self.state.borrow_mut();
+ let detect_os = spec.detect_os;
+ state.view = View::Form(HostForm {
+ editing: Some(project_id.to_string()),
+ original: Some(spec),
+ fields,
+ focused: FIELD_HOST,
+ detect_os,
+ error: None,
+ });
+ self.element.borrow_mut().take();
+ }
+
+ pub fn cancel_to_grid(&self) {
+ let mut state = self.state.borrow_mut();
+ state.view = View::Grid;
+ self.element.borrow_mut().take();
+ }
+
+ pub fn toggle_detect(&self) {
+ let mut state = self.state.borrow_mut();
+ if let View::Form(form) = &mut state.view {
+ form.detect_os = !form.detect_os;
+ }
+ self.element.borrow_mut().take();
+ }
+
+ pub fn focus_field(&self, idx: usize) {
+ let mut state = self.state.borrow_mut();
+ if let View::Form(form) = &mut state.view {
+ form.focused = idx.min(FIELD_COUNT - 1);
+ }
+ self.element.borrow_mut().take();
+ }
+
+ pub fn focus_step(&self, delta: isize) {
+ let mut state = self.state.borrow_mut();
+ if let View::Form(form) = &mut state.view {
+ let next = (form.focused as isize + delta).rem_euclid(FIELD_COUNT as isize);
+ form.focused = next as usize;
+ }
+ self.element.borrow_mut().take();
+ }
+
+ pub fn form_push_char(&self, c: char) {
+ let mut state = self.state.borrow_mut();
+ if let View::Form(form) = &mut state.view {
+ form.fields[form.focused].push(c);
+ form.error = None;
+ }
+ self.element.borrow_mut().take();
+ }
+
+ pub fn form_backspace(&self) {
+ let mut state = self.state.borrow_mut();
+ if let View::Form(form) = &mut state.view {
+ form.fields[form.focused].pop();
+ form.error = None;
+ }
+ self.element.borrow_mut().take();
+ }
+
+ pub fn is_form(&self) -> bool {
+ matches!(self.state.borrow().view, View::Form(_))
+ }
+
+ /// Validate the form and create/update the host. On success returns the
+ /// remote project id and switches back to the grid; on error records the
+ /// message and stays on the form.
+ pub fn persist_form(&self) -> Option<String> {
+ let mut state = self.state.borrow_mut();
+ let View::Form(form) = &mut state.view else {
+ return None;
+ };
+
+ let host = form.fields[FIELD_HOST].trim().to_string();
+ if host.is_empty() {
+ form.error = Some("Host is required".to_string());
+ self.element.borrow_mut().take();
+ return None;
+ }
+ let port = match form.fields[FIELD_PORT].trim() {
+ "" => None,
+ value => match value.parse::<u16>() {
+ Ok(p) => Some(p),
+ Err(_) => {
+ form.error = Some("Port must be a number".to_string());
+ self.element.borrow_mut().take();
+ return None;
+ }
+ },
+ };
+
+ let opt = |s: &str| {
+ let t = s.trim();
+ (!t.is_empty()).then(|| t.to_string())
+ };
+ let label = match opt(&form.fields[FIELD_LABEL]) {
+ Some(l) => l,
+ None => host.clone(),
+ };
+
+ let mut spec = form.original.clone().unwrap_or_else(|| {
+ crate::project_sessions::SshHostSpec {
+ label: label.clone(),
+ host: host.clone(),
+ port,
+ username: None,
+ identity_file: None,
+ ssh_options: Default::default(),
+ multiplexing: true,
+ default_workspace: None,
+ detect_os: true,
+ detected_distro: None,
+ }
+ });
+ spec.label = label;
+ spec.host = host;
+ spec.port = port;
+ spec.username = opt(&form.fields[FIELD_USER]);
+ spec.identity_file = opt(&form.fields[FIELD_IDENTITY]);
+ spec.default_workspace = opt(&form.fields[FIELD_WORKSPACE]);
+ spec.detect_os = form.detect_os;
+
+ let project_id = match &form.editing {
+ Some(id) => {
+ crate::project_sessions::update_host(id, spec);
+ id.clone()
+ }
+ None => crate::project_sessions::create_host(spec),
+ };
+
+ state.view = View::Grid;
+ self.element.borrow_mut().take();
+ Some(project_id)
+ }
+
+ // --- Rendering ---------------------------------------------------------
+
+ fn compute(&self, term_window: &mut TermWindow) -> anyhow::Result<Vec<ComputedElement>> {
+ let font = term_window
+ .fonts
+ .command_palette_font()
+ .expect("to resolve command palette font");
+ let metrics = RenderMetrics::with_font_metrics(&font.metrics());
+
+ let bg_linear = term_window.config.command_palette_bg_color.to_linear();
+ let bg: InheritableColor = bg_linear.into();
+ let fg: InheritableColor = term_window
+ .config
+ .command_palette_fg_color
+ .to_linear()
+ .into();
+
+ let state = self.state.borrow();
+ let mut children: Vec<Element> = vec![];
+
+ match &state.view {
+ View::Grid => {
+ children.push(
+ heading(&font, "SSH Hosts").display(DisplayType::Block),
+ );
+ children.push(
+ Element::new(
+ &font,
+ ElementContent::Text(format!("Search: {}_", state.search)),
+ )
+ .display(DisplayType::Block)
+ .colors(text_colors(fg.clone())),
+ );
+
+ // "+ New Host" action row.
+ children.push(
+ action_row(
+ &font,
+ SvgIcon::Plus,
+ "New Host".to_string(),
+ String::new(),
+ UIItemType::SshHosts(SshHostsAction::New),
+ false,
+ bg.clone(),
+ fg.clone(),
+ ),
+ );
+
+ let hosts = Self::filtered_hosts(&state.search);
+ if hosts.is_empty() {
+ children.push(
+ Element::new(
+ &font,
+ ElementContent::Text(
+ "No SSH hosts yet. Click \"New Host\" to add one.".to_string(),
+ ),
+ )
+ .display(DisplayType::Block)
+ .colors(text_colors(fg.clone())),
+ );
+ } else {
+ for (idx, (id, spec)) in hosts.iter().enumerate() {
+ let subtitle = host_subtitle(spec);
+ children.push(host_card(
+ &font,
+ id,
+ &spec.label,
+ &subtitle,
+ spec.detected_distro.as_deref(),
+ idx == state.selected,
+ bg.clone(),
+ fg.clone(),
+ ));
+ }
+ }
+ }
+ View::Form(form) => {
+ let title = if form.editing.is_some() {
+ "Edit Host"
+ } else {
+ "New Host"
+ };
+ children.push(heading(&font, title).display(DisplayType::Block));
+
+ for (idx, label) in FIELD_LABELS.iter().enumerate() {
+ let value = &form.fields[idx];
+ let focused = idx == form.focused;
+ let shown = if focused {
+ format!("{value}_")
+ } else {
+ value.clone()
+ };
+ let line = format!("{label:<14}{shown}");
+ children.push(
+ Element::new(&font, ElementContent::Text(line))
+ .display(DisplayType::Block)
+ .item_type(UIItemType::SshHosts(SshHostsAction::FocusField(idx)))
+ .colors(if focused {
+ selected_colors(bg.clone(), fg.clone())
+ } else {
+ text_colors(fg.clone())
+ })
+ .padding(cells(0.25, 0.25, 0.1, 0.1))
+ .min_width(Some(Dimension::Percent(1.))),
+ );
+ }
+
+ let detect_label = format!(
+ "Detect OS on connect: {}",
+ if form.detect_os { "ON" } else { "OFF" }
+ );
+ children.push(
+ Element::new(&font, ElementContent::Text(detect_label))
+ .display(DisplayType::Block)
+ .item_type(UIItemType::SshHosts(SshHostsAction::ToggleDetect))
+ .colors(text_colors(fg.clone()))
+ .padding(cells(0.25, 0.25, 0.3, 0.1))
+ .min_width(Some(Dimension::Percent(1.))),
+ );
+
+ if let Some(err) = &form.error {
+ children.push(
+ Element::new(&font, ElementContent::Text(format!("⚠ {err}")))
+ .display(DisplayType::Block)
+ .colors(text_colors(fg.clone())),
+ );
+ }
+
+ // Button row.
+ let buttons = vec![
+ button(
+ &font,
+ "Save",
+ UIItemType::SshHosts(SshHostsAction::Save),
+ bg.clone(),
+ fg.clone(),
+ ),
+ button(
+ &font,
+ "Save & Connect",
+ UIItemType::SshHosts(SshHostsAction::SaveAndConnect),
+ bg.clone(),
+ fg.clone(),
+ ),
+ button(
+ &font,
+ "Cancel",
+ UIItemType::SshHosts(SshHostsAction::Cancel),
+ bg.clone(),
+ fg.clone(),
+ ),
+ ];
+ children.push(
+ Element::new(&font, ElementContent::Children(buttons))
+ .display(DisplayType::Block)
+ .padding(cells(0.25, 0.25, 0.4, 0.1)),
+ );
+ }
+ }
+
+ let dimensions = term_window.dimensions;
+ let size = term_window.terminal_size;
+ let (padding_left, padding_top) = term_window.padding_left_top();
+ let top_bar_height = if term_window.show_tab_bar && !term_window.config.tab_bar_at_bottom {
+ term_window.tab_bar_pixel_height().unwrap_or(0.)
+ } else {
+ 0.
+ };
+ let border = term_window.get_os_border();
+ let top_pixel_y = top_bar_height + padding_top + border.top.get() as f32;
+
+ let desired_width = (size.cols * 2 / 3).max(80).min(size.cols);
+ let avail_pixel_width =
+ size.cols as f32 * term_window.render_metrics.cell_size.width as f32;
+ let desired_pixel_width =
+ desired_width as f32 * term_window.render_metrics.cell_size.width as f32;
+
+ let element = Element::new(&font, ElementContent::Children(children))
+ .colors(ElementColors {
+ border: BorderColor::new(bg_linear),
+ bg: bg.clone(),
+ text: fg.clone(),
+ })
+ .margin(cells(0.5, 0.5, 0.5, 0.5))
+ .padding(cells(0.75, 0.75, 0.5, 0.5))
+ .border(BoxDimension::new(Dimension::Pixels(1.)))
+ .border_corners(Some(rounded_corners()))
+ .min_width(Some(Dimension::Pixels(desired_pixel_width)));
+
+ let x_adjust = ((avail_pixel_width - padding_left) - desired_pixel_width) / 2.;
+
+ let computed = term_window.compute_element(
+ &LayoutContext {
+ height: DimensionContext {
+ dpi: dimensions.dpi as f32,
+ pixel_max: dimensions.pixel_height as f32,
+ pixel_cell: metrics.cell_size.height as f32,
+ },
+ width: DimensionContext {
+ dpi: dimensions.dpi as f32,
+ pixel_max: dimensions.pixel_width as f32,
+ pixel_cell: metrics.cell_size.width as f32,
+ },
+ bounds: euclid::rect(
+ padding_left + x_adjust.max(0.),
+ top_pixel_y,
+ desired_pixel_width,
+ size.rows as f32 * term_window.render_metrics.cell_size.height as f32,
+ ),
+ metrics: &metrics,
+ gl_state: term_window.render_state.as_ref().unwrap(),
+ zindex: 100,
+ },
+ &element,
+ )?;
+
+ Ok(vec![computed])
+ }
+}
+
+impl Modal for SshHostsModal {
+ fn perform_assignment(
+ &self,
+ _assignment: &KeyAssignment,
+ _term_window: &mut TermWindow,
+ ) -> bool {
+ false
+ }
+
+ fn mouse_event(&self, _event: MouseEvent, _term_window: &mut TermWindow) -> anyhow::Result<()> {
+ // Clicks are routed via UIItemType::SshHosts in mouseevent.rs.
+ Ok(())
+ }
+
+ fn key_down(
+ &self,
+ key: KeyCode,
+ mods: KeyModifiers,
+ term_window: &mut TermWindow,
+ ) -> anyhow::Result<bool> {
+ let in_form = self.is_form();
+ match (key, mods) {
+ (KeyCode::Escape, _) => {
+ if in_form {
+ self.cancel_to_grid();
+ } else {
+ term_window.cancel_modal();
+ return Ok(true);
+ }
+ }
+ (KeyCode::Tab, KeyModifiers::NONE) | (KeyCode::DownArrow, KeyModifiers::NONE) => {
+ if in_form {
+ self.focus_step(1);
+ } else {
+ self.move_selection(1);
+ }
+ }
+ (KeyCode::Tab, KeyModifiers::SHIFT) | (KeyCode::UpArrow, KeyModifiers::NONE) => {
+ if in_form {
+ self.focus_step(-1);
+ } else {
+ self.move_selection(-1);
+ }
+ }
+ (KeyCode::Enter, _) => {
+ if in_form {
+ self.persist_form();
+ } else if let Some(id) = self.selected_host_id() {
+ term_window.cancel_modal();
+ term_window.connect_ssh_host(id, None);
+ return Ok(true);
+ }
+ }
+ (KeyCode::Backspace, _) => {
+ if in_form {
+ self.form_backspace();
+ } else {
+ self.backspace_search();
+ }
+ }
+ (KeyCode::Char(c), KeyModifiers::NONE) | (KeyCode::Char(c), KeyModifiers::SHIFT) => {
+ if in_form {
+ self.form_push_char(c);
+ } else {
+ self.push_search_char(c);
+ }
+ }
+ _ => return Ok(false),
+ }
+ term_window.invalidate_modal();
+ Ok(true)
+ }
+
+ fn computed_element(
+ &self,
+ term_window: &mut TermWindow,
+ ) -> anyhow::Result<Ref<'_, [ComputedElement]>> {
+ if self.element.borrow().is_none() {
+ let computed = self.compute(term_window)?;
+ self.element.borrow_mut().replace(computed);
+ }
+ Ok(Ref::map(self.element.borrow(), |v| {
+ v.as_ref().unwrap().as_slice()
+ }))
+ }
+
+ fn reconfigure(&self, _term_window: &mut TermWindow) {
+ self.element.borrow_mut().take();
+ }
+}
+
+// --- element helpers -------------------------------------------------------
+
+fn cells(left: f64, right: f64, top: f64, bottom: f64) -> BoxDimension {
+ BoxDimension {
+ left: Dimension::Cells(left as f32),
+ right: Dimension::Cells(right as f32),
+ top: Dimension::Cells(top as f32),
+ bottom: Dimension::Cells(bottom as f32),
+ }
+}
+
+fn rounded_corners() -> Corners {
+ Corners {
+ top_left: SizedPoly {
+ width: Dimension::Cells(0.3),
+ height: Dimension::Cells(0.3),
+ poly: TOP_LEFT_ROUNDED_CORNER,
+ },
+ top_right: SizedPoly {
+ width: Dimension::Cells(0.3),
+ height: Dimension::Cells(0.3),
+ poly: TOP_RIGHT_ROUNDED_CORNER,
+ },
+ bottom_left: SizedPoly {
+ width: Dimension::Cells(0.3),
+ height: Dimension::Cells(0.3),
+ poly: BOTTOM_LEFT_ROUNDED_CORNER,
+ },
+ bottom_right: SizedPoly {
+ width: Dimension::Cells(0.3),
+ height: Dimension::Cells(0.3),
+ poly: BOTTOM_RIGHT_ROUNDED_CORNER,
+ },
+ }
+}
+
+fn text_colors(fg: InheritableColor) -> ElementColors {
+ ElementColors {
+ border: BorderColor::default(),
+ bg: LinearRgba::TRANSPARENT.into(),
+ text: fg,
+ }
+}
+
+fn selected_colors(bg: InheritableColor, fg: InheritableColor) -> ElementColors {
+ ElementColors {
+ border: BorderColor::default(),
+ bg: fg,
+ text: bg,
+ }
+}
+
+fn heading(font: &Rc<wezterm_font::LoadedFont>, text: &str) -> Element {
+ Element::new(font, ElementContent::Text(text.to_string()))
+ .padding(cells(0.0, 0.0, 0.0, 0.4))
+}
+
+fn host_subtitle(spec: &crate::project_sessions::SshHostSpec) -> String {
+ let mut parts = vec!["ssh".to_string()];
+ if let Some(user) = &spec.username {
+ if !user.is_empty() {
+ parts.push(user.clone());
+ }
+ }
+ parts.push(spec.host.clone());
+ parts.join(", ")
+}
+
+#[allow(clippy::too_many_arguments)]
+fn action_row(
+ font: &Rc<wezterm_font::LoadedFont>,
+ icon: SvgIcon,
+ label: String,
+ _subtitle: String,
+ item: UIItemType,
+ selected: bool,
+ bg: InheritableColor,
+ fg: InheritableColor,
+) -> Element {
+ let row = vec![
+ Element::new(
+ font,
+ ElementContent::Icon {
+ icon,
+ size: Dimension::Cells(1.2),
+ },
+ )
+ .min_width(Some(Dimension::Cells(2.))),
+ Element::new(font, ElementContent::Text(label)),
+ ];
+ Element::new(font, ElementContent::Children(row))
+ .display(DisplayType::Block)
+ .item_type(item)
+ .colors(if selected {
+ selected_colors(bg, fg)
+ } else {
+ text_colors(fg)
+ })
+ .padding(cells(0.25, 0.25, 0.2, 0.2))
+ .min_width(Some(Dimension::Percent(1.)))
+}
+
+#[allow(clippy::too_many_arguments)]
+fn host_card(
+ font: &Rc<wezterm_font::LoadedFont>,
+ project_id: &str,
+ label: &str,
+ subtitle: &str,
+ distro: Option<&str>,
+ selected: bool,
+ bg: InheritableColor,
+ fg: InheritableColor,
+) -> Element {
+ // Show the detected OS brand logo when known, otherwise a generic server.
+ let icon_el = match distro.and_then(distro_to_icon) {
+ Some(brand) => Element::new(
+ font,
+ ElementContent::BrandIcon {
+ icon: brand,
+ size: Dimension::Cells(1.4),
+ },
+ ),
+ None => Element::new(
+ font,
+ ElementContent::Icon {
+ icon: SvgIcon::Server,
+ size: Dimension::Cells(1.4),
+ },
+ ),
+ }
+ .min_width(Some(Dimension::Cells(2.5)));
+
+ let text_col = vec![
+ Element::new(font, ElementContent::Text(label.to_string())).display(DisplayType::Block),
+ Element::new(font, ElementContent::Text(subtitle.to_string())).display(DisplayType::Block),
+ ];
+ let edit = Element::new(font, ElementContent::Text(" Edit".to_string()))
+ .float(Float::Right)
+ .item_type(UIItemType::SshHosts(SshHostsAction::Edit(
+ project_id.to_string(),
+ )));
+ let delete = Element::new(font, ElementContent::Text(" Delete".to_string()))
+ .float(Float::Right)
+ .item_type(UIItemType::SshHosts(SshHostsAction::Delete(
+ project_id.to_string(),
+ )));
+ let row = vec![
+ icon_el,
+ Element::new(font, ElementContent::Children(text_col)),
+ delete,
+ edit,
+ ];
+ Element::new(font, ElementContent::Children(row))
+ .display(DisplayType::Block)
+ .item_type(UIItemType::SshHosts(SshHostsAction::Connect(
+ project_id.to_string(),
+ )))
+ .colors(if selected {
+ selected_colors(bg, fg)
+ } else {
+ text_colors(fg)
+ })
+ .padding(cells(0.25, 0.25, 0.25, 0.25))
+ .min_width(Some(Dimension::Percent(1.)))
+}
+
+fn button(
+ font: &Rc<wezterm_font::LoadedFont>,
+ label: &str,
+ item: UIItemType,
+ bg: InheritableColor,
+ fg: InheritableColor,
+) -> Element {
+ Element::new(font, ElementContent::Text(format!("[ {label} ]")))
+ .item_type(item)
+ .colors(text_colors(fg.clone()))
+ .hover_colors(Some(selected_colors(bg, fg)))
+ .padding(cells(0.5, 0.5, 0.1, 0.1))
+}
diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rs
index 6035bdb9..253a59c1 100644
--- a/wezterm-gui/src/termwindow/ui/icons.rs
+++ b/wezterm-gui/src/termwindow/ui/icons.rs
@@ -34,6 +34,7 @@ pub enum SvgIcon {
Plus,
RotateCcw,
Search,
+ Server,
Settings,
SlidersHorizontal,
SlidersVertical,
@@ -112,6 +113,7 @@ impl SvgIcon {
include_bytes!("../../../../third_party/lucide/icons/rotate-ccw.svg")
}
Self::Search => include_bytes!("../../../../third_party/lucide/icons/search.svg"),
+ Self::Server => include_bytes!("../../../../third_party/lucide/icons/server.svg"),
Self::Settings => include_bytes!("../../../../third_party/lucide/icons/settings.svg"),
Self::SlidersHorizontal => {
include_bytes!("../../../../third_party/lucide/icons/sliders-horizontal.svg")
@@ -149,38 +151,179 @@ impl SvgIcon {
}
pub fn rasterize_with_rotation(self, size: usize, degrees: f32) -> Result<Image> {
- let size = size.max(1);
let svg = std::str::from_utf8(self.bytes()).context("SVG asset is not UTF-8")?;
+ // Lucide icons use `currentColor`; tint them white for the dark UI.
let svg = svg.replace("currentColor", "#ffffff");
- let tree = resvg::usvg::Tree::from_data(svg.as_bytes(), &resvg::usvg::Options::default())
- .context("parsing SVG icon")?;
- let svg_size = tree.size();
- let scale = (size as f32 / svg_size.width()).min(size as f32 / svg_size.height());
- let translate_x = (size as f32 - svg_size.width() * scale) / 2.0;
- let translate_y = (size as f32 - svg_size.height() * scale) / 2.0;
- let mut transform = resvg::tiny_skia::Transform::from_translate(translate_x, translate_y)
- .pre_scale(scale, scale);
- if degrees != 0.0 {
- transform = transform.post_rotate_at(degrees, size as f32 / 2.0, size as f32 / 2.0);
+ rasterize_svg_str(&svg, size, degrees)
+ }
+}
+
+/// Brand / product logos sourced from the `simple-icons` submodule
+/// (`third_party/simple-icons/icons/<slug>.svg`).
+///
+/// Unlike Lucide, simple-icons SVGs are a single fill-less `<path>` that
+/// defaults to black, and each brand has an official color. We inject that
+/// color as the path fill. Because many brands are black/near-black (GitHub,
+/// Anthropic, Apple, Rust, Debian) and would vanish on the dark UI, a brand
+/// color darker than [`MIN_BRAND_LUMA`] is rendered white instead.
+#[allow(dead_code)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum BrandIcon {
+ Alpine,
+ Anthropic,
+ Apple,
+ ArchLinux,
+ CentOS,
+ Claude,
+ Debian,
+ Docker,
+ Fedora,
+ Git,
+ GitHub,
+ Linux,
+ NixOS,
+ Proxmox,
+ RaspberryPi,
+ RedHat,
+ Ubuntu,
+}
+
+/// Brand colors darker than this perceived luminance (0..=255) are rendered
+/// white so they stay visible on ThinkTerm's dark chrome.
+const MIN_BRAND_LUMA: f32 = 40.0;
+
+impl BrandIcon {
+ pub fn bytes(self) -> &'static [u8] {
+ match self {
+ Self::Alpine => {
+ include_bytes!("../../../../third_party/simple-icons/icons/alpinelinux.svg")
+ }
+ Self::Anthropic => {
+ include_bytes!("../../../../third_party/simple-icons/icons/anthropic.svg")
+ }
+ Self::Apple => include_bytes!("../../../../third_party/simple-icons/icons/apple.svg"),
+ Self::ArchLinux => {
+ include_bytes!("../../../../third_party/simple-icons/icons/archlinux.svg")
+ }
+ Self::CentOS => include_bytes!("../../../../third_party/simple-icons/icons/centos.svg"),
+ Self::Claude => include_bytes!("../../../../third_party/simple-icons/icons/claude.svg"),
+ Self::Debian => include_bytes!("../../../../third_party/simple-icons/icons/debian.svg"),
+ Self::Docker => include_bytes!("../../../../third_party/simple-icons/icons/docker.svg"),
+ Self::Fedora => include_bytes!("../../../../third_party/simple-icons/icons/fedora.svg"),
+ Self::Git => include_bytes!("../../../../third_party/simple-icons/icons/git.svg"),
+ Self::GitHub => include_bytes!("../../../../third_party/simple-icons/icons/github.svg"),
+ Self::Linux => include_bytes!("../../../../third_party/simple-icons/icons/linux.svg"),
+ Self::NixOS => include_bytes!("../../../../third_party/simple-icons/icons/nixos.svg"),
+ Self::Proxmox => {
+ include_bytes!("../../../../third_party/simple-icons/icons/proxmox.svg")
+ }
+ Self::RaspberryPi => {
+ include_bytes!("../../../../third_party/simple-icons/icons/raspberrypi.svg")
+ }
+ Self::RedHat => include_bytes!("../../../../third_party/simple-icons/icons/redhat.svg"),
+ Self::Ubuntu => include_bytes!("../../../../third_party/simple-icons/icons/ubuntu.svg"),
+ }
+ }
+
+ /// Official brand color (sRGB) from `simple-icons/data/simple-icons.json`.
+ pub fn brand_color(self) -> (u8, u8, u8) {
+ match self {
+ Self::Alpine => (0x0D, 0x59, 0x7F),
+ Self::Anthropic => (0x19, 0x19, 0x19),
+ Self::Apple => (0x00, 0x00, 0x00),
+ Self::ArchLinux => (0x17, 0x93, 0xD1),
+ Self::CentOS => (0x26, 0x25, 0x77),
+ Self::Claude => (0xD9, 0x77, 0x57),
+ Self::Debian => (0xA8, 0x1D, 0x33),
+ Self::Docker => (0x24, 0x96, 0xED),
+ Self::Fedora => (0x51, 0xA2, 0xDA),
+ Self::Git => (0xF0, 0x3C, 0x2E),
+ Self::GitHub => (0x18, 0x17, 0x17),
+ Self::Linux => (0xFC, 0xC6, 0x24),
+ Self::NixOS => (0x52, 0x77, 0xC3),
+ Self::Proxmox => (0xE5, 0x70, 0x00),
+ Self::RaspberryPi => (0xA2, 0x28, 0x46),
+ Self::RedHat => (0xEE, 0x00, 0x00),
+ Self::Ubuntu => (0xE9, 0x54, 0x20),
+ }
+ }
+
+ /// Brand color, falling back to white when too dark for the dark UI.
+ pub fn display_color(self) -> (u8, u8, u8) {
+ let (r, g, b) = self.brand_color();
+ let luma = 0.2126 * r as f32 + 0.7152 * g as f32 + 0.0722 * b as f32;
+ if luma < MIN_BRAND_LUMA {
+ (0xFF, 0xFF, 0xFF)
+ } else {
+ (r, g, b)
}
+ }
- let mut pixmap = resvg::tiny_skia::Pixmap::new(size as u32, size as u32)
- .with_context(|| format!("allocating {size}px SVG icon pixmap"))?;
- resvg::render(&tree, transform, &mut pixmap.as_mut());
+ pub fn rasterize(self, size: usize) -> Result<Image> {
+ let svg = std::str::from_utf8(self.bytes()).context("brand SVG asset is not UTF-8")?;
+ let (r, g, b) = self.display_color();
+ let fill = format!("#{r:02X}{g:02X}{b:02X}");
+ // simple-icons paths carry no fill; inject the brand color on the
+ // single `<path ` element so resvg renders it in color.
+ let svg = svg.replacen("<path ", &format!("<path fill=\"{fill}\" "), 1);
+ rasterize_svg_str(&svg, size, 0.0)
+ }
+}
- Ok(Image::from_raw(size, size, pixmap.take()))
+/// Map an `/etc/os-release` `ID` (or a value from `ID_LIKE`) to a brand icon.
+/// Returns `None` when the distro is unknown so callers can fall back to a
+/// generic server icon.
+pub fn distro_to_icon(id: &str) -> Option<BrandIcon> {
+ match id.trim().to_ascii_lowercase().as_str() {
+ "ubuntu" => Some(BrandIcon::Ubuntu),
+ "debian" => Some(BrandIcon::Debian),
+ "raspbian" => Some(BrandIcon::RaspberryPi),
+ "fedora" => Some(BrandIcon::Fedora),
+ "arch" | "archlinux" | "arch-linux" => Some(BrandIcon::ArchLinux),
+ "alpine" => Some(BrandIcon::Alpine),
+ "rhel" | "redhat" | "red hat" => Some(BrandIcon::RedHat),
+ "centos" => Some(BrandIcon::CentOS),
+ "nixos" => Some(BrandIcon::NixOS),
+ "proxmox" | "pve" => Some(BrandIcon::Proxmox),
+ "darwin" | "macos" => Some(BrandIcon::Apple),
+ "linux" => Some(BrandIcon::Linux),
+ _ => None,
}
}
+/// Shared SVG -> RGBA raster path used by both [`SvgIcon`] and [`BrandIcon`].
+/// The icon is scaled to fit and centered within a `size`×`size` pixmap.
+fn rasterize_svg_str(svg: &str, size: usize, degrees: f32) -> Result<Image> {
+ let size = size.max(1);
+ let tree = resvg::usvg::Tree::from_data(svg.as_bytes(), &resvg::usvg::Options::default())
+ .context("parsing SVG icon")?;
+ let svg_size = tree.size();
+ let scale = (size as f32 / svg_size.width()).min(size as f32 / svg_size.height());
+ let translate_x = (size as f32 - svg_size.width() * scale) / 2.0;
+ let translate_y = (size as f32 - svg_size.height() * scale) / 2.0;
+ let mut transform = resvg::tiny_skia::Transform::from_translate(translate_x, translate_y)
+ .pre_scale(scale, scale);
+ if degrees != 0.0 {
+ transform = transform.post_rotate_at(degrees, size as f32 / 2.0, size as f32 / 2.0);
+ }
+
+ let mut pixmap = resvg::tiny_skia::Pixmap::new(size as u32, size as u32)
+ .with_context(|| format!("allocating {size}px SVG icon pixmap"))?;
+ resvg::render(&tree, transform, &mut pixmap.as_mut());
+
+ Ok(Image::from_raw(size, size, pixmap.take()))
+}
+
#[cfg(test)]
mod tests {
- use super::SvgIcon;
+ use super::{BrandIcon, SvgIcon};
#[test]
fn svg_icons_rasterize() {
for icon in [
SvgIcon::Archive,
SvgIcon::Bell,
+ SvgIcon::Server,
SvgIcon::ExternalLink,
SvgIcon::ChevronDown,
SvgIcon::ChevronRight,
@@ -227,4 +370,40 @@ mod tests {
assert!(data.iter().any(|value| *value != 0));
}
}
+
+ #[test]
+ fn brand_icons_rasterize() {
+ for icon in [
+ BrandIcon::Alpine,
+ BrandIcon::Anthropic,
+ BrandIcon::Apple,
+ BrandIcon::ArchLinux,
+ BrandIcon::CentOS,
+ BrandIcon::Claude,
+ BrandIcon::Debian,
+ BrandIcon::Docker,
+ BrandIcon::Fedora,
+ BrandIcon::Git,
+ BrandIcon::GitHub,
+ BrandIcon::Linux,
+ BrandIcon::NixOS,
+ BrandIcon::Proxmox,
+ BrandIcon::RaspberryPi,
+ BrandIcon::RedHat,
+ BrandIcon::Ubuntu,
+ ] {
+ let data: Vec<u8> = icon.rasterize(24).unwrap().into();
+ assert_eq!(data.len(), 24 * 24 * 4);
+ // The brand color must actually paint some non-transparent pixels.
+ assert!(data.iter().any(|value| *value != 0), "{:?} rendered empty", icon);
+ }
+ }
+
+ #[test]
+ fn dark_brands_fall_back_to_white() {
+ // GitHub (#181717) is too dark for the dark UI and must render white.
+ assert_eq!(BrandIcon::GitHub.display_color(), (0xFF, 0xFF, 0xFF));
+ // Ubuntu (#E95420) keeps its brand color.
+ assert_eq!(BrandIcon::Ubuntu.display_color(), (0xE9, 0x54, 0x20));
+ }
}
diff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rs
index cff154c9..3a78fb82 100644
--- a/wezterm-gui/src/termwindow/ui/sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs
@@ -5,7 +5,7 @@ use crate::termwindow::render::corners::{
BOTTOM_LEFT_ROUNDED_CORNER, BOTTOM_RIGHT_ROUNDED_CORNER, TOP_LEFT_ROUNDED_CORNER,
TOP_RIGHT_ROUNDED_CORNER,
};
-use crate::termwindow::ui::icons::SvgIcon;
+use crate::termwindow::ui::icons::{distro_to_icon, BrandIcon, SvgIcon};
use crate::termwindow::ui::status_icon::{split_leading_legacy_progress_marker, UiStatusKind};
use crate::termwindow::ui::tokens::{
CAPSULE_BORDER_WIDTH, MACOS_TITLEBAR_CONTENT_TOP_INSET, SIDEBAR_ICON_GAP, SIDEBAR_INSET,
@@ -1139,18 +1139,39 @@ impl crate::TermWindow {
disclosure_size,
muted_fg,
)?;
- self.paint_sidebar_icon(
- layers,
- if project.sessions_collapsed {
+ let remote_brand = if project.is_remote {
+ project.distro.as_deref().and_then(distro_to_icon)
+ } else {
+ None
+ };
+ if let Some(brand) = remote_brand {
+ // Detected remote OS: show its brand logo in full color.
+ self.paint_sidebar_brand_icon(
+ layers,
+ brand,
+ project_icon_x,
+ icon_y,
+ icon_size,
+ )?;
+ } else {
+ let project_icon = if project.is_remote {
+ // Remote host without a detected OS: a globe marks it as
+ // distinct from local folder projects in the mixed list.
+ SvgIcon::Globe
+ } else if project.sessions_collapsed {
SvgIcon::Folder
} else {
SvgIcon::FolderOpen
- },
- project_icon_x,
- icon_y,
- icon_size,
- muted_fg,
- )?;
+ };
+ self.paint_sidebar_icon(
+ layers,
+ project_icon,
+ project_icon_x,
+ icon_y,
+ icon_size,
+ muted_fg,
+ )?;
+ }
let project_title = self.sidebar_project_title(&project.id, &project.name);
self.paint_sidebar_text(
layers,
@@ -2038,4 +2059,38 @@ impl crate::TermWindow {
Ok(())
}
+
+ /// Paint a full-color brand/OS logo (the brand color is baked into the
+ /// sprite, so unlike [`Self::paint_sidebar_icon`] it is not tinted).
+ fn paint_sidebar_brand_icon(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ icon: BrandIcon,
+ x: usize,
+ y: usize,
+ size: usize,
+ ) -> anyhow::Result<()> {
+ let left_offset = self.dimensions.pixel_width as f32 / 2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / 2.0;
+ let gl_state = self.render_state.as_ref().unwrap();
+ let sprite = gl_state
+ .glyph_cache
+ .borrow_mut()
+ .cached_brand_icon(icon, size)?
+ .texture_coords();
+
+ let mut quad = layers.allocate(2)?;
+ quad.set_position(
+ x as f32 - left_offset,
+ y as f32 - top_offset,
+ x as f32 + size as f32 - left_offset,
+ y as f32 + size as f32 - top_offset,
+ );
+ quad.set_texture(sprite);
+ quad.set_hsv(None);
+ quad.set_has_color(true);
+ quad.set_fg_color(LinearRgba::with_components(1.0, 1.0, 1.0, 1.0));
+
+ Ok(())
+ }
}