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 encrypted SSH host store and content views

RoversX210fbc7c6738
diff --git a/Cargo.lock b/Cargo.lock
index 64a41c38..6257097b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6975,6 +6975,7 @@ name = "wezterm-gui"
version = "0.1.0"
dependencies = [
"anyhow",
+ "base64 0.22.1",
"benchmarking",
"bitflags 1.3.2",
"bytemuck",
@@ -7011,6 +7012,7 @@ dependencies = [
"mux",
"mux-lua",
"nucleo-matcher",
+ "openssl",
"ordered-float 4.6.0",
"parking_lot",
"portable-pty",
diff --git a/mux/src/ssh.rs b/mux/src/ssh.rs
index 66825cf0..8455891a 100644
--- a/mux/src/ssh.rs
+++ b/mux/src/ssh.rs
@@ -182,6 +182,8 @@ pub struct RemoteSshDomain {
dom: SshDomain,
id: DomainId,
name: String,
+ /// Optional stored password used to auto-answer the first password prompt.
+ password: Option<String>,
}
pub fn ssh_domain_to_ssh_config(ssh_dom: &SshDomain) -> anyhow::Result<ConfigMap> {
@@ -244,12 +246,23 @@ fn parse_os_release_id(text: &str) -> Option<String> {
impl RemoteSshDomain {
pub fn with_ssh_domain(dom: &SshDomain) -> anyhow::Result<Self> {
+ Self::with_ssh_domain_and_password(dom, None)
+ }
+
+ /// Like [`Self::with_ssh_domain`] but stores a password used to
+ /// auto-answer the first interactive password prompt (ThinkTerm host
+ /// manager). The password is held in memory only on this domain.
+ pub fn with_ssh_domain_and_password(
+ dom: &SshDomain,
+ password: Option<String>,
+ ) -> anyhow::Result<Self> {
let id = alloc_domain_id();
Ok(Self {
id,
name: dom.name.clone(),
session: Mutex::new(None),
dom: dom.clone(),
+ password,
})
}
@@ -362,6 +375,7 @@ impl RemoteSshDomain {
command_line: Option<String>,
env: HashMap<String, String>,
size: TerminalSize,
+ password: Option<String>,
) -> anyhow::Result<StartNewSessionResult> {
let (session, events) = Session::connect(self.ssh_config().context("obtain ssh config")?)
.context("connect to ssh server")?;
@@ -433,6 +447,7 @@ impl RemoteSshDomain {
size,
command_line,
env,
+ password,
) {
let _ = write!(stdout_write, "{:#}", err);
log::error!("Failed to connect ssh: {:#}", err);
@@ -463,6 +478,7 @@ fn connect_ssh_session(
size: Arc<Mutex<TerminalSize>>,
command_line: Option<String>,
env: HashMap<String, String>,
+ mut password: Option<String>,
) -> anyhow::Result<()> {
struct StdoutShim<'a> {
size: Arc<Mutex<TerminalSize>>,
@@ -660,6 +676,17 @@ fn connect_ssh_session(
for line in &prompt_lines {
shim.output_line(line)?;
}
+ // Auto-answer the first password (non-echo) prompt with a
+ // stored password, if any. Only once: a wrong stored
+ // password then falls back to interactive entry so the user
+ // can correct it instead of looping.
+ if !prompt.echo {
+ if let Some(stored) = password.take() {
+ shim.output_line(editor_prompt)?;
+ answers.push(stored);
+ continue;
+ }
+ }
let mut editor = LineEditor::new(&mut shim);
let mut host = PasswordPromptHost::default();
editor.set_prompt(editor_prompt);
@@ -775,7 +802,8 @@ impl Domain for RemoteSshDomain {
{
// Session died (perhaps they closed the initial tab?)
// So we'll try making a new one
- self.start_new_session(command_line, env, size).await?
+ self.start_new_session(command_line, env, size, self.password.clone())
+ .await?
} else {
log::error!("{err:#?}");
return Err(err);
@@ -783,7 +811,8 @@ impl Domain for RemoteSshDomain {
}
}
} else {
- self.start_new_session(command_line, env, size).await?
+ self.start_new_session(command_line, env, size, self.password.clone())
+ .await?
};
// Wrap up the pty etc. in a LocalPane. That allows for
diff --git a/wezterm-font/Cargo.toml b/wezterm-font/Cargo.toml
index f6e7ef20..4df70894 100644
--- a/wezterm-font/Cargo.toml
+++ b/wezterm-font/Cargo.toml
@@ -8,6 +8,7 @@ publish = false
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[features]
+cargo-clippy = []
vendor-jetbrains = []
vendor-roboto = []
vendor-noto-emoji = []
diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.toml
index 91e01839..5011962c 100644
--- a/wezterm-gui/Cargo.toml
+++ b/wezterm-gui/Cargo.toml
@@ -10,6 +10,7 @@ publish = false
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[features]
+cargo-clippy = []
default = ["vendored-fonts", "wayland"]
wayland = ["window/wayland"]
distro-defaults = ["config/distro-defaults"]
@@ -35,6 +36,7 @@ embed-resource.workspace = true
[dependencies]
anyhow.workspace = true
+base64.workspace = true
bitflags.workspace = true
bytemuck.workspace = true
chrono.workspace = true
@@ -66,6 +68,7 @@ mlua = {workspace=true, features=["send", "serialize"]}
mux-lua.workspace = true
mux.workspace = true
nucleo-matcher.workspace = true
+openssl.workspace = true
ordered-float.workspace = true
parking_lot.workspace = true
portable-pty = { workspace=true, features = ["serde_support"]}
diff --git a/wezterm-gui/src/customglyph.rs b/wezterm-gui/src/customglyph.rs
index a57b5490..0b1f7661 100644
--- a/wezterm-gui/src/customglyph.rs
+++ b/wezterm-gui/src/customglyph.rs
@@ -5018,6 +5018,13 @@ impl GlyphCache {
blend_mode: BlendMode,
) {
let (width, height) = buffer.image_dimensions();
+ // A degenerate (zero-area) buffer can occur when a rounded-rect corner
+ // is requested at sub-pixel size (e.g. a tab dragged very small).
+ // `PixmapMut::from_bytes` returns None for 0 dimensions; skip rather
+ // than panic.
+ if width == 0 || height == 0 {
+ return;
+ }
let mut pixmap =
PixmapMut::from_bytes(buffer.pixel_data_slice_mut(), width as u32, height as u32)
.expect("make pixmap from existing bitmap");
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index 94e4379c..3c74fcb0 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -50,6 +50,7 @@ mod renderstate;
mod resize_increment_calculator;
mod scripting;
mod scrollbar;
+mod secret;
mod selection;
mod settings_window;
mod shapecache;
diff --git a/wezterm-gui/src/project_sessions.rs b/wezterm-gui/src/project_sessions.rs
index b76a6558..21472b9c 100644
--- a/wezterm-gui/src/project_sessions.rs
+++ b/wezterm-gui/src/project_sessions.rs
@@ -35,48 +35,6 @@ 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)]
@@ -162,6 +120,7 @@ pub enum SessionWorkStatus {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActivationPlan {
+ pub project_id: ProjectId,
pub session_id: SessionId,
pub workspace_name: String,
pub project_path: PathBuf,
@@ -225,7 +184,68 @@ pub fn load_session_store_from_path(path: &Path) -> Result<SessionStore> {
return Ok(SessionStore::default());
}
let file = fs::File::open(path).with_context(|| format!("open {}", path.display()))?;
- serde_json::from_reader(file).with_context(|| format!("parse {}", path.display()))
+ let value: serde_json::Value =
+ serde_json::from_reader(file).with_context(|| format!("parse {}", path.display()))?;
+ migrate_legacy_remote_hosts(&value);
+ serde_json::from_value(value).with_context(|| format!("parse {}", path.display()))
+}
+
+fn migrate_legacy_remote_hosts(value: &serde_json::Value) {
+ let Some(projects) = value
+ .get("projects")
+ .and_then(|projects| projects.as_array())
+ else {
+ return;
+ };
+
+ for project in projects {
+ let Some(remote) = project.get("remote") else {
+ continue;
+ };
+ let project_label = project
+ .get("name")
+ .and_then(|name| name.as_str())
+ .unwrap_or("SSH Host");
+ let project_id = project
+ .get("id")
+ .and_then(|id| id.as_str())
+ .unwrap_or("<unknown>");
+
+ let mut spec = match serde_json::from_value::<crate::ssh_hosts::SshHostSpec>(remote.clone())
+ {
+ Ok(spec) => spec,
+ Err(err) => {
+ log::warn!(
+ "failed to migrate legacy SSH host from session project {project_id}: {err:#}"
+ );
+ continue;
+ }
+ };
+
+ if spec.label.trim().is_empty() {
+ spec.label = project_label.to_string();
+ }
+
+ if let Some(password) = spec.password.clone() {
+ if !password.is_empty() && !crate::secret::is_encrypted(&password) {
+ match crate::secret::encrypt(&password) {
+ Ok(encrypted) => spec.password = Some(encrypted),
+ Err(err) => {
+ log::warn!(
+ "failed to encrypt legacy SSH password for session project {project_id}: {err:#}"
+ );
+ continue;
+ }
+ }
+ }
+ }
+
+ if let Err(err) = crate::ssh_hosts::try_import_legacy_host(spec) {
+ log::warn!(
+ "failed to migrate legacy SSH host from session project {project_id}: {err:#}"
+ );
+ }
+ }
}
pub fn save_session_store(store: &SessionStore) -> Result<()> {
@@ -274,7 +294,6 @@ pub fn current_project_from_cwd() -> Project {
sessions: vec![],
active_session_id: None,
sessions_collapsed: false,
- remote: None,
}
}
@@ -317,110 +336,35 @@ 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 {
+/// Create a new session under a remote (SSH) project bound to `workspace_name`,
+/// mark it active, and return its id. Remote host connection details live in
+/// `ssh_hosts.json`; the project record here is layout/sidebar state only.
+pub fn create_remote_host_session(
+ project_id: &str,
+ label: &str,
+ path: PathBuf,
+ workspace_name: &str,
+) -> SessionId {
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);
+ project.name = label.to_string();
+ project.path = path.clone();
} else {
- let path = PathBuf::from(format!("ssh://{}", host_display(&spec)));
store.projects.push(Project {
- id: project_id.clone(),
- name: spec.label.clone(),
+ id: project_id.to_string(),
+ name: label.to_string(),
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())?;
+ .find(|p| p.id == project_id)
+ .expect("remote project was just inserted");
let name = format!("Session {}", project.sessions.len() + 1);
let session = Session::new(
project_id.to_string(),
@@ -432,7 +376,7 @@ pub fn create_host_session(project_id: &str, workspace_name: &str) -> Option<Ses
project.sessions.push(session);
store.active_project_id = Some(project_id.to_string());
persist_locked(&store);
- Some(session_id)
+ session_id
}
pub fn activate_session_record(
@@ -722,24 +666,29 @@ impl SessionStore {
let projects = self
.projects
.iter()
- .map(|project| ProjectView {
- id: project.id.clone(),
- name: project.name.clone(),
- is_active: project.id == active_project_id,
- sessions_collapsed: project.sessions_collapsed,
- sessions: session_views_for_project(
- project,
- Some(active_project_id),
- live_workspaces,
- )
- .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()),
+ .map(|project| {
+ let is_remote = is_remote_project(project);
+ ProjectView {
+ id: project.id.clone(),
+ name: project.name.clone(),
+ is_active: project.id == active_project_id,
+ sessions_collapsed: project.sessions_collapsed,
+ sessions: session_views_for_project(
+ project,
+ Some(active_project_id),
+ live_workspaces,
+ )
+ .into_iter()
+ .filter(|session| !session.is_pinned)
+ .collect(),
+ is_remote,
+ distro: if is_remote {
+ crate::ssh_hosts::host_spec(&project.id)
+ .and_then(|spec| spec.detected_distro.clone())
+ } else {
+ None
+ },
+ }
})
.collect();
ProjectSessionView {
@@ -826,7 +775,6 @@ 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();
@@ -909,6 +857,7 @@ impl SessionStore {
project.active_session_id = Some(session.id.clone());
self.active_project_id = Some(project.id.clone());
Some(ActivationPlan {
+ project_id,
session_id: session.id.clone(),
workspace_name,
project_path: project.path.clone(),
@@ -1611,33 +1560,10 @@ 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 is_remote_project(project: &Project) -> bool {
+ project.id.starts_with("ssh-")
+ || project.id.starts_with("system-ssh-")
+ || project.path.to_string_lossy().starts_with("ssh://")
}
fn normalize_project_path(path: &str) -> Result<PathBuf> {
@@ -1706,7 +1632,6 @@ mod tests {
)],
active_session_id: None,
sessions_collapsed: false,
- remote: None,
};
store.active_project_id = Some(project.id.clone());
store.projects.push(project);
@@ -1730,7 +1655,6 @@ mod tests {
sessions: vec![session],
active_session_id: None,
sessions_collapsed: false,
- remote: None,
});
save_session_store_to_path(&path, &store).unwrap();
@@ -1763,7 +1687,6 @@ mod tests {
)],
active_session_id: None,
sessions_collapsed: false,
- remote: None,
};
let session_id = project.sessions[0].id.clone();
store.projects.push(project);
@@ -1825,7 +1748,6 @@ mod tests {
)],
active_session_id: None,
sessions_collapsed: false,
- remote: None,
};
let session_id = project.sessions[0].id.clone();
store.projects.push(project);
@@ -1856,7 +1778,6 @@ 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(
@@ -1885,7 +1806,6 @@ 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(),
@@ -1894,7 +1814,6 @@ 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());
@@ -1919,7 +1838,6 @@ 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(),
@@ -1928,7 +1846,6 @@ 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());
@@ -1963,7 +1880,6 @@ 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/secret.rs b/wezterm-gui/src/secret.rs
new file mode 100644
index 00000000..a727fb64
--- /dev/null
+++ b/wezterm-gui/src/secret.rs
@@ -0,0 +1,135 @@
+//! At-rest encryption for stored secrets (currently SSH passwords).
+//!
+//! Secrets are encrypted with AES-256-GCM using a per-machine random key kept
+//! in `DATA_DIR/thinkterm/secret.key` (mode 0600). The encrypted value is
+//! stored in `sessions.json` as `enc:v1:<base64(nonce|tag|ciphertext)>` so the
+//! JSON never contains plaintext. This protects against casual disclosure
+//! (sync/backups/prying eyes); anyone with both the key file and the ciphertext
+//! can still decrypt, which is the documented trade-off for a key-on-disk
+//! scheme (vs the macOS Keychain).
+
+use anyhow::{Context, Result};
+use base64::engine::general_purpose::STANDARD;
+use base64::Engine;
+use openssl::symm::{decrypt_aead, encrypt_aead, Cipher};
+use std::fs;
+use std::io::Write;
+use std::path::PathBuf;
+
+const MARKER: &str = "enc:v1:";
+const IV_LEN: usize = 12;
+const TAG_LEN: usize = 16;
+
+fn key_path() -> PathBuf {
+ config::DATA_DIR.join("thinkterm").join("secret.key")
+}
+
+/// Load the 32-byte key, generating and persisting one (0600) if absent.
+fn load_or_create_key() -> Result<[u8; 32]> {
+ let path = key_path();
+ if let Ok(bytes) = fs::read(&path) {
+ if bytes.len() == 32 {
+ let mut key = [0u8; 32];
+ key.copy_from_slice(&bytes);
+ return Ok(key);
+ }
+ }
+
+ let mut key = [0u8; 32];
+ openssl::rand::rand_bytes(&mut key).context("generate secret key")?;
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
+ }
+ write_key_file(&path, &key)?;
+ Ok(key)
+}
+
+#[cfg(unix)]
+fn write_key_file(path: &std::path::Path, key: &[u8]) -> Result<()> {
+ use std::os::unix::fs::OpenOptionsExt;
+ let mut file = fs::OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .mode(0o600)
+ .open(path)
+ .with_context(|| format!("create {}", path.display()))?;
+ file.write_all(key)
+ .with_context(|| format!("write {}", path.display()))?;
+ Ok(())
+}
+
+#[cfg(not(unix))]
+fn write_key_file(path: &std::path::Path, key: &[u8]) -> Result<()> {
+ fs::write(path, key).with_context(|| format!("write {}", path.display()))
+}
+
+/// True if `value` is an encrypted blob produced by [`encrypt`].
+pub fn is_encrypted(value: &str) -> bool {
+ value.starts_with(MARKER)
+}
+
+/// Encrypt `plaintext` into the `enc:v1:...` storage form.
+pub fn encrypt(plaintext: &str) -> Result<String> {
+ let key = load_or_create_key()?;
+ let mut iv = [0u8; IV_LEN];
+ openssl::rand::rand_bytes(&mut iv).context("generate nonce")?;
+ let mut tag = [0u8; TAG_LEN];
+ let ciphertext = encrypt_aead(
+ Cipher::aes_256_gcm(),
+ &key,
+ Some(&iv),
+ &[],
+ plaintext.as_bytes(),
+ &mut tag,
+ )
+ .context("aes-256-gcm encrypt")?;
+
+ let mut blob = Vec::with_capacity(IV_LEN + TAG_LEN + ciphertext.len());
+ blob.extend_from_slice(&iv);
+ blob.extend_from_slice(&tag);
+ blob.extend_from_slice(&ciphertext);
+ Ok(format!("{MARKER}{}", STANDARD.encode(&blob)))
+}
+
+/// Decrypt a value produced by [`encrypt`]. Returns `None` if it is not an
+/// encrypted blob or cannot be decrypted.
+pub fn decrypt(stored: &str) -> Option<String> {
+ let blob = STANDARD.decode(stored.strip_prefix(MARKER)?).ok()?;
+ if blob.len() < IV_LEN + TAG_LEN {
+ return None;
+ }
+ let key = load_or_create_key().ok()?;
+ let (iv, rest) = blob.split_at(IV_LEN);
+ let (tag, ciphertext) = rest.split_at(TAG_LEN);
+ let plaintext =
+ decrypt_aead(Cipher::aes_256_gcm(), &key, Some(iv), &[], ciphertext, tag).ok()?;
+ String::from_utf8(plaintext).ok()
+}
+
+/// Decrypt an encrypted value, or pass through a legacy plaintext value
+/// (one not produced by [`encrypt`]).
+pub fn reveal(stored: &str) -> String {
+ if is_encrypted(stored) {
+ decrypt(stored).unwrap_or_default()
+ } else {
+ stored.to_string()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn round_trip() {
+ let secret = "hunter2 · 密码 🔒";
+ let enc = encrypt(secret).unwrap();
+ assert!(is_encrypted(&enc));
+ assert_ne!(enc, secret);
+ assert_eq!(decrypt(&enc).as_deref(), Some(secret));
+ assert_eq!(reveal(&enc), secret);
+ // Legacy plaintext passes through.
+ assert_eq!(reveal("plain"), "plain");
+ }
+}
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index 4e0f4d0c..71784ecb 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -1474,6 +1474,7 @@ impl SettingsWindow {
return match event.key {
KeyCode::Char('a') | KeyCode::Char('A') => self.select_all_focused_input(focused),
KeyCode::Char('c') | KeyCode::Char('C') => self.copy_focused_input(focused, window),
+ KeyCode::Char('x') | KeyCode::Char('X') => self.cut_focused_input(focused, window),
KeyCode::Char('v') | KeyCode::Char('V') => {
self.paste_focused_input_from_clipboard(focused, window)
}
@@ -1538,6 +1539,29 @@ impl SettingsWindow {
true
}
+ fn cut_focused_input(&mut self, focused: SettingsAction, window: &Window) -> bool {
+ let text = match focused {
+ SettingsAction::SearchInput => {
+ let Some(text) = self.ui.search.take_selected_text() else {
+ return false;
+ };
+ self.ui.sidebar_scroll.reset();
+ self.sync_selected_section_with_search();
+ text
+ }
+ SettingsAction::FontFamilyInput => {
+ let Some(text) = self.ui.font_family_input.take_selected_text() else {
+ return false;
+ };
+ self.sync_native_terminal_inputs();
+ text
+ }
+ _ => return false,
+ };
+ window.set_clipboard(Clipboard::Clipboard, text);
+ true
+ }
+
fn paste_focused_input_from_clipboard(
&mut self,
focused: SettingsAction,
@@ -4549,14 +4573,17 @@ impl SettingsWindow {
_ => false,
};
if focused && selected_all && !value.is_empty() {
+ let selection_width = self
+ .measure_text_width(&ui_font, value)
+ .min((control_width - 32.0).max(0.0));
self.draw_rounded_rect(
layers,
1,
- control_x + 10.0,
- control_y + 8.0,
- control_width - 20.0,
- CONTROL_HEIGHT - 16.0,
- palette.nav_selected_bg.mul_alpha(0.32),
+ control_x + 12.0,
+ control_y + 6.0,
+ selection_width + 8.0,
+ CONTROL_HEIGHT - 12.0,
+ palette.nav_selected_bg.mul_alpha(0.56),
CONTROL_RADIUS - 4.0,
)?;
}
@@ -4579,10 +4606,10 @@ impl SettingsWindow {
self.draw_rect(
layers,
1,
- caret_x,
- control_y + 12.0,
- 1.5,
- CONTROL_HEIGHT - 24.0,
+ caret_x - 1.0,
+ control_y + 8.0,
+ 3.0,
+ CONTROL_HEIGHT - 16.0,
palette.nav_selected_bg,
)?;
}
@@ -5201,14 +5228,17 @@ impl SettingsWindow {
palette.text
};
if spec.focused && spec.selected_all && !spec.text.is_empty() {
+ let selection_width = self
+ .measure_text_width(&Rc::clone(&self.ui_font), spec.text)
+ .min((spec.rect.size.width - 116.0).max(0.0));
self.draw_rounded_rect(
layers,
1,
- spec.rect.origin.x + 50.0,
- spec.rect.origin.y + 8.0,
- spec.rect.size.width - 96.0,
- spec.rect.size.height - 16.0,
- palette.nav_selected_bg.mul_alpha(0.32),
+ spec.rect.origin.x + 54.0,
+ spec.rect.origin.y + 6.0,
+ selection_width + 8.0,
+ spec.rect.size.height - 12.0,
+ palette.nav_selected_bg.mul_alpha(0.56),
self.ui.tokens.control_radius - 4.0,
)?;
}
@@ -5230,10 +5260,10 @@ impl SettingsWindow {
self.draw_rect(
layers,
1,
- caret_x,
- spec.rect.origin.y + 10.0,
- 1.5,
- spec.rect.size.height - 20.0,
+ caret_x - 1.0,
+ spec.rect.origin.y + 8.0,
+ 3.0,
+ spec.rect.size.height - 16.0,
palette.nav_selected_bg,
)?;
}
diff --git a/wezterm-gui/src/ssh_hosts.rs b/wezterm-gui/src/ssh_hosts.rs
index 0de6ff3c..c7748fb7 100644
--- a/wezterm-gui/src/ssh_hosts.rs
+++ b/wezterm-gui/src/ssh_hosts.rs
@@ -1,21 +1,299 @@
-//! Runtime SSH host -> mux domain plumbing for the ThinkTerm host manager.
+//! ThinkTerm SSH host address book and runtime host -> mux domain plumbing.
//!
-//! 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;
+//! `sessions.json` owns workspace/session layout only. User-created SSH hosts
+//! live in `ssh_hosts.json`; system `~/.ssh/config` hosts are exposed as
+//! read-only entries. Runtime domains are still registered lazily with the mux
+//! via [`mux::Mux::add_domain`].
+
+use anyhow::{Context, Result};
use config::{SshDomain, SshMultiplexing};
use mux::domain::Domain;
use mux::ssh::RemoteSshDomain;
use mux::Mux;
+use parking_lot::Mutex;
+use serde::{Deserialize, Serialize};
use std::collections::HashMap;
+use std::fs;
+use std::io::Write;
+use std::path::{Path, PathBuf};
use std::sync::Arc;
+pub type SshHostId = String;
+
+#[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>,
+ /// Optional stored password used to auto-answer the password prompt on
+ /// connect. New values are stored encrypted (`enc:v1:...`); legacy
+ /// plaintext values are still accepted by the connection layer.
+ #[serde(default)]
+ pub password: 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.
+ /// That requires `wezterm` installed on the remote; default to direct
+ /// `ssh` (like `wezterm ssh`) so password auth + the shell work anywhere.
+ #[serde(default)]
+ 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, Copy, PartialEq, Eq)]
+pub enum SshHostSource {
+ ThinkTerm,
+ System,
+}
+
+#[derive(Debug, Clone)]
+pub struct SshHostEntry {
+ pub id: SshHostId,
+ pub source: SshHostSource,
+ pub spec: SshHostSpec,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+struct SshHostRecord {
+ id: SshHostId,
+ spec: SshHostSpec,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+struct SshHostStore {
+ #[serde(default = "store_version")]
+ version: u32,
+ #[serde(default)]
+ hosts: Vec<SshHostRecord>,
+}
+
+impl Default for SshHostStore {
+ fn default() -> Self {
+ Self {
+ version: store_version(),
+ hosts: vec![],
+ }
+ }
+}
+
+fn store_version() -> u32 {
+ 1
+}
+
+lazy_static::lazy_static! {
+ static ref SSH_HOST_STORE: Mutex<SshHostStore> =
+ Mutex::new(load_ssh_host_store().unwrap_or_else(|err| {
+ log::warn!("failed to load ThinkTerm SSH host store: {err:#}");
+ SshHostStore::default()
+ }));
+}
+
+pub fn ssh_hosts_store_path() -> PathBuf {
+ config::DATA_DIR.join("thinkterm").join("ssh_hosts.json")
+}
+
+fn load_ssh_host_store() -> Result<SshHostStore> {
+ load_ssh_host_store_from_path(&ssh_hosts_store_path())
+}
+
+fn load_ssh_host_store_from_path(path: &Path) -> Result<SshHostStore> {
+ if !path.exists() {
+ return Ok(SshHostStore::default());
+ }
+ let file = fs::File::open(path).with_context(|| format!("open {}", path.display()))?;
+ serde_json::from_reader(file).with_context(|| format!("parse {}", path.display()))
+}
+
+fn save_ssh_host_store(store: &SshHostStore) -> Result<()> {
+ save_ssh_host_store_to_path(&ssh_hosts_store_path(), store)
+}
+
+fn save_ssh_host_store_to_path(path: &Path, store: &SshHostStore) -> Result<()> {
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
+ let mut file = tempfile::NamedTempFile::new_in(parent)
+ .with_context(|| format!("create temporary SSH host store in {}", parent.display()))?;
+ serde_json::to_writer_pretty(&mut file, store)
+ .with_context(|| format!("write {}", path.display()))?;
+ file.flush()
+ .with_context(|| format!("flush {}", path.display()))?;
+ file.as_file()
+ .sync_all()
+ .with_context(|| format!("sync {}", path.display()))?;
+ file.persist(path)
+ .with_context(|| format!("replace {}", path.display()))?;
+ return Ok(());
+ }
+
+ let mut file = fs::File::create(path).with_context(|| format!("create {}", path.display()))?;
+ serde_json::to_writer_pretty(&mut file, store)
+ .with_context(|| format!("write {}", path.display()))?;
+ file.flush()
+ .with_context(|| format!("flush {}", path.display()))?;
+ file.sync_all()
+ .with_context(|| format!("sync {}", path.display()))
+}
+
+pub fn list_hosts() -> Vec<(SshHostId, SshHostSpec)> {
+ let store = SSH_HOST_STORE.lock();
+ store
+ .hosts
+ .iter()
+ .map(|record| (record.id.clone(), record.spec.clone()))
+ .collect()
+}
+
+pub fn list_all_hosts() -> Vec<SshHostEntry> {
+ let mut entries: Vec<_> = list_hosts()
+ .into_iter()
+ .map(|(id, spec)| SshHostEntry {
+ id,
+ source: SshHostSource::ThinkTerm,
+ spec,
+ })
+ .collect();
+ entries.extend(list_system_hosts());
+ entries
+}
+
+pub fn host_spec(host_id: &str) -> Option<SshHostSpec> {
+ {
+ let store = SSH_HOST_STORE.lock();
+ if let Some(record) = store.hosts.iter().find(|record| record.id == host_id) {
+ return Some(record.spec.clone());
+ }
+ }
+ list_system_hosts()
+ .into_iter()
+ .find(|entry| entry.id == host_id)
+ .map(|entry| entry.spec)
+}
+
+pub fn try_create_host(spec: SshHostSpec) -> Result<SshHostId> {
+ let (host_id, spec) = upsert_host(spec)?;
+ register_ssh_domain(&spec)?;
+ Ok(host_id)
+}
+
+pub fn try_import_legacy_host(spec: SshHostSpec) -> Result<SshHostId> {
+ let mut store = SSH_HOST_STORE.lock();
+ let host_id = host_id_for_host(&spec);
+ if store.hosts.iter().any(|record| record.id == host_id) {
+ return Ok(host_id);
+ }
+ store.hosts.push(SshHostRecord {
+ id: host_id.clone(),
+ spec,
+ });
+ save_ssh_host_store(&store)?;
+ Ok(host_id)
+}
+
+fn upsert_host(spec: SshHostSpec) -> Result<(SshHostId, SshHostSpec)> {
+ let mut store = SSH_HOST_STORE.lock();
+ let host_id = host_id_for_host(&spec);
+ if let Some(record) = store.hosts.iter_mut().find(|record| record.id == host_id) {
+ record.spec = spec;
+ } else {
+ store.hosts.push(SshHostRecord {
+ id: host_id.clone(),
+ spec,
+ });
+ }
+ save_ssh_host_store(&store)?;
+ let saved_spec = store
+ .hosts
+ .iter()
+ .find(|record| record.id == host_id)
+ .map(|record| record.spec.clone())
+ .expect("host was just inserted");
+ Ok((host_id, saved_spec))
+}
+
+pub fn try_update_host(host_id: &str, spec: SshHostSpec) -> Result<bool> {
+ if is_system_host_id(host_id) {
+ return Ok(false);
+ }
+ let mut store = SSH_HOST_STORE.lock();
+ let Some(record) = store.hosts.iter_mut().find(|record| record.id == host_id) else {
+ return Ok(false);
+ };
+ record.spec = spec;
+ save_ssh_host_store(&store)?;
+ let spec = store
+ .hosts
+ .iter()
+ .find(|record| record.id == host_id)
+ .map(|record| record.spec.clone());
+ drop(store);
+ if let Some(spec) = spec {
+ register_ssh_domain(&spec)?;
+ }
+ Ok(true)
+}
+
+pub fn try_remove_host(host_id: &str) -> Result<bool> {
+ if is_system_host_id(host_id) {
+ return Ok(false);
+ }
+ let mut store = SSH_HOST_STORE.lock();
+ let before = store.hosts.len();
+ store.hosts.retain(|record| record.id != host_id);
+ if store.hosts.len() == before {
+ return Ok(false);
+ }
+ save_ssh_host_store(&store)?;
+ Ok(true)
+}
+
+pub fn set_host_distro(host_id: &str, distro_id: &str) -> bool {
+ if is_system_host_id(host_id) {
+ return false;
+ }
+ let mut store = SSH_HOST_STORE.lock();
+ let Some(record) = store.hosts.iter_mut().find(|record| record.id == host_id) else {
+ return false;
+ };
+ let new_value = {
+ let trimmed = distro_id.trim();
+ (!trimmed.is_empty()).then(|| trimmed.to_string())
+ };
+ if record.spec.detected_distro == new_value {
+ return false;
+ }
+ record.spec.detected_distro = new_value;
+ if let Err(err) = save_ssh_host_store(&store) {
+ log::warn!("failed to persist SSH host distro for {host_id}: {err:#}");
+ }
+ true
+}
+
+pub fn is_system_host_id(host_id: &str) -> bool {
+ host_id.starts_with("system-ssh-")
+}
+
/// `user@host` (or `host`, with `:port` when non-default) used for the
/// human-readable domain / workspace identifiers.
fn endpoint(spec: &SshHostSpec) -> String {
@@ -29,6 +307,10 @@ fn endpoint(spec: &SshHostSpec) -> String {
}
}
+pub fn host_project_path(spec: &SshHostSpec) -> PathBuf {
+ PathBuf::from(format!("ssh://{}", endpoint(spec)))
+}
+
/// 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.
@@ -76,6 +358,20 @@ pub fn build_ssh_domain(spec: &SshHostSpec) -> SshDomain {
}
}
+fn register_ssh_domain(spec: &SshHostSpec) -> Result<()> {
+ let dom = build_ssh_domain(spec);
+ let password = spec
+ .password
+ .as_deref()
+ .map(crate::secret::reveal)
+ .filter(|p| !p.is_empty());
+ let domain: Arc<dyn Domain> = Arc::new(RemoteSshDomain::with_ssh_domain_and_password(
+ &dom, password,
+ )?);
+ Mux::get().add_domain(&domain);
+ Ok(())
+}
+
/// 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
@@ -84,9 +380,7 @@ 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);
+ register_ssh_domain(spec)?;
}
Ok(name)
}
@@ -95,12 +389,198 @@ pub fn ensure_ssh_domain_registered(spec: &SshHostSpec) -> Result<String> {
/// 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) {
+ for entry in list_all_hosts() {
+ if let Err(err) = ensure_ssh_domain_registered(&entry.spec) {
log::warn!(
"failed to register saved SSH host {:?}: {err:#}",
- spec.label
+ entry.spec.label
+ );
+ }
+ }
+}
+
+pub fn list_system_hosts() -> Vec<SshHostEntry> {
+ let path = config::HOME_DIR.join(".ssh").join("config");
+ match parse_system_ssh_config(&path) {
+ Ok(hosts) => hosts,
+ Err(err) => {
+ log::debug!(
+ "failed to read system SSH config {}: {err:#}",
+ path.display()
);
+ vec![]
}
}
}
+
+fn parse_system_ssh_config(path: &Path) -> Result<Vec<SshHostEntry>> {
+ if !path.exists() {
+ return Ok(vec![]);
+ }
+ let content = fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
+ Ok(parse_system_ssh_config_str(&content))
+}
+
+#[derive(Default)]
+struct SystemHostBlock {
+ aliases: Vec<String>,
+ user: Option<String>,
+ port: Option<u16>,
+ identity_file: Option<String>,
+}
+
+fn parse_system_ssh_config_str(content: &str) -> Vec<SshHostEntry> {
+ fn flush(block: &mut Option<SystemHostBlock>, out: &mut Vec<SshHostEntry>) {
+ let Some(block) = block.take() else {
+ return;
+ };
+ for alias in block.aliases {
+ if !is_concrete_host_alias(&alias) {
+ continue;
+ }
+ let spec = SshHostSpec {
+ label: alias.clone(),
+ // Preserve the alias as the remote address so ssh_config
+ // alias-scoped options such as ProxyJump still apply.
+ host: alias.clone(),
+ port: block.port,
+ username: block.user.clone(),
+ identity_file: block.identity_file.clone(),
+ password: None,
+ ssh_options: HashMap::new(),
+ multiplexing: false,
+ default_workspace: None,
+ detect_os: true,
+ detected_distro: None,
+ };
+ out.push(SshHostEntry {
+ id: system_host_id(&alias),
+ source: SshHostSource::System,
+ spec,
+ });
+ }
+ }
+
+ let mut entries = Vec::new();
+ let mut current: Option<SystemHostBlock> = None;
+
+ for raw_line in content.lines() {
+ let Some(line) = strip_ssh_config_comment(raw_line) else {
+ continue;
+ };
+ let mut parts = line.split_whitespace();
+ let Some(key) = parts.next() else {
+ continue;
+ };
+ let key = key.to_ascii_lowercase();
+ match key.as_str() {
+ "host" => {
+ flush(&mut current, &mut entries);
+ let aliases = parts.map(|part| part.to_string()).collect::<Vec<_>>();
+ current = Some(SystemHostBlock {
+ aliases,
+ ..Default::default()
+ });
+ }
+ "user" => {
+ if let Some(block) = current.as_mut() {
+ block.user = parts.next().map(|value| value.to_string());
+ }
+ }
+ "port" => {
+ if let Some(block) = current.as_mut() {
+ block.port = parts.next().and_then(|value| value.parse::<u16>().ok());
+ }
+ }
+ "identityfile" => {
+ if let Some(block) = current.as_mut() {
+ block.identity_file = parts.next().map(expand_system_ssh_value);
+ }
+ }
+ _ => {}
+ }
+ }
+ flush(&mut current, &mut entries);
+ entries.sort_by(|a, b| {
+ a.spec
+ .label
+ .to_ascii_lowercase()
+ .cmp(&b.spec.label.to_ascii_lowercase())
+ });
+ entries.dedup_by(|a, b| a.id == b.id);
+ entries
+}
+
+fn strip_ssh_config_comment(line: &str) -> Option<&str> {
+ let line = line.split_once('#').map(|(head, _)| head).unwrap_or(line);
+ let line = line.trim();
+ (!line.is_empty()).then_some(line)
+}
+
+fn is_concrete_host_alias(alias: &str) -> bool {
+ !alias.starts_with('!') && !alias.contains('*') && !alias.contains('?')
+}
+
+fn expand_system_ssh_value(value: &str) -> String {
+ if value == "~" {
+ config::HOME_DIR.to_string_lossy().to_string()
+ } else if let Some(rest) = value.strip_prefix("~/") {
+ config::HOME_DIR.join(rest).to_string_lossy().to_string()
+ } else {
+ value.to_string()
+ }
+}
+
+fn fnv1a(input: &str) -> u64 {
+ let mut hash = 0xcbf29ce484222325u64;
+ for byte in input.bytes() {
+ hash ^= byte as u64;
+ hash = hash.wrapping_mul(0x100000001b3);
+ }
+ hash
+}
+
+fn host_id_for_host(spec: &SshHostSpec) -> SshHostId {
+ let key = format!(
+ "ssh:{}@{}:{}",
+ spec.username.as_deref().unwrap_or(""),
+ spec.host,
+ spec.port.unwrap_or(22)
+ );
+ format!("ssh-{:x}", fnv1a(&key))
+}
+
+fn system_host_id(alias: &str) -> SshHostId {
+ format!("system-ssh-{:x}", fnv1a(&format!("system:{alias}")))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn system_hosts_preserve_ssh_config_alias_as_remote_address() {
+ let entries = parse_system_ssh_config_str(
+ r#"
+Host prod *.internal
+ HostName 10.0.0.1
+ User deploy
+ Port 2202
+ IdentityFile ~/.ssh/prod
+ ProxyJump bastion
+"#,
+ );
+
+ assert_eq!(entries.len(), 1);
+ let spec = &entries[0].spec;
+ assert_eq!(spec.label, "prod");
+ assert_eq!(spec.host, "prod");
+ assert_eq!(spec.username.as_deref(), Some("deploy"));
+ assert_eq!(spec.port, Some(2202));
+ assert!(spec
+ .identity_file
+ .as_deref()
+ .unwrap()
+ .ends_with("/.ssh/prod"));
+ }
+}
diff --git a/wezterm-gui/src/tabbar.rs b/wezterm-gui/src/tabbar.rs
index ba006412..18f44e34 100644
--- a/wezterm-gui/src/tabbar.rs
+++ b/wezterm-gui/src/tabbar.rs
@@ -27,9 +27,14 @@ pub enum TabBarItem {
None,
LeftStatus,
RightStatus,
- Tab { tab_idx: usize, active: bool },
+ Tab {
+ tab_idx: usize,
+ active: bool,
+ },
NewTabButton,
WindowButton(IntegratedTitleButton),
+ /// Synthetic tab for a ThinkTerm content view (e.g. SSH hosts).
+ ContentView,
}
#[derive(Clone, Debug, PartialEq)]
diff --git a/wezterm-gui/src/termwindow/box_model.rs b/wezterm-gui/src/termwindow/box_model.rs
index f1f91f9a..27a5fde1 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::{BrandIcon, SvgIcon};
+use crate::termwindow::ui::icons::SvgIcon;
use crate::termwindow::{
ColorEase, MouseCapture, RenderState, TermWindowNotif, UIItem, UIItemType,
};
@@ -396,7 +396,6 @@ 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> {
@@ -445,7 +444,6 @@ impl ComputedElement {
ComputedElementContent::Text(_) => {}
ComputedElementContent::Poly { .. } => {}
ComputedElementContent::Icon { .. } => {}
- ComputedElementContent::BrandIcon { .. } => {}
}
}
@@ -475,7 +473,6 @@ impl ComputedElement {
}
ComputedElementContent::Poly { .. } => {}
ComputedElementContent::Icon { .. } => {}
- ComputedElementContent::BrandIcon { .. } => {}
}
}
}
@@ -492,10 +489,6 @@ pub enum ComputedElementContent {
icon: SvgIcon,
size: f32,
},
- BrandIcon {
- icon: BrandIcon,
- size: f32,
- },
}
#[derive(Debug, Clone)]
@@ -855,26 +848,6 @@ 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 },
- })
- }
}
}
@@ -1015,28 +988,6 @@ 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/content_view.rs b/wezterm-gui/src/termwindow/content_view.rs
new file mode 100644
index 00000000..76e9cdec
--- /dev/null
+++ b/wezterm-gui/src/termwindow/content_view.rs
@@ -0,0 +1,68 @@
+//! Reusable "content view" framework: a GPU-drawn panel that occupies the
+//! terminal content area and behaves like a synthetic tab (switch / close /
+//! preserve state). The SSH hosts manager is the first implementer; other
+//! native panels can plug in by implementing [`ContentView`] and calling
+//! `TermWindow::open_content_view`.
+
+use crate::quad::TripleLayerQuadAllocator;
+use crate::termwindow::TermWindow;
+use crate::ui::{DrawContext, UiPalette};
+use std::rc::Rc;
+use wezterm_font::LoadedFont;
+use wezterm_term::{KeyCode, KeyModifiers};
+use window::{MouseEventKind as WMEK, RectF};
+
+/// What `TermWindow` should do after a content view handled an input event.
+pub(crate) enum ContentViewResponse {
+ /// Event not consumed by the view.
+ Ignored,
+ /// Repaint the window.
+ Redraw,
+ /// Close the content view (remove its synthetic tab).
+ Close,
+ /// Run a callback back on the owning `TermWindow` (e.g. connect SSH).
+ Run(Box<dyn FnOnce(&mut TermWindow)>),
+}
+
+pub(crate) trait ContentView {
+ /// Title shown on the synthetic tab.
+ fn title(&self) -> String;
+
+ /// Whether the view currently wants the cursor-blink animation running
+ /// (true only while a text field is focused, to avoid needless repaints).
+ fn wants_cursor_blink(&self) -> bool {
+ false
+ }
+
+ /// Paint the view into `area` (the terminal content rect). `cursor_on` is
+ /// the current blink phase for any focused caret.
+ fn paint(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ cursor_on: bool,
+ ) -> anyhow::Result<()>;
+
+ fn on_mouse(&mut self, x: f32, y: f32, kind: WMEK) -> ContentViewResponse;
+
+ fn on_key(&mut self, key: KeyCode, mods: KeyModifiers) -> ContentViewResponse;
+
+ /// Insert pasted text into the focused field, if any.
+ fn on_paste(&mut self, _text: &str) -> ContentViewResponse {
+ ContentViewResponse::Redraw
+ }
+
+ /// Text to copy to the clipboard for ⌘C (e.g. the focused field), if any.
+ fn copy_text(&self) -> Option<String> {
+ None
+ }
+
+ /// Text to cut to the clipboard for ⌘X. Views that only support whole-field
+ /// selection should return text only when that selection is active.
+ fn cut_text(&mut self) -> Option<String> {
+ None
+ }
+}
diff --git a/wezterm-gui/src/termwindow/keyevent.rs b/wezterm-gui/src/termwindow/keyevent.rs
index ed953228..8ff085f6 100644
--- a/wezterm-gui/src/termwindow/keyevent.rs
+++ b/wezterm-gui/src/termwindow/keyevent.rs
@@ -450,6 +450,52 @@ impl super::TermWindow {
}
}
+ if only_key_bindings == OnlyKeyBindings::No && self.content_view_foreground() {
+ use ::termwiz::input::{KeyCode as TKC, Modifiers as TMods};
+ match self.win_key_code_to_termwiz_key_code(keycode) {
+ Key::Code(term_key) => {
+ let mods = raw_modifiers.remove_positional_mods();
+ // ⌘C / ⌘X / ⌘V operate on the focused content-view field.
+ if mods.contains(TMods::SUPER)
+ && matches!(term_key, TKC::Char('v') | TKC::Char('V'))
+ {
+ self.content_view_paste();
+ return true;
+ }
+ if mods.contains(TMods::SUPER)
+ && matches!(term_key, TKC::Char('x') | TKC::Char('X'))
+ {
+ self.content_view_cut();
+ return true;
+ }
+ if mods.contains(TMods::SUPER)
+ && matches!(term_key, TKC::Char('c') | TKC::Char('C'))
+ {
+ self.content_view_copy();
+ return true;
+ }
+ let resp = self.content_view.as_mut().map(|v| v.on_key(term_key, mods));
+ match resp {
+ Some(crate::termwindow::content_view::ContentViewResponse::Ignored)
+ | None => {}
+ Some(resp) => {
+ self.handle_content_response(resp);
+ return true;
+ }
+ }
+ }
+ // IME / composed text (e.g. CJK input) arrives here.
+ Key::Composed(text) => {
+ let resp = self.content_view.as_mut().map(|v| v.on_paste(&text));
+ if let Some(resp) = resp {
+ self.handle_content_response(resp);
+ }
+ return true;
+ }
+ _ => {}
+ }
+ }
+
if let Some((entry, table_name)) = self.lookup_key(
pane,
&keycode,
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index 54299c53..77e6466c 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -31,8 +31,8 @@ use ::window::color::LinearRgba;
use ::window::*;
use anyhow::{anyhow, ensure, Context};
use config::keyassignment::{
- Confirmation, KeyAssignment, LauncherActionArgs, PaneDirection, Pattern, PromptInputLine,
- QuickSelectArguments, RotationDirection, SpawnCommand, SplitSize,
+ ClipboardPasteSource, Confirmation, KeyAssignment, LauncherActionArgs, PaneDirection, Pattern,
+ PromptInputLine, QuickSelectArguments, RotationDirection, SpawnCommand, SplitSize,
};
use config::window::WindowLevel;
use config::{
@@ -84,6 +84,7 @@ pub mod background;
pub mod box_model;
pub mod charselect;
pub mod clipboard;
+pub mod content_view;
pub mod keyevent;
pub mod modal;
mod mouseevent;
@@ -94,7 +95,7 @@ pub mod render;
pub mod resize;
mod selection;
pub mod spawn;
-pub mod ssh_hosts_modal;
+pub mod ssh_hosts_view;
pub mod ui;
pub mod webgpu;
@@ -230,38 +231,14 @@ pub enum UIItemType {
WorkspaceSidebarResize,
WorkspaceSidebarSettings,
WorkspaceSidebarViewOptions,
+ WorkspaceSidebarSshHosts,
WorkspaceSidebarNotifications,
AboveScrollThumb,
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,
+ /// Close button on the synthetic content-view tab.
+ ContentViewClose,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -742,6 +719,11 @@ pub struct TermWindow {
ui_items: Vec<UIItem>,
dragging: Option<(UIItem, MouseEvent)>,
+ /// When `Some`, a content view (e.g. SSH hosts) is available as a synthetic
+ /// tab. `content_view_active` is whether it is the foreground content (vs a
+ /// terminal tab being shown).
+ content_view: Option<Box<dyn crate::termwindow::content_view::ContentView>>,
+ content_view_active: bool,
workspace_sidebar_width: usize,
workspace_sidebar_collapsed: bool,
workspace_sidebar_scroll_offset: f32,
@@ -1162,6 +1144,8 @@ impl TermWindow {
semantic_zones: HashMap::new(),
ui_items: vec![],
dragging: None,
+ content_view: None,
+ content_view_active: false,
workspace_sidebar_width,
workspace_sidebar_collapsed: false,
workspace_sidebar_scroll_offset: 0.0,
@@ -2276,6 +2260,124 @@ impl TermWindow {
self.emit_window_event("window-config-reloaded", None);
}
+ /// True when a content view is the foreground content (occupying the
+ /// content area instead of terminal panes).
+ pub(crate) fn content_view_foreground(&self) -> bool {
+ self.content_view.is_some() && self.content_view_active
+ }
+
+ pub(crate) fn open_content_view(
+ &mut self,
+ view: Box<dyn crate::termwindow::content_view::ContentView>,
+ ) {
+ self.content_view = Some(view);
+ self.content_view_active = true;
+ self.invalidate_window();
+ }
+
+ pub(crate) fn close_content_view(&mut self) {
+ self.content_view = None;
+ self.content_view_active = false;
+ self.invalidate_window();
+ }
+
+ pub(crate) fn set_content_view_active(&mut self, active: bool) {
+ if self.content_view.is_some() {
+ self.content_view_active = active;
+ self.invalidate_window();
+ }
+ }
+
+ /// Toggle the SSH hosts content view (sidebar button / OpenSshHosts).
+ pub(crate) fn toggle_ssh_hosts_view(&mut self) {
+ if self.content_view.is_some() {
+ self.close_content_view();
+ } else {
+ self.open_content_view(Box::new(
+ crate::termwindow::ssh_hosts_view::SshHostsView::new(),
+ ));
+ }
+ }
+
+ fn invalidate_window(&self) {
+ if let Some(window) = self.window.as_ref() {
+ window.invalidate();
+ }
+ }
+
+ /// Copy the active content view's focused text to the clipboard (⌘C).
+ pub(crate) fn content_view_copy(&mut self) {
+ if let Some(text) = self.content_view.as_ref().and_then(|v| v.copy_text()) {
+ if !text.is_empty() {
+ self.copy_to_clipboard(
+ config::keyassignment::ClipboardCopyDestination::Clipboard,
+ text,
+ );
+ }
+ }
+ }
+
+ /// Cut the active content view's selected text to the clipboard (⌘X).
+ pub(crate) fn content_view_cut(&mut self) {
+ if let Some(text) = self.content_view.as_mut().and_then(|v| v.cut_text()) {
+ if !text.is_empty() {
+ self.copy_to_clipboard(
+ config::keyassignment::ClipboardCopyDestination::Clipboard,
+ text,
+ );
+ self.invalidate_window();
+ }
+ }
+ }
+
+ fn content_view_paste_from(&mut self, clipboard: ClipboardPasteSource) {
+ let Some(window) = self.window.as_ref().map(|w| w.clone()) else {
+ return;
+ };
+ let clipboard = match clipboard {
+ ClipboardPasteSource::Clipboard => ::window::Clipboard::Clipboard,
+ ClipboardPasteSource::PrimarySelection => ::window::Clipboard::PrimarySelection,
+ };
+ let future = window.get_clipboard(clipboard);
+ promise::spawn::spawn(async move {
+ if let Ok(clip) = future.await {
+ window.notify(TermWindowNotif::Apply(Box::new(move |myself| {
+ let resp = myself.content_view.as_mut().map(|v| v.on_paste(&clip));
+ if let Some(resp) = resp {
+ myself.handle_content_response(resp);
+ }
+ })));
+ }
+ })
+ .detach();
+ }
+
+ /// Read the clipboard asynchronously and feed it to the active content view
+ /// (used for ⌘V inside content-view text fields).
+ pub(crate) fn content_view_paste(&mut self) {
+ self.content_view_paste_from(ClipboardPasteSource::Clipboard);
+ }
+
+ /// Apply the result of an input event handled by the active content view.
+ pub(crate) fn handle_content_response(
+ &mut self,
+ response: crate::termwindow::content_view::ContentViewResponse,
+ ) {
+ use crate::termwindow::content_view::ContentViewResponse;
+ match response {
+ ContentViewResponse::Ignored => return,
+ ContentViewResponse::Redraw => {}
+ ContentViewResponse::Close => {
+ self.content_view = None;
+ self.content_view_active = false;
+ }
+ ContentViewResponse::Run(func) => {
+ func(self);
+ }
+ }
+ self.invalidate_window();
+ }
+
fn invalidate_modal(&mut self) {
if let Some(modal) = self.get_modal() {
modal.reconfigure(self);
@@ -3220,6 +3322,24 @@ impl TermWindow {
}
}
+ if self.content_view_foreground() {
+ match assignment {
+ CopyTo(destination) => {
+ if let Some(text) = self.content_view.as_ref().and_then(|v| v.copy_text()) {
+ if !text.is_empty() {
+ self.copy_to_clipboard(*destination, text);
+ }
+ }
+ return Ok(PerformAssignmentResult::Handled);
+ }
+ PasteFrom(source) => {
+ self.content_view_paste_from(*source);
+ return Ok(PerformAssignmentResult::Handled);
+ }
+ _ => {}
+ }
+ }
+
match pane.perform_assignment(assignment) {
PerformAssignmentResult::Unhandled => {}
result => return Ok(result),
@@ -3867,8 +3987,7 @@ impl TermWindow {
crate::settings_window::show();
}
OpenSshHosts => {
- let modal = crate::termwindow::ssh_hosts_modal::SshHostsModal::new();
- self.set_modal(Rc::new(modal));
+ self.toggle_ssh_hosts_view();
}
ActivateCommandPalette => {
let modal = crate::termwindow::palette::CommandPalette::new(self);
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index d0813a95..a88883f8 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -8,10 +8,9 @@ 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, SshHostsAction,
- TabWheelSurface, TermWindowNotif, UIItem, UIItemType, TMB,
+ GuiWin, MouseCapture, PaneNavAction, PositionedSplit, ScrollHit, TabWheelSurface,
+ TermWindowNotif, UIItem, UIItemType, TMB,
};
use ::window::{
ContextMenuItem, MouseButtons as WMB, MouseCursor, MouseEvent, MouseEventKind as WMEK,
@@ -586,12 +585,13 @@ impl super::TermWindow {
| UIItemType::WorkspaceSidebarResize
| UIItemType::WorkspaceSidebarSettings
| UIItemType::WorkspaceSidebarViewOptions
+ | UIItemType::WorkspaceSidebarSshHosts
| UIItemType::WorkspaceSidebarNotifications
| UIItemType::AboveScrollThumb
| UIItemType::BelowScrollThumb
| UIItemType::ScrollThumb
| UIItemType::Split(_)
- | UIItemType::SshHosts(_) => {}
+ | UIItemType::ContentViewClose => {}
}
}
@@ -614,12 +614,13 @@ impl super::TermWindow {
| UIItemType::WorkspaceSidebarResize
| UIItemType::WorkspaceSidebarSettings
| UIItemType::WorkspaceSidebarViewOptions
+ | UIItemType::WorkspaceSidebarSshHosts
| UIItemType::WorkspaceSidebarNotifications
| UIItemType::AboveScrollThumb
| UIItemType::BelowScrollThumb
| UIItemType::ScrollThumb
| UIItemType::Split(_)
- | UIItemType::SshHosts(_) => {}
+ | UIItemType::ContentViewClose => {}
}
}
@@ -866,6 +867,18 @@ impl super::TermWindow {
self.current_mouse_capture = Some(MouseCapture::UI);
}
self.mouse_event_ui_item(item, pane, y, event, context);
+ } else if self.content_view_foreground() {
+ // The content view owns the content area; route by pixel coords.
+ context.set_cursor(Some(MouseCursor::Arrow));
+ let px = event.coords.x as f32;
+ let py = event.coords.y as f32;
+ let resp = self
+ .content_view
+ .as_mut()
+ .map(|v| v.on_mouse(px, py, event.kind));
+ if let Some(resp) = resp {
+ self.handle_content_response(resp);
+ }
} else if matches!(
self.current_mouse_capture,
None | Some(MouseCapture::TerminalPane(_))
@@ -1130,79 +1143,23 @@ impl super::TermWindow {
UIItemType::WorkspaceSidebarSettings => {
self.mouse_event_workspace_sidebar_settings(event, context);
}
- UIItemType::WorkspaceSidebarViewOptions => {
- self.mouse_event_workspace_sidebar_view_options(item, event, context);
- }
- UIItemType::WorkspaceSidebarNotifications => {
+ UIItemType::WorkspaceSidebarSshHosts => {
context.set_cursor(Some(MouseCursor::Hand));
+ if event.kind == WMEK::Press(MousePress::Left) {
+ self.toggle_ssh_hosts_view();
+ }
}
- 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();
+ UIItemType::ContentViewClose => {
+ context.set_cursor(Some(MouseCursor::Hand));
+ if event.kind == WMEK::Press(MousePress::Left) {
+ self.close_content_view();
}
}
- SshHostsAction::Cancel => {
- self.with_ssh_hosts_modal(|m| m.cancel_to_grid());
- self.invalidate_modal();
+ UIItemType::WorkspaceSidebarViewOptions => {
+ self.mouse_event_workspace_sidebar_view_options(item, event, context);
}
- SshHostsAction::Background => {
- self.cancel_modal();
+ UIItemType::WorkspaceSidebarNotifications => {
+ context.set_cursor(Some(MouseCursor::Hand));
}
}
}
@@ -1563,7 +1520,28 @@ impl super::TermWindow {
}
let workspace_name = plan.workspace_name.clone();
- let initial_cwd = plan.project_path.to_str().map(|path| path.to_string());
+ let remote_spec = crate::ssh_hosts::host_spec(&plan.project_id);
+ let (initial_cwd, default_domain) = if let Some(spec) = remote_spec.as_ref() {
+ match crate::ssh_hosts::ensure_ssh_domain_registered(spec) {
+ Ok(domain_name) => (
+ None,
+ config::keyassignment::SpawnTabDomain::DomainName(domain_name),
+ ),
+ Err(err) => {
+ log::error!(
+ "failed to register SSH domain for session {:?}: {err:#}",
+ spec.label
+ );
+ context.invalidate();
+ return;
+ }
+ }
+ } else {
+ (
+ plan.project_path.to_str().map(|path| path.to_string()),
+ config::keyassignment::SpawnTabDomain::DefaultDomain,
+ )
+ };
let layout = crate::project_sessions::session_layout(&plan.session_id);
let dpi = self.dimensions.dpi as u32;
let size = self.config.initial_size(
@@ -1583,7 +1561,7 @@ impl super::TermWindow {
size,
None,
term_config,
- config::keyassignment::SpawnTabDomain::DefaultDomain,
+ default_domain,
)
.await
{
@@ -1600,7 +1578,11 @@ impl super::TermWindow {
/// 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>) {
+ 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 {
@@ -1608,14 +1590,17 @@ impl super::TermWindow {
}
};
- let Some(spec) = crate::project_sessions::host_spec(&project_id) else {
+ let Some(spec) = crate::ssh_hosts::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);
+ log::error!(
+ "failed to register SSH domain for {:?}: {err:#}",
+ spec.label
+ );
return;
}
};
@@ -1634,7 +1619,12 @@ impl super::TermWindow {
}
self.snapshot_active_project_session_layout();
- let _ = crate::project_sessions::create_host_session(&project_id, &workspace_name);
+ let _ = crate::project_sessions::create_remote_host_session(
+ &project_id,
+ &spec.label,
+ crate::ssh_hosts::host_project_path(&spec),
+ &workspace_name,
+ );
let size = self.config.initial_size(
self.dimensions.dpi as u32,
@@ -1671,7 +1661,7 @@ impl super::TermWindow {
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 crate::ssh_hosts::set_host_distro(&detect_project, &distro) {
if let Some(win) = detect_window.as_ref() {
win.invalidate();
}
@@ -1986,17 +1976,6 @@ impl super::TermWindow {
.detach();
}
- fn spawn_window_tab_from_active_pane(&mut self) {
- let pane = match self.get_active_pane_or_overlay() {
- Some(pane) => pane,
- None => return,
- };
- let assignment = KeyAssignment::SpawnTab(SpawnTabDomain::CurrentPaneDomain);
- if let Err(err) = self.perform_key_assignment(&pane, &assignment) {
- log::error!("tab bar double-click new tab failed: {err:#}");
- }
- }
-
fn tab_context_action(tab_idx: usize, action: KeyAssignment) -> KeyAssignment {
KeyAssignment::Multiple(vec![KeyAssignment::ActivateTab(tab_idx as isize), action])
}
@@ -2119,19 +2098,16 @@ impl super::TermWindow {
match event.kind {
WMEK::Press(MousePress::Left) => match item {
TabBarItem::Tab { tab_idx, .. } => {
+ self.set_content_view_active(false);
self.activate_tab(tab_idx as isize).ok();
}
+ TabBarItem::ContentView => {
+ self.set_content_view_active(true);
+ }
TabBarItem::NewTabButton { .. } => {
self.do_new_tab_button_click(MousePress::Left);
}
TabBarItem::None | TabBarItem::LeftStatus | TabBarItem::RightStatus => {
- if self.last_mouse_click.as_ref().map(|c| c.streak) == Some(2) {
- self.window_drag_position.take();
- self.spawn_window_tab_from_active_pane();
- context.invalidate();
- return;
- }
-
let maximized = self
.window_state
.intersects(WindowState::MAXIMIZED | WindowState::FULL_SCREEN);
@@ -2150,9 +2126,15 @@ impl super::TermWindow {
}
// Potentially starting a drag by the tab bar
if !maximized {
+ #[cfg(target_os = "macos")]
+ {
+ context.request_drag_move();
+ }
+ #[cfg(not(target_os = "macos"))]
self.window_drag_position.replace(event.clone());
+ #[cfg(not(target_os = "macos"))]
+ context.request_drag_move();
}
- context.request_drag_move();
}
TabBarItem::WindowButton(button) => {
use window::IntegratedTitleButton as Button;
@@ -2184,6 +2166,7 @@ impl super::TermWindow {
TabBarItem::None
| TabBarItem::LeftStatus
| TabBarItem::RightStatus
+ | TabBarItem::ContentView
| TabBarItem::WindowButton(_) => {}
},
WMEK::Press(MousePress::Right) => match item {
@@ -2196,6 +2179,7 @@ impl super::TermWindow {
TabBarItem::None
| TabBarItem::LeftStatus
| TabBarItem::RightStatus
+ | TabBarItem::ContentView
| TabBarItem::WindowButton(_) => {}
},
WMEK::Move => match item {
@@ -2214,6 +2198,7 @@ impl super::TermWindow {
}
TabBarItem::WindowButton(_)
| TabBarItem::Tab { .. }
+ | TabBarItem::ContentView
| TabBarItem::NewTabButton { .. } => {}
},
WMEK::HorzWheel(amount) => {
diff --git a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs
index 3b4f42a1..a43ddb69 100644
--- a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs
+++ b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs
@@ -3,12 +3,13 @@ use crate::quad::{QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorT
use crate::tabbar::{TabBarItem, TabEntry};
use crate::termwindow::ui::icons::SvgIcon;
use crate::termwindow::ui::tokens::{
- CAPSULE_BORDER_WIDTH, SIDEBAR_INSET, TAB_CLOSE_HOVER_INSET, TAB_CLOSE_HOVER_RADIUS,
- TAB_CLOSE_RIGHT_GAP, TAB_ROW_START_PADDING, TAB_VERTICAL_PADDING,
- WINDOW_TAB_ACTION_RESERVED_WIDTH, WINDOW_TAB_FULLSCREEN_SIDEBAR_BUTTON_SIZE,
- WINDOW_TAB_FULLSCREEN_SIDEBAR_BUTTON_Y_OFFSET, WINDOW_TAB_FULLSCREEN_SIDEBAR_ICON_SIZE,
- WINDOW_TAB_GAP, WINDOW_TAB_LEADING_ACTION_BUTTON_SIZE, WINDOW_TAB_LEADING_ACTION_GAP,
- WINDOW_TAB_LEADING_ACTION_ICON_SIZE, WINDOW_TAB_RADIUS, WINDOW_TAB_TOP_SPACER,
+ CAPSULE_BORDER_WIDTH, ICON_BUTTON_BORDER_WIDTH, SIDEBAR_INSET, TAB_CLOSE_HOVER_INSET,
+ TAB_CLOSE_HOVER_RADIUS, TAB_CLOSE_RIGHT_GAP, TAB_ROW_START_PADDING, TAB_VERTICAL_PADDING,
+ WINDOW_TAB_ACTION_RESERVED_WIDTH, WINDOW_TAB_ADD_BUTTON_RADIUS,
+ WINDOW_TAB_FULLSCREEN_SIDEBAR_BUTTON_SIZE, WINDOW_TAB_FULLSCREEN_SIDEBAR_BUTTON_Y_OFFSET,
+ WINDOW_TAB_FULLSCREEN_SIDEBAR_ICON_SIZE, WINDOW_TAB_GAP, WINDOW_TAB_LEADING_ACTION_BUTTON_SIZE,
+ WINDOW_TAB_LEADING_ACTION_GAP, WINDOW_TAB_LEADING_ACTION_ICON_SIZE, WINDOW_TAB_RADIUS,
+ WINDOW_TAB_TOP_SPACER,
};
use crate::termwindow::{TermWindowNotif, UIItem, UIItemType};
use crate::ui::UiPalette;
@@ -17,6 +18,7 @@ use anyhow::Context;
use finl_unicode::grapheme_clusters::Graphemes;
use std::rc::Rc;
use termwiz::cell::grapheme_column_width;
+use termwiz::cell::CellAttributes;
use wezterm_bidi::Direction;
use wezterm_font::LoadedFont;
use wezterm_term::Line;
@@ -144,12 +146,17 @@ impl crate::TermWindow {
.and_then(|window| window.idx_by_id(tab_id))
});
+ // When a content view is the foreground, no mux tab is "active".
+ let cv_present = self.content_view.is_some();
+ let cv_active = self.content_view_active;
+
let tab_step = tab_width + WINDOW_TAB_GAP;
let mut tab_sequence_idx = 0usize;
for item in self.tab_bar.items() {
let TabBarItem::Tab { tab_idx, active } = item.item else {
continue;
};
+ let active = active && !cv_active;
let virtual_left = tab_sequence_idx as f32 * tab_step as f32 - scroll_offset;
tab_sequence_idx += 1;
@@ -192,6 +199,46 @@ impl crate::TermWindow {
)?;
}
+ // Synthetic content-view tab (e.g. SSH Hosts), placed after the mux tabs.
+ if cv_present {
+ let virtual_left = tab_sequence_idx as f32 * tab_step as f32 - scroll_offset;
+ let tab_left = viewport_left as f32 + virtual_left;
+ let tab_right = tab_left + tab_width as f32;
+ if tab_right > viewport_left as f32 && tab_left < viewport_right as f32 {
+ let visible_left = tab_left.max(viewport_left as f32);
+ let visible_right = tab_right.min(viewport_right as f32);
+ let visible_width = (visible_right - visible_left).max(0.0);
+ if visible_width > 1.0 {
+ let title = self
+ .content_view
+ .as_ref()
+ .map(|v| v.title())
+ .unwrap_or_default();
+ self.paint_content_view_tab(
+ layers,
+ &mut ui_items,
+ &title,
+ cv_active,
+ tab_left,
+ visible_left,
+ visible_width,
+ viewport_left,
+ viewport_right,
+ content_row_y,
+ content_row_height,
+ tab_width,
+ button_size,
+ icon_size,
+ &font,
+ metrics,
+ chrome,
+ background,
+ if cv_active { foreground } else { muted_fg },
+ )?;
+ }
+ }
+ }
+
self.paint_window_tab_new_button(
layers,
&mut ui_items,
@@ -523,6 +570,135 @@ impl crate::TermWindow {
Ok(())
}
+ #[allow(clippy::too_many_arguments)]
+ fn paint_content_view_tab(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ ui_items: &mut Vec<UIItem>,
+ title: &str,
+ active: bool,
+ tab_left: f32,
+ visible_left: f32,
+ visible_width: f32,
+ viewport_left: usize,
+ viewport_right: usize,
+ row_y: usize,
+ row_height: usize,
+ tab_width: usize,
+ button_size: usize,
+ icon_size: usize,
+ font: &Rc<LoadedFont>,
+ metrics: RenderMetrics,
+ chrome: UiPalette,
+ background: LinearRgba,
+ foreground: LinearRgba,
+ ) -> anyhow::Result<()> {
+ let is_hovered = self.is_pointer_over_ui_rect(
+ visible_left.max(0.0) as usize,
+ row_y,
+ visible_width.max(0.0) as usize,
+ row_height,
+ );
+ let surface = if active {
+ chrome.control_bg
+ } else if is_hovered {
+ chrome.control_hover_bg
+ } else {
+ background
+ };
+ let tab_surface_y = row_y + (row_height.saturating_sub(button_size) / 2);
+ self.fill_rounded_rectangle_with_border(
+ layers,
+ 1,
+ euclid::rect(
+ visible_left,
+ tab_surface_y as f32,
+ visible_width,
+ button_size as f32,
+ ),
+ surface,
+ if active {
+ chrome.control_border
+ } else {
+ LinearRgba::TRANSPARENT
+ },
+ WINDOW_TAB_RADIUS,
+ CAPSULE_BORDER_WIDTH,
+ )
+ .context("content view tab surface")?;
+
+ ui_items.push(UIItem {
+ x: visible_left.max(0.0) as usize,
+ y: row_y,
+ width: visible_width.max(0.0) as usize,
+ height: row_height,
+ item_type: UIItemType::TabBar(TabBarItem::ContentView),
+ });
+
+ let tab_left = tab_left.max(0.0) as usize;
+ let icon_x = tab_left + WINDOW_TAB_INSET;
+ let icon_y = row_y + (row_height.saturating_sub(icon_size) / 2);
+ if icon_x >= viewport_left && icon_x.saturating_add(icon_size) <= viewport_right {
+ self.paint_fancy_tab_icon(
+ layers,
+ SvgIcon::Link2,
+ icon_x,
+ icon_y,
+ icon_size,
+ foreground,
+ )?;
+ }
+
+ let close_x = tab_left
+ .saturating_add(tab_width)
+ .saturating_sub(button_size + TAB_CLOSE_RIGHT_GAP);
+ let close_y = row_y + (row_height.saturating_sub(button_size) / 2);
+ let show_close =
+ close_x >= viewport_left && close_x.saturating_add(button_size) <= viewport_right;
+ if show_close {
+ let close_hovered =
+ self.is_pointer_over_ui_rect(close_x, close_y, button_size, button_size);
+ ui_items.push(UIItem {
+ x: close_x,
+ y: close_y,
+ width: button_size,
+ height: button_size,
+ item_type: UIItemType::ContentViewClose,
+ });
+ self.paint_fancy_tab_icon(
+ layers,
+ SvgIcon::X,
+ close_x + (button_size.saturating_sub(icon_size) / 2),
+ icon_y,
+ icon_size,
+ if close_hovered {
+ foreground
+ } else {
+ foreground.mul_alpha(0.82)
+ },
+ )?;
+ }
+
+ let text_x = icon_x + icon_size + WINDOW_TAB_ICON_GAP;
+ let text_right = if show_close {
+ close_x.saturating_sub(WINDOW_TAB_ICON_GAP)
+ } else {
+ tab_left
+ .saturating_add(tab_width)
+ .saturating_sub(WINDOW_TAB_INSET)
+ }
+ .min(viewport_right);
+ let text_width = text_right.saturating_sub(text_x);
+ let text_y = row_y + (row_height.saturating_sub(metrics.cell_size.height as usize) / 2);
+ if text_x >= viewport_left && text_x < viewport_right {
+ let line = Line::from_text(title, &CellAttributes::blank(), 0, None);
+ self.paint_fancy_tab_text(
+ layers, font, &line, false, text_x, text_y, text_width, foreground,
+ )?;
+ }
+ Ok(())
+ }
+
#[allow(clippy::too_many_arguments)]
fn paint_window_tab_new_button(
&self,
@@ -536,27 +712,34 @@ impl crate::TermWindow {
foreground: LinearRgba,
muted_fg: LinearRgba,
) -> anyhow::Result<()> {
- let button_x = row_right.saturating_sub(WINDOW_TAB_INSET + button_size);
+ let button_x = row_right.saturating_sub(WINDOW_TAB_INSET + button_size + 2);
let button_y = row_y + (row_height.saturating_sub(button_size) / 2);
let hovered = self.is_pointer_over_ui_rect(button_x, button_y, button_size, button_size);
+ let pressed = hovered
+ && self.is_pointer_pressing_ui_rect(button_x, button_y, button_size, button_size);
+ let press_inset = if pressed { 1 } else { 0 };
+ let visual_size = button_size.saturating_sub(press_inset * 2);
if hovered {
- let hover_alpha =
- if self.is_pointer_pressing_ui_rect(button_x, button_y, button_size, button_size) {
- 0.20
- } else {
- 0.12
- };
- self.fill_rounded_rectangle(
+ let chrome = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ let fill = if pressed {
+ chrome.control_pressed_bg
+ } else {
+ chrome.control_hover_bg
+ };
+ let border_alpha = if pressed { 0.52 } else { 0.38 };
+ self.fill_rounded_rectangle_with_border(
layers,
1,
euclid::rect(
- button_x as f32,
- button_y as f32,
- button_size as f32,
- button_size as f32,
+ (button_x + press_inset) as f32,
+ (button_y + press_inset) as f32,
+ visual_size as f32,
+ visual_size as f32,
),
- foreground.mul_alpha(hover_alpha),
- 5.0,
+ fill,
+ foreground.mul_alpha(border_alpha),
+ WINDOW_TAB_ADD_BUTTON_RADIUS,
+ ICON_BUTTON_BORDER_WIDTH,
)
.context("window tab new button hover")?;
}
@@ -569,11 +752,16 @@ impl crate::TermWindow {
item_type: UIItemType::TabBar(TabBarItem::NewTabButton),
});
+ let icon_size = if pressed {
+ icon_size.saturating_sub(1).max(1)
+ } else {
+ icon_size
+ };
self.paint_fancy_tab_icon(
layers,
SvgIcon::Plus,
- button_x + (button_size.saturating_sub(icon_size) / 2),
- button_y + (button_size.saturating_sub(icon_size) / 2),
+ button_x + press_inset + (visual_size.saturating_sub(icon_size) / 2),
+ button_y + press_inset + (visual_size.saturating_sub(icon_size) / 2),
icon_size,
if hovered { foreground } else { muted_fg },
)
diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rs
index daaa1350..8671883c 100644
--- a/wezterm-gui/src/termwindow/render/paint.rs
+++ b/wezterm-gui/src/termwindow/render/paint.rs
@@ -1,5 +1,6 @@
+use crate::quad::TripleLayerQuadAllocator;
use crate::termwindow::{RenderFrame, TermWindowNotif};
-use crate::ui::UiPalette;
+use crate::ui::{DrawContext, UiPalette};
use ::window::bitmaps::atlas::OutOfTextureSpace;
use ::window::WindowOps;
use anyhow::Context;
@@ -182,6 +183,74 @@ impl crate::TermWindow {
}
}
+ /// Paint the active content view into the content area (right of the
+ /// sidebar, below the tab bar).
+ pub fn paint_content_view(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ ) -> anyhow::Result<()> {
+ let settings = crate::native_settings::load();
+ let font_size = crate::native_settings::settings_font_size(&settings);
+ let font_weight = crate::native_settings::settings_font_weight(&settings);
+ let ui_font = self
+ .fonts
+ .command_palette_font_with_size_and_weight(font_size, font_weight)?;
+ let render_metrics =
+ crate::utilsprites::RenderMetrics::with_font_metrics(&ui_font.metrics());
+ let dimensions = self.dimensions;
+ let palette = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+
+ // Occupy exactly the terminal content area: right of the (possibly
+ // collapsed) sidebar and below the tab bar. padding_left_top().0 already
+ // includes the effective sidebar width.
+ let (padding_left, padding_top) = self.padding_left_top();
+ let border = self.get_os_border();
+ let top_tab_h = if self.show_tab_bar && !self.config.tab_bar_at_bottom {
+ self.tab_bar_pixel_height().unwrap_or(0.0)
+ } else {
+ 0.0
+ };
+ let bottom_tab_h = if self.show_tab_bar && self.config.tab_bar_at_bottom {
+ self.tab_bar_pixel_height().unwrap_or(0.0)
+ } else {
+ 0.0
+ };
+ let left = padding_left + border.left.get() as f32;
+ let top = border.top.get() as f32 + top_tab_h + padding_top;
+ let width = (dimensions.pixel_width as f32 - left - border.right.get() as f32).max(0.0);
+ let height =
+ (dimensions.pixel_height as f32 - top - border.bottom.get() as f32 - bottom_tab_h)
+ .max(0.0);
+ let area = euclid::rect(left, top, width, height);
+
+ // Cursor blink: only animate when the view wants it (focused input).
+ let wants_blink = self
+ .content_view
+ .as_ref()
+ .map(|v| v.wants_cursor_blink())
+ .unwrap_or(false);
+ let blink_ms = (self.config.cursor_blink_rate as u64).max(100);
+ let cursor_on = if wants_blink {
+ let ms = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis())
+ .unwrap_or(0);
+ (ms / blink_ms as u128) % 2 == 0
+ } else {
+ true
+ };
+ if wants_blink {
+ self.update_next_frame_time(Some(Instant::now() + Duration::from_millis(blink_ms)));
+ }
+
+ let gl_state = self.render_state.as_ref().unwrap();
+ let ctx = DrawContext::new(gl_state, dimensions, &render_metrics);
+ if let Some(view) = self.content_view.as_mut() {
+ view.paint(&ctx, layers, area, palette, &ui_font, cursor_on)?;
+ }
+ Ok(())
+ }
+
pub fn paint_modal(&mut self) -> anyhow::Result<()> {
if let Some(modal) = self.get_modal() {
for computed in modal.computed_element(self)?.iter() {
@@ -312,23 +381,34 @@ impl crate::TermWindow {
.context("filled_rectangle for chrome header background")?;
}
- for pos in panes {
- if pos.is_active {
- self.update_text_cursor(&pos);
- if focused {
- pos.pane.advise_focus();
- mux::Mux::get().record_focus_for_current_identity(pos.pane.pane_id());
+ // When a content view is the foreground it takes over the content area,
+ // so skip painting the terminal panes / splits.
+ let content_view_active = self.content_view_foreground();
+
+ if !content_view_active {
+ for pos in panes {
+ if pos.is_active {
+ self.update_text_cursor(&pos);
+ if focused {
+ pos.pane.advise_focus();
+ mux::Mux::get().record_focus_for_current_identity(pos.pane.pane_id());
+ }
+ }
+ self.paint_pane(&pos, &mut layers).context("paint_pane")?;
+ }
+
+ if let Some(pane) = self.get_active_pane_or_overlay() {
+ let splits = self.get_splits();
+ for split in &splits {
+ self.paint_split(&mut layers, split, &pane)
+ .context("paint_split")?;
}
}
- self.paint_pane(&pos, &mut layers).context("paint_pane")?;
}
- if let Some(pane) = self.get_active_pane_or_overlay() {
- let splits = self.get_splits();
- for split in &splits {
- self.paint_split(&mut layers, split, &pane)
- .context("paint_split")?;
- }
+ if content_view_active {
+ self.paint_content_view(&mut layers)
+ .context("paint_content_view")?;
}
self.paint_workspace_sidebar(&mut layers)
diff --git a/wezterm-gui/src/termwindow/render/pane.rs b/wezterm-gui/src/termwindow/render/pane.rs
index 101834c4..1bdff7d2 100644
--- a/wezterm-gui/src/termwindow/render/pane.rs
+++ b/wezterm-gui/src/termwindow/render/pane.rs
@@ -11,9 +11,10 @@ use crate::termwindow::ui::icons::SvgIcon;
use crate::termwindow::ui::pane_nav_bar_height_for_metrics;
use crate::termwindow::ui::status_icon::{split_leading_legacy_progress_marker, UiStatusKind};
use crate::termwindow::ui::tokens::{
- CAPSULE_BORDER_WIDTH, PANE_NAV_BUTTON_GAP, PANE_NAV_ICON_GAP, PANE_NAV_INSET, PANE_NAV_TAB_GAP,
- PANE_NAV_TAB_RADIUS, PANE_NAV_TAB_TOP_OFFSET, TAB_CLOSE_HOVER_INSET, TAB_CLOSE_HOVER_RADIUS,
- TAB_CLOSE_RIGHT_GAP, TAB_VERTICAL_PADDING,
+ CAPSULE_BORDER_WIDTH, ICON_BUTTON_BORDER_WIDTH, PANE_NAV_ACTION_BUTTON_RADIUS,
+ PANE_NAV_BUTTON_GAP, PANE_NAV_ICON_GAP, PANE_NAV_INSET, PANE_NAV_TAB_GAP, PANE_NAV_TAB_RADIUS,
+ PANE_NAV_TAB_TOP_OFFSET, TAB_CLOSE_HOVER_INSET, TAB_CLOSE_HOVER_RADIUS, TAB_CLOSE_RIGHT_GAP,
+ TAB_VERTICAL_PADDING,
};
use crate::termwindow::{PaneNavAction, ScrollHit, UIItem, UIItemType};
use crate::ui::UiPalette;
@@ -539,6 +540,7 @@ impl crate::TermWindow {
.min(nav_height.saturating_sub(button_size));
let mut button_x = (pane_x + pane_width) as usize;
let mut actions = vec![
+ (SvgIcon::Plus, PaneNavAction::NewTab),
(SvgIcon::SplitVertical, PaneNavAction::SplitDown),
(SvgIcon::SplitHorizontal, PaneNavAction::SplitRight),
];
@@ -555,6 +557,11 @@ impl crate::TermWindow {
));
for (icon, action) in actions {
button_x = button_x.saturating_sub(button_size + PANE_NAV_BUTTON_GAP);
+ // Stop once a button would spill past the pane's left edge (happens
+ // when the pane is too narrow to hold all the action buttons).
+ if (button_x as f32) < pane_x {
+ break;
+ }
self.paint_pane_nav_icon_button(
layers,
icon,
@@ -819,27 +826,44 @@ impl crate::TermWindow {
});
let hovered = self.is_pointer_over_ui_rect(x, y, button_size, button_size);
+ let pressed = hovered && self.is_pointer_pressing_ui_rect(x, y, button_size, button_size);
+ let press_inset = if pressed { 1 } else { 0 };
+ let visual_size = button_size.saturating_sub(press_inset * 2);
if hovered {
- let hover_alpha = if self.is_pointer_pressing_ui_rect(x, y, button_size, button_size) {
- 0.20
+ let chrome = UiPalette::for_appearance(crate::native_settings::effective_appearance());
+ let fill = if pressed {
+ chrome.control_pressed_bg
} else {
- 0.12
+ chrome.control_hover_bg
};
- self.fill_rounded_rectangle(
+ let border_alpha = if pressed { 0.52 } else { 0.38 };
+ self.fill_rounded_rectangle_with_border(
layers,
1,
- euclid::rect(x as f32, y as f32, button_size as f32, button_size as f32),
- color.mul_alpha(hover_alpha),
- 5.0,
+ euclid::rect(
+ (x + press_inset) as f32,
+ (y + press_inset) as f32,
+ visual_size as f32,
+ visual_size as f32,
+ ),
+ fill,
+ color.mul_alpha(border_alpha),
+ PANE_NAV_ACTION_BUTTON_RADIUS,
+ ICON_BUTTON_BORDER_WIDTH,
)
.context("pane nav button hover")?;
}
+ let icon_size = if pressed {
+ icon_size.saturating_sub(1).max(1)
+ } else {
+ icon_size
+ };
self.paint_pane_nav_icon(
layers,
icon,
- x + ((button_size.saturating_sub(icon_size)) / 2),
- y + ((button_size.saturating_sub(icon_size)) / 2),
+ x + press_inset + ((visual_size.saturating_sub(icon_size)) / 2),
+ y + press_inset + ((visual_size.saturating_sub(icon_size)) / 2),
icon_size,
if hovered { hover_color } else { color },
)
diff --git a/wezterm-gui/src/termwindow/render/screen_line.rs b/wezterm-gui/src/termwindow/render/screen_line.rs
index 3bf75aa8..0089687a 100644
--- a/wezterm-gui/src/termwindow/render/screen_line.rs
+++ b/wezterm-gui/src/termwindow/render/screen_line.rs
@@ -451,10 +451,6 @@ impl crate::TermWindow {
}
};
- // TODO: remember logical/visual mapping for selection
- #[allow(unused_variables)]
- let mut phys_cell_idx = cluster.first_cell_idx;
-
// Pre-decrement by the cluster width when doing RTL,
// so that we can render it right-justified
if direction == Direction::RightToLeft {
@@ -681,7 +677,6 @@ impl crate::TermWindow {
}
}
}
- phys_cell_idx += info.pos.num_cells as usize;
visual_cell_idx += info.pos.num_cells as usize;
cluster_x_pos += if params.use_pixel_positioning {
glyph.x_advance.get() as f32 * width_scale
diff --git a/wezterm-gui/src/termwindow/ssh_hosts_modal.rs b/wezterm-gui/src/termwindow/ssh_hosts_modal.rs
deleted file mode 100644
index d4762f5c..00000000
--- a/wezterm-gui/src/termwindow/ssh_hosts_modal.rs
+++ /dev/null
@@ -1,792 +0,0 @@
-//! 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/ssh_hosts_view.rs b/wezterm-gui/src/termwindow/ssh_hosts_view.rs
new file mode 100644
index 00000000..6de75fe5
--- /dev/null
+++ b/wezterm-gui/src/termwindow/ssh_hosts_view.rs
@@ -0,0 +1,1425 @@
+//! In-window SSH hosts manager: a full-content-area "page" (left host list +
+//! right edit form) that replaces the terminal area when toggled from the
+//! sidebar `link-2` button. Draws with the shared `ui::draw`/`ui::widgets`
+//! infrastructure. The view owns its state + hit-testing and exposes a tiny
+//! [`SshViewOutcome`] so `TermWindow` integration stays minimal.
+
+use crate::project_sessions;
+use crate::quad::TripleLayerQuadAllocator;
+use crate::ssh_hosts::{self, SshHostEntry, SshHostSource, SshHostSpec};
+use crate::termwindow::content_view::{ContentView, ContentViewResponse};
+use crate::termwindow::ui::icons::{distro_to_icon, SvgIcon};
+use crate::termwindow::TermWindow;
+use crate::ui::{
+ draw_button, draw_icon_button, draw_scrollbar, draw_text_input, draw_toggle, rect,
+ wheel_delta_pixels, ButtonSpec, ControlState, DrawContext, InteractionState, ScrollState,
+ TextInputSpec, UiContext, UiPalette, UiTokens, WidgetKind,
+};
+use std::rc::Rc;
+use wezterm_font::LoadedFont;
+use wezterm_term::{KeyCode, KeyModifiers};
+use window::color::LinearRgba;
+use window::{MouseEventKind as WMEK, MousePress, RectF};
+
+const FIELD_NAME: usize = 0;
+const FIELD_HOST: usize = 1;
+const FIELD_PORT: usize = 2;
+const FIELD_USER: usize = 3;
+const FIELD_PASSWORD: usize = 4;
+const FIELD_IDENTITY: usize = 5;
+const FIELD_WORKSPACE: usize = 6;
+const FIELD_COUNT: usize = 7;
+const FIELD_LABELS: [&str; FIELD_COUNT] = [
+ "Name",
+ "Host",
+ "Port",
+ "User",
+ "Password",
+ "Identity file",
+ "Workspace",
+];
+
+const PAD: f32 = 20.0;
+const LEFT_DEFAULT_W: f32 = 500.0;
+const LEFT_MIN_W: f32 = 360.0;
+const LEFT_MAX_W: f32 = 680.0;
+const RIGHT_MIN_W: f32 = 360.0;
+const SPLIT_HANDLE_W: f32 = 14.0;
+const ROW_MIN_H: f32 = 92.0;
+const ROW_GAP: f32 = 14.0;
+const GROUP_ROW_H: f32 = 44.0;
+const INPUT_H: f32 = 44.0;
+const BTN_H: f32 = 42.0;
+const HOST_ROW_RADIUS: f32 = 14.0;
+const HOST_ACTION_RIGHT_PAD: f32 = 14.0;
+const HOST_ACTION_GAP: f32 = 8.0;
+const HOST_ACTION_BTN: f32 = 32.0;
+const LIST_FADE_HEIGHT: f32 = 32.0;
+
+/// Clickable targets inside the view. `usize` payloads index into the current
+/// filtered host list, so the action type stays `Copy` (needed by `UiContext`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+enum SshViewAction {
+ Search,
+ Connect(usize),
+ Edit(usize),
+ Delete(usize),
+ New,
+ FocusField(usize),
+ ToggleDetect,
+ Save,
+ SaveAndConnect,
+ Cancel,
+ ToggleSystemHosts,
+ ResizeLeftPane,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Focus {
+ Search,
+ Field(usize),
+}
+
+#[derive(Default, Clone)]
+struct HostForm {
+ editing: Option<String>,
+ original: Option<SshHostSpec>,
+ fields: [String; FIELD_COUNT],
+ detect_os: bool,
+ error: Option<String>,
+}
+
+pub(crate) struct SshHostsView {
+ search: String,
+ selected: usize,
+ focus: Focus,
+ form: Option<HostForm>,
+ filtered: Vec<SshHostEntry>,
+ system_host_count: usize,
+ system_hosts_collapsed: bool,
+ left_width: f32,
+ dragging_left_pane: bool,
+ last_area_x: f32,
+ last_area_w: f32,
+ list_area: RectF,
+ /// When true the focused field is "select-all"; the next edit replaces it.
+ select_all: bool,
+ widgets: UiContext<SshViewAction>,
+ interaction: InteractionState<SshViewAction>,
+ scroll: ScrollState,
+}
+
+impl SshHostsView {
+ pub(crate) fn new() -> Self {
+ let mut view = Self {
+ search: String::new(),
+ selected: 0,
+ focus: Focus::Search,
+ form: None,
+ filtered: Vec::new(),
+ system_host_count: 0,
+ system_hosts_collapsed: true,
+ left_width: LEFT_DEFAULT_W,
+ dragging_left_pane: false,
+ last_area_x: 0.0,
+ last_area_w: 0.0,
+ list_area: rect(0.0, 0.0, 0.0, 0.0),
+ select_all: false,
+ widgets: UiContext::default(),
+ interaction: InteractionState::default(),
+ scroll: ScrollState::new(),
+ };
+ view.refresh();
+ view
+ }
+
+ fn refresh(&mut self) {
+ let needle = self.search.trim().to_ascii_lowercase();
+ let show_system_hosts = !self.system_hosts_collapsed || !needle.is_empty();
+ self.system_host_count = 0;
+ self.filtered = ssh_hosts::list_all_hosts()
+ .into_iter()
+ .filter(|entry| {
+ if needle.is_empty() {
+ return true;
+ }
+ format!(
+ "{} {} {}",
+ entry.spec.label,
+ entry.spec.host,
+ entry.spec.username.as_deref().unwrap_or("")
+ )
+ .to_ascii_lowercase()
+ .contains(&needle)
+ })
+ .filter(|entry| {
+ if entry.source == SshHostSource::System {
+ self.system_host_count += 1;
+ show_system_hosts
+ } else {
+ true
+ }
+ })
+ .collect();
+ if self.filtered.is_empty() {
+ self.selected = 0;
+ } else {
+ self.selected = self.selected.min(self.filtered.len() - 1);
+ }
+ }
+
+ // ---- form helpers -----------------------------------------------------
+
+ fn open_new_form(&mut self) {
+ let mut form = HostForm::default();
+ form.fields[FIELD_PORT] = "22".to_string();
+ form.detect_os = true;
+ self.form = Some(form);
+ self.focus = Focus::Field(FIELD_HOST);
+ }
+
+ fn open_edit_form(&mut self, project_id: &str) {
+ if ssh_hosts::is_system_host_id(project_id) {
+ return;
+ }
+ let Some(spec) = ssh_hosts::host_spec(project_id) else {
+ return;
+ };
+ let mut fields: [String; FIELD_COUNT] = Default::default();
+ fields[FIELD_NAME] = 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_PASSWORD] = spec
+ .password
+ .as_deref()
+ .map(crate::secret::reveal)
+ .unwrap_or_default();
+ fields[FIELD_IDENTITY] = spec.identity_file.clone().unwrap_or_default();
+ fields[FIELD_WORKSPACE] = spec.default_workspace.clone().unwrap_or_default();
+ let detect_os = spec.detect_os;
+ self.form = Some(HostForm {
+ editing: Some(project_id.to_string()),
+ original: Some(spec),
+ fields,
+ detect_os,
+ error: None,
+ });
+ self.focus = Focus::Field(FIELD_HOST);
+ }
+
+ fn close_form(&mut self) {
+ self.form = None;
+ self.focus = Focus::Search;
+ }
+
+ /// Validate + create/update. On success returns the project id and closes
+ /// the form; on error records the message and keeps the form open.
+ fn persist_form(&mut self) -> Option<String> {
+ let form = self.form.as_mut()?;
+ let host = form.fields[FIELD_HOST].trim().to_string();
+ if host.is_empty() {
+ form.error = Some("Host is required".to_string());
+ 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());
+ return None;
+ }
+ },
+ };
+ let opt = |s: &str| {
+ let t = s.trim();
+ (!t.is_empty()).then(|| t.to_string())
+ };
+ let label = opt(&form.fields[FIELD_NAME]).unwrap_or_else(|| host.clone());
+
+ let mut spec = form.original.clone().unwrap_or_else(|| SshHostSpec {
+ label: label.clone(),
+ host: host.clone(),
+ port,
+ username: None,
+ identity_file: None,
+ password: None,
+ ssh_options: Default::default(),
+ multiplexing: false,
+ 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]);
+ // Encrypt the password before it is persisted to ssh_hosts.json. Never
+ // fall back to plaintext: if encryption fails, keep the form open.
+ spec.password = match opt(&form.fields[FIELD_PASSWORD]) {
+ Some(password) => match crate::secret::encrypt(&password) {
+ Ok(encrypted) => Some(encrypted),
+ Err(err) => {
+ log::error!("failed to encrypt SSH password: {err:#}");
+ form.error = Some(format!("Failed to encrypt password: {err:#}"));
+ return None;
+ }
+ },
+ None => None,
+ };
+ 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) => match ssh_hosts::try_update_host(id, spec) {
+ Ok(true) => id.clone(),
+ Ok(false) => {
+ form.error = Some("Host no longer exists".to_string());
+ return None;
+ }
+ Err(err) => {
+ form.error = Some(format!("Failed to save host: {err:#}"));
+ return None;
+ }
+ },
+ None => match ssh_hosts::try_create_host(spec) {
+ Ok(id) => id,
+ Err(err) => {
+ form.error = Some(format!("Failed to save host: {err:#}"));
+ return None;
+ }
+ },
+ };
+ self.close_form();
+ self.refresh();
+ Some(project_id)
+ }
+
+ // ---- input ------------------------------------------------------------
+
+ fn on_mouse_impl(&mut self, x: f32, y: f32, kind: WMEK) -> ContentViewResponse {
+ let hit = self.widgets.hit_test(x, y).map(|t| t.action);
+ match kind {
+ WMEK::VertWheel(amount) => {
+ if self.point_in_host_list(x, y) {
+ let old = self.scroll.offset;
+ self.scroll.scroll_by(wheel_delta_pixels(amount));
+ if (self.scroll.offset - old).abs() > 0.01 {
+ ContentViewResponse::Redraw
+ } else {
+ ContentViewResponse::Ignored
+ }
+ } else {
+ ContentViewResponse::Ignored
+ }
+ }
+ WMEK::Move => {
+ if self.dragging_left_pane {
+ self.left_width =
+ Self::clamp_left_width(x - self.last_area_x, self.last_area_w);
+ return ContentViewResponse::Redraw;
+ }
+ if self.interaction.hovered != hit {
+ self.interaction.hovered = hit;
+ ContentViewResponse::Redraw
+ } else {
+ ContentViewResponse::Ignored
+ }
+ }
+ WMEK::Press(MousePress::Left) => {
+ self.interaction.pressed = hit;
+ if hit == Some(SshViewAction::ResizeLeftPane) {
+ self.dragging_left_pane = true;
+ }
+ ContentViewResponse::Redraw
+ }
+ WMEK::Release(MousePress::Left) => {
+ if self.dragging_left_pane {
+ self.dragging_left_pane = false;
+ self.interaction.pressed = None;
+ return ContentViewResponse::Redraw;
+ }
+ let pressed = self.interaction.pressed.take();
+ if let (Some(a), Some(b)) = (hit, pressed) {
+ if a == b {
+ return self.apply(a);
+ }
+ }
+ ContentViewResponse::Redraw
+ }
+ _ => ContentViewResponse::Ignored,
+ }
+ }
+
+ fn point_in_host_list(&self, x: f32, y: f32) -> bool {
+ x >= self.list_area.origin.x
+ && x <= self.list_area.origin.x + self.list_area.size.width
+ && y >= self.list_area.origin.y
+ && y <= self.list_area.origin.y + self.list_area.size.height
+ }
+
+ fn apply(&mut self, action: SshViewAction) -> ContentViewResponse {
+ self.select_all = false;
+ match action {
+ SshViewAction::Search => {
+ self.focus = Focus::Search;
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::New => {
+ self.open_new_form();
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::Edit(i) => {
+ if let Some(entry) = self.filtered.get(i) {
+ let id = entry.id.clone();
+ if entry.source == SshHostSource::ThinkTerm {
+ self.open_edit_form(&id);
+ }
+ }
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::Delete(i) => {
+ if let Some(entry) = self.filtered.get(i) {
+ let id = entry.id.clone();
+ if entry.source == SshHostSource::ThinkTerm {
+ if let Err(err) = ssh_hosts::try_remove_host(&id) {
+ log::error!("failed to delete SSH host {id}: {err:#}");
+ } else {
+ let _ = project_sessions::remove_project(&id);
+ }
+ self.refresh();
+ }
+ }
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::FocusField(n) => {
+ self.focus = Focus::Field(n.min(FIELD_COUNT - 1));
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::ToggleDetect => {
+ if let Some(form) = self.form.as_mut() {
+ form.detect_os = !form.detect_os;
+ }
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::Save => {
+ self.persist_form();
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::SaveAndConnect => match self.persist_form() {
+ Some(id) => connect_response(id),
+ None => ContentViewResponse::Redraw,
+ },
+ SshViewAction::Cancel => {
+ self.close_form();
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::ToggleSystemHosts => {
+ self.system_hosts_collapsed = !self.system_hosts_collapsed;
+ self.refresh();
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::ResizeLeftPane => ContentViewResponse::Redraw,
+ SshViewAction::Connect(i) => match self.filtered.get(i) {
+ Some(entry) => connect_response(entry.id.clone()),
+ None => ContentViewResponse::Redraw,
+ },
+ }
+ }
+
+ fn on_key_impl(&mut self, key: KeyCode, mods: KeyModifiers) -> ContentViewResponse {
+ let in_form = self.form.is_some();
+ match (key, mods) {
+ (KeyCode::Escape, _) => {
+ if in_form {
+ self.close_form();
+ ContentViewResponse::Redraw
+ } else {
+ ContentViewResponse::Close
+ }
+ }
+ (KeyCode::Enter, _) => {
+ if in_form {
+ match self.persist_form() {
+ Some(id) => connect_response(id),
+ None => ContentViewResponse::Redraw,
+ }
+ } else if let Some(entry) = self.filtered.get(self.selected) {
+ connect_response(entry.id.clone())
+ } else {
+ ContentViewResponse::Redraw
+ }
+ }
+ (KeyCode::Tab, KeyModifiers::NONE) | (KeyCode::DownArrow, KeyModifiers::NONE) => {
+ if in_form {
+ self.step_field(1);
+ } else if !self.filtered.is_empty() {
+ self.selected = (self.selected + 1).min(self.filtered.len() - 1);
+ }
+ ContentViewResponse::Redraw
+ }
+ (KeyCode::Tab, KeyModifiers::SHIFT) | (KeyCode::UpArrow, KeyModifiers::NONE) => {
+ if in_form {
+ self.step_field(-1);
+ } else {
+ self.selected = self.selected.saturating_sub(1);
+ }
+ ContentViewResponse::Redraw
+ }
+ // Select-all of the focused field (⌘A): next edit replaces it.
+ (KeyCode::Char('a'), m) if m.contains(KeyModifiers::SUPER) => {
+ self.select_all = true;
+ ContentViewResponse::Redraw
+ }
+ (KeyCode::Backspace, _) => {
+ if self.select_all {
+ self.clear_focused();
+ self.select_all = false;
+ } else {
+ self.edit_focused(|s| {
+ s.pop();
+ });
+ }
+ ContentViewResponse::Redraw
+ }
+ (KeyCode::Char(c), KeyModifiers::NONE) | (KeyCode::Char(c), KeyModifiers::SHIFT) => {
+ if self.select_all {
+ self.clear_focused();
+ self.select_all = false;
+ }
+ self.edit_focused(|s| s.push(c));
+ if matches!(self.focus, Focus::Search) {
+ self.selected = 0;
+ self.refresh();
+ }
+ ContentViewResponse::Redraw
+ }
+ _ => ContentViewResponse::Ignored,
+ }
+ }
+
+ fn on_paste_impl(&mut self, text: &str) -> ContentViewResponse {
+ let cleaned: String = text.chars().filter(|c| !c.is_control()).collect();
+ if self.select_all {
+ self.clear_focused();
+ self.select_all = false;
+ }
+ self.edit_focused(|s| s.push_str(&cleaned));
+ if matches!(self.focus, Focus::Search) {
+ self.selected = 0;
+ self.refresh();
+ }
+ ContentViewResponse::Redraw
+ }
+
+ fn step_field(&mut self, delta: isize) {
+ self.select_all = false;
+ if let Focus::Field(n) = self.focus {
+ let next = (n as isize + delta).rem_euclid(FIELD_COUNT as isize) as usize;
+ self.focus = Focus::Field(next);
+ } else {
+ self.focus = Focus::Field(FIELD_HOST);
+ }
+ }
+
+ fn edit_focused(&mut self, f: impl FnOnce(&mut String)) {
+ match self.focus {
+ Focus::Search => f(&mut self.search),
+ Focus::Field(n) => {
+ if let Some(form) = self.form.as_mut() {
+ form.error = None;
+ f(&mut form.fields[n]);
+ }
+ }
+ }
+ }
+
+ fn clear_focused(&mut self) {
+ self.edit_focused(|s| s.clear());
+ }
+
+ fn take_focused_selection(&mut self) -> Option<String> {
+ if !self.select_all {
+ return None;
+ }
+ self.select_all = false;
+ let text = match self.focus {
+ Focus::Search => std::mem::take(&mut self.search),
+ Focus::Field(n) => {
+ let form = self.form.as_mut()?;
+ form.error = None;
+ std::mem::take(&mut form.fields[n])
+ }
+ };
+ if matches!(self.focus, Focus::Search) {
+ self.selected = 0;
+ self.refresh();
+ }
+ (!text.is_empty()).then_some(text)
+ }
+
+ // ---- paint ------------------------------------------------------------
+
+ fn clamp_left_width(width: f32, total_width: f32) -> f32 {
+ let available = (total_width - RIGHT_MIN_W).max(260.0);
+ let max_width = available.min(LEFT_MAX_W).max(260.0);
+ let min_width = LEFT_MIN_W.min(max_width);
+ width.clamp(min_width, max_width)
+ }
+
+ fn paint_impl(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ cursor_on: bool,
+ ) -> anyhow::Result<()> {
+ let tokens = UiTokens::default();
+ self.refresh();
+ self.widgets.clear();
+
+ let ox = area.origin.x;
+ let oy = area.origin.y;
+ let w = area.size.width;
+ let h = area.size.height;
+ self.last_area_x = ox;
+ self.last_area_w = w;
+ self.left_width = Self::clamp_left_width(self.left_width, w);
+
+ // Background.
+ ctx.draw_rect(layers, 0, ox, oy, w, h, palette.window_bg)?;
+
+ let left_w = self.left_width;
+ let left_x = ox + PAD;
+ let inner_left_w = left_w - PAD * 2.0;
+
+ let search_y = oy + PAD + 48.0;
+
+ // Host list.
+ let list_top = search_y + INPUT_H + 14.0;
+ let list_bottom = oy + h - PAD;
+ self.list_area = rect(
+ left_x,
+ list_top,
+ inner_left_w,
+ (list_bottom - list_top).max(0.0),
+ );
+ if self.filtered.is_empty() && self.system_host_count == 0 {
+ self.scroll.set_extents(self.list_area.size.height, 0.0);
+ ctx.draw_text(
+ layers,
+ font,
+ left_x,
+ list_top + 8.0,
+ "No hosts yet. Click + to add.",
+ palette.muted_text,
+ inner_left_w,
+ )?;
+ } else {
+ let filtered = self.filtered.clone();
+ let row_h = Self::host_row_height(ctx);
+ let think_count = filtered
+ .iter()
+ .filter(|entry| entry.source == SshHostSource::ThinkTerm)
+ .count();
+ let visible_system_count =
+ if !self.system_hosts_collapsed || !self.search.trim().is_empty() {
+ filtered
+ .iter()
+ .filter(|entry| entry.source == SshHostSource::System)
+ .count()
+ } else {
+ 0
+ };
+ let mut content_h = Self::rows_height(think_count, row_h);
+ if self.system_host_count > 0 {
+ if content_h > 0.0 {
+ content_h += ROW_GAP + 4.0;
+ } else {
+ content_h += 4.0;
+ }
+ content_h += GROUP_ROW_H + 10.0;
+ content_h += Self::rows_height(visible_system_count, row_h);
+ }
+ self.scroll
+ .set_extents(self.list_area.size.height, content_h);
+
+ let mut row_y = list_top - self.scroll.offset;
+ for (i, entry) in filtered
+ .iter()
+ .enumerate()
+ .filter(|(_, entry)| entry.source == SshHostSource::ThinkTerm)
+ {
+ if row_y > list_bottom {
+ break;
+ }
+ if Self::row_visible(row_y, row_h, list_top, list_bottom) {
+ self.paint_host_row(
+ ctx,
+ layers,
+ font,
+ palette,
+ left_x,
+ row_y,
+ inner_left_w,
+ i,
+ entry,
+ list_top,
+ list_bottom,
+ )?;
+ }
+ row_y += row_h + ROW_GAP;
+ }
+
+ if self.system_host_count > 0 {
+ row_y += 4.0;
+ if Self::row_visible(row_y, GROUP_ROW_H, list_top, list_bottom) {
+ self.paint_system_group_header(
+ ctx,
+ layers,
+ font,
+ palette,
+ left_x,
+ row_y,
+ inner_left_w,
+ list_top,
+ list_bottom,
+ )?;
+ row_y += GROUP_ROW_H + 10.0;
+ }
+ if !self.system_hosts_collapsed || !self.search.trim().is_empty() {
+ for (i, entry) in filtered
+ .iter()
+ .enumerate()
+ .filter(|(_, entry)| entry.source == SshHostSource::System)
+ {
+ if row_y > list_bottom {
+ break;
+ }
+ if Self::row_visible(row_y, row_h, list_top, list_bottom) {
+ self.paint_host_row(
+ ctx,
+ layers,
+ font,
+ palette,
+ left_x,
+ row_y,
+ inner_left_w,
+ i,
+ entry,
+ list_top,
+ list_bottom,
+ )?;
+ }
+ row_y += row_h + ROW_GAP;
+ }
+ }
+ }
+ }
+
+ // Mask scrolled rows back out of the fixed header/search area, then
+ // repaint the header controls above the list. This mirrors the main
+ // workspace sidebar and avoids rows bleeding over "SSH Hosts".
+ self.paint_list_mask(
+ ctx,
+ layers,
+ ox,
+ oy,
+ left_w,
+ (list_top - oy).max(0.0),
+ palette,
+ )?;
+ self.paint_list_mask(
+ ctx,
+ layers,
+ ox,
+ list_bottom,
+ left_w,
+ (oy + h - list_bottom).max(0.0),
+ palette,
+ )?;
+ self.paint_list_fades(ctx, layers, self.list_area, palette)?;
+ self.paint_header_controls(
+ ctx,
+ layers,
+ font,
+ left_x,
+ oy + PAD,
+ search_y,
+ inner_left_w,
+ palette,
+ tokens,
+ cursor_on,
+ )?;
+ if self.scroll.has_overflow() {
+ draw_scrollbar(ctx, layers, palette, tokens, self.list_area, self.scroll)?;
+ }
+
+ // Right pane: form or empty hint.
+ let right_x = ox + left_w + PAD;
+ let right_w = (ox + w - PAD) - right_x;
+ // Vertical separator.
+ let split_x = ox + left_w;
+ ctx.draw_rect(
+ layers,
+ 0,
+ split_x,
+ oy + PAD,
+ if self.dragging_left_pane { 2.0 } else { 1.0 },
+ h - PAD * 2.0,
+ if self.dragging_left_pane {
+ palette.selected_bg
+ } else {
+ palette.separator
+ },
+ )?;
+ self.widgets.push(
+ rect(split_x - SPLIT_HANDLE_W / 2.0, oy, SPLIT_HANDLE_W, h),
+ WidgetKind::ResizeHandle,
+ SshViewAction::ResizeLeftPane,
+ );
+
+ if self.form.is_some() {
+ self.paint_form(
+ ctx,
+ layers,
+ font,
+ palette,
+ tokens,
+ cursor_on,
+ right_x,
+ oy + PAD,
+ right_w,
+ )?;
+ } else {
+ ctx.draw_text(
+ layers,
+ font,
+ right_x,
+ oy + h / 2.0 - 10.0,
+ "Select a host, or click + to add a new one.",
+ palette.muted_text,
+ right_w.max(0.0),
+ )?;
+ }
+
+ Ok(())
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn paint_header_controls(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ font: &Rc<LoadedFont>,
+ left_x: f32,
+ title_y: f32,
+ search_y: f32,
+ inner_left_w: f32,
+ palette: UiPalette,
+ tokens: UiTokens,
+ cursor_on: bool,
+ ) -> anyhow::Result<()> {
+ ctx.draw_text_on_layer(
+ layers,
+ 2,
+ font,
+ left_x,
+ title_y,
+ "SSH Hosts",
+ palette.text,
+ inner_left_w,
+ )?;
+
+ let search_rect = rect(left_x, search_y, inner_left_w - INPUT_H - 8.0, INPUT_H);
+ self.widgets
+ .push(search_rect, WidgetKind::TextInput, SshViewAction::Search);
+ let search_focused = matches!(self.focus, Focus::Search);
+ let search_border = if search_focused {
+ palette.selected_bg
+ } else if self.interaction.hovered == Some(SshViewAction::Search) {
+ palette.separator
+ } else {
+ palette.control_border
+ };
+ ctx.draw_rounded_frame(
+ layers,
+ 2,
+ search_rect.origin.x,
+ search_rect.origin.y,
+ search_rect.size.width,
+ search_rect.size.height,
+ palette.control_bg,
+ search_border,
+ tokens.control_radius,
+ )?;
+
+ let text_pad = 12.0;
+ let (search_text, search_color) = if self.search.is_empty() && !search_focused {
+ ("Search hosts...", palette.muted_text)
+ } else {
+ (self.search.as_str(), palette.text)
+ };
+ if search_focused && self.select_all && !self.search.is_empty() {
+ let selection_width = ctx
+ .measure_text_width(font, &self.search)
+ .min((search_rect.size.width - text_pad * 2.0).max(0.0));
+ ctx.draw_rounded_rect(
+ layers,
+ 2,
+ search_rect.origin.x + text_pad - 4.0,
+ search_rect.origin.y + 5.0,
+ selection_width + 8.0,
+ search_rect.size.height - 10.0,
+ palette.selected_bg.mul_alpha(0.56),
+ (tokens.control_radius - 5.0).max(3.0),
+ )?;
+ }
+ ctx.draw_text_on_layer(
+ layers,
+ 2,
+ font,
+ search_rect.origin.x + text_pad,
+ Self::control_text_y(ctx, search_rect.origin.y, search_rect.size.height),
+ search_text,
+ search_color,
+ (search_rect.size.width - text_pad * 2.0).max(0.0),
+ )?;
+ if search_focused && !self.select_all && cursor_on {
+ let caret_x = search_rect.origin.x
+ + text_pad
+ + ctx
+ .measure_text_width(font, &self.search)
+ .min((search_rect.size.width - text_pad * 2.0).max(0.0));
+ ctx.draw_rect(
+ layers,
+ 2,
+ caret_x - 1.0,
+ search_rect.origin.y + 5.0,
+ 3.0,
+ search_rect.size.height - 10.0,
+ palette.selected_bg,
+ )?;
+ }
+
+ let add_x = left_x + inner_left_w - INPUT_H;
+ let add_rect = rect(add_x, search_y, INPUT_H, INPUT_H);
+ self.widgets
+ .push(add_rect, WidgetKind::Button, SshViewAction::New);
+ let add_hovered = self.interaction.hovered == Some(SshViewAction::New);
+ let add_pressed = self.interaction.pressed == Some(SshViewAction::New);
+ let add_bg = if add_pressed {
+ palette.control_pressed_bg
+ } else if add_hovered {
+ palette.control_hover_bg
+ } else {
+ LinearRgba::TRANSPARENT
+ };
+ if add_bg.3 > 0.0 {
+ ctx.draw_rounded_rect(layers, 2, add_x, search_y, INPUT_H, INPUT_H, add_bg, 8.0)?;
+ }
+ let icon_size = (ctx.metrics.cell_size.height as f32 + 4.0).clamp(20.0, 30.0);
+ ctx.draw_svg_icon(
+ layers,
+ SvgIcon::Plus,
+ add_x + (INPUT_H - icon_size) / 2.0,
+ search_y + (INPUT_H - icon_size) / 2.0,
+ icon_size,
+ if add_hovered || add_pressed {
+ palette.text
+ } else {
+ palette.muted_text
+ },
+ )?;
+
+ Ok(())
+ }
+
+ fn control_text_y(ctx: &DrawContext, y: f32, height: f32) -> f32 {
+ let cell_height = ctx.metrics.cell_size.height as f32;
+ y + ((height - cell_height) / 2.0).max(0.0)
+ }
+
+ fn paint_list_fades(
+ &self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ ) -> anyhow::Result<()> {
+ if !self.scroll.has_overflow() || area.size.width <= 0.0 || area.size.height <= 0.0 {
+ return Ok(());
+ }
+
+ let fade_height = LIST_FADE_HEIGHT.min(area.size.height).ceil() as usize;
+ if fade_height == 0 {
+ return Ok(());
+ }
+
+ if self.scroll.offset > 0.5 {
+ for step in 0..fade_height {
+ let progress = step as f32 / fade_height as f32;
+ let alpha = 1.0 - Self::smoothstep(progress);
+ ctx.draw_rect(
+ layers,
+ 2,
+ area.origin.x,
+ area.origin.y + step as f32,
+ area.size.width,
+ 1.0,
+ palette.window_bg.mul_alpha(alpha),
+ )?;
+ }
+ }
+
+ if self.scroll.offset < self.scroll.max_offset() - 0.5 {
+ let start_y = area.origin.y + area.size.height - fade_height as f32;
+ for step in 0..fade_height {
+ let progress = (step + 1) as f32 / fade_height as f32;
+ let alpha = Self::smoothstep(progress);
+ ctx.draw_rect(
+ layers,
+ 2,
+ area.origin.x,
+ start_y + step as f32,
+ area.size.width,
+ 1.0,
+ palette.window_bg.mul_alpha(alpha),
+ )?;
+ }
+ }
+
+ Ok(())
+ }
+
+ fn smoothstep(t: f32) -> f32 {
+ let t = t.clamp(0.0, 1.0);
+ t * t * (3.0 - 2.0 * t)
+ }
+
+ fn paint_list_mask(
+ &self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ y: f32,
+ width: f32,
+ height: f32,
+ palette: UiPalette,
+ ) -> anyhow::Result<()> {
+ if width <= 0.0 || height <= 0.0 {
+ return Ok(());
+ }
+ for layer in 0..=2 {
+ ctx.draw_rect(layers, layer, x, y, width, height, palette.window_bg)?;
+ }
+ Ok(())
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn paint_system_group_header(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ font: &Rc<LoadedFont>,
+ palette: UiPalette,
+ x: f32,
+ y: f32,
+ width: f32,
+ list_top: f32,
+ list_bottom: f32,
+ ) -> anyhow::Result<()> {
+ let hit_y = y.max(list_top);
+ let hit_h = (y + GROUP_ROW_H).min(list_bottom) - hit_y;
+ let rect = rect(x, hit_y, width, hit_h.max(0.0));
+ self.widgets.push(
+ rect,
+ WidgetKind::SidebarRow,
+ SshViewAction::ToggleSystemHosts,
+ );
+ let hovered = self.interaction.hovered == Some(SshViewAction::ToggleSystemHosts);
+ if hovered {
+ ctx.draw_rounded_rect(
+ layers,
+ 0,
+ x,
+ y,
+ width,
+ GROUP_ROW_H,
+ palette.sidebar_row_hover_bg,
+ 10.0,
+ )?;
+ }
+ let icon = if self.system_hosts_collapsed && self.search.trim().is_empty() {
+ SvgIcon::ChevronRight
+ } else {
+ SvgIcon::ChevronDown
+ };
+ ctx.draw_svg_icon(layers, icon, x + 12.0, y + 12.0, 20.0, palette.muted_text)?;
+ let label = format!("System SSH ({})", self.system_host_count);
+ ctx.draw_text(
+ layers,
+ font,
+ x + 42.0,
+ y + 8.0,
+ &label,
+ palette.muted_text,
+ (width - 50.0).max(0.0),
+ )?;
+ Ok(())
+ }
+
+ fn host_row_height(ctx: &DrawContext) -> f32 {
+ (ctx.metrics.cell_size.height as f32 * 2.15 + 26.0).max(ROW_MIN_H)
+ }
+
+ fn rows_height(count: usize, row_h: f32) -> f32 {
+ if count == 0 {
+ 0.0
+ } else {
+ count as f32 * row_h + (count.saturating_sub(1)) as f32 * ROW_GAP
+ }
+ }
+
+ fn row_visible(y: f32, height: f32, list_top: f32, list_bottom: f32) -> bool {
+ y + height >= list_top && y <= list_bottom
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn paint_host_row(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ font: &Rc<LoadedFont>,
+ palette: UiPalette,
+ x: f32,
+ y: f32,
+ width: f32,
+ index: usize,
+ entry: &SshHostEntry,
+ list_top: f32,
+ list_bottom: f32,
+ ) -> anyhow::Result<()> {
+ let spec = &entry.spec;
+ let row_h = Self::host_row_height(ctx);
+ let hit_y = y.max(list_top);
+ let hit_h = (y + row_h).min(list_bottom) - hit_y;
+ let row_rect = rect(x, hit_y, width, hit_h.max(0.0));
+ self.widgets.push(
+ row_rect,
+ WidgetKind::SidebarRow,
+ SshViewAction::Connect(index),
+ );
+
+ let selected = index == self.selected;
+ let hovered = self.interaction.hovered == Some(SshViewAction::Connect(index));
+ let bg = if selected {
+ palette.sidebar_row_active_bg
+ } else if hovered {
+ palette.sidebar_row_hover_bg
+ } else {
+ LinearRgba::TRANSPARENT
+ };
+ if bg.3 > 0.0 {
+ ctx.draw_rounded_rect(layers, 0, x, y, width, row_h, bg, HOST_ROW_RADIUS)?;
+ }
+
+ // OS / brand icon.
+ let line_h = ctx.metrics.cell_size.height as f32;
+ let icon_size = (line_h * 1.05).clamp(34.0, 48.0);
+ let icon_x = x + 12.0;
+ let icon_y = y + (row_h - icon_size) / 2.0;
+ match spec.detected_distro.as_deref().and_then(distro_to_icon) {
+ Some(brand) => ctx.draw_brand_icon(layers, brand, icon_x, icon_y, icon_size)?,
+ None => ctx.draw_svg_icon(
+ layers,
+ SvgIcon::Server,
+ icon_x,
+ icon_y,
+ icon_size,
+ palette.text,
+ )?,
+ }
+
+ let text_x = icon_x + icon_size + 14.0;
+ let action_space = if entry.source == SshHostSource::ThinkTerm {
+ HOST_ACTION_RIGHT_PAD + HOST_ACTION_BTN * 2.0 + HOST_ACTION_GAP + 10.0
+ } else {
+ 16.0
+ };
+ let text_w = width - (text_x - x) - action_space;
+ let stack_h = line_h * 2.02;
+ let title_y = y + ((row_h - stack_h) / 2.0).max(8.0) - 2.0;
+ let subtitle_y = (title_y + line_h * 1.02).min(y + row_h - line_h - 8.0);
+ ctx.draw_text(
+ layers,
+ font,
+ text_x,
+ title_y,
+ &spec.label,
+ palette.text,
+ text_w.max(0.0),
+ )?;
+ let subtitle = {
+ let user = spec.username.as_deref().unwrap_or("");
+ let source = match entry.source {
+ SshHostSource::ThinkTerm => "ssh",
+ SshHostSource::System => "system ssh",
+ };
+ if user.is_empty() {
+ source.to_string()
+ } else {
+ format!("{source}, {user}")
+ }
+ };
+ ctx.draw_text(
+ layers,
+ font,
+ text_x,
+ subtitle_y,
+ &subtitle,
+ palette.muted_text,
+ text_w.max(0.0),
+ )?;
+
+ // Edit + delete icon buttons (right aligned). System SSH config hosts
+ // are read-only here: connect only, no write-back.
+ if entry.source == SshHostSource::System {
+ return Ok(());
+ }
+ let btn = HOST_ACTION_BTN;
+ let btn_y = y + (row_h - btn) / 2.0;
+ draw_icon_button(
+ ctx,
+ layers,
+ &mut self.widgets,
+ &self.interaction,
+ palette,
+ x + width - HOST_ACTION_RIGHT_PAD - btn * 2.0 - HOST_ACTION_GAP,
+ btn_y,
+ btn,
+ SvgIcon::SlidersHorizontal,
+ SshViewAction::Edit(index),
+ )?;
+ draw_icon_button(
+ ctx,
+ layers,
+ &mut self.widgets,
+ &self.interaction,
+ palette,
+ x + width - HOST_ACTION_RIGHT_PAD - btn,
+ btn_y,
+ btn,
+ SvgIcon::Trash2,
+ SshViewAction::Delete(index),
+ )?;
+ Ok(())
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn paint_form(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ font: &Rc<LoadedFont>,
+ palette: UiPalette,
+ tokens: UiTokens,
+ cursor_on: bool,
+ x: f32,
+ y: f32,
+ width: f32,
+ ) -> anyhow::Result<()> {
+ let form = self.form.as_ref().unwrap();
+ let editing = form.editing.is_some();
+ let detect_os = form.detect_os;
+ let fields = form.fields.clone();
+ let error = form.error.clone();
+ let focus = self.focus;
+
+ ctx.draw_text(
+ layers,
+ font,
+ x,
+ y,
+ if editing { "Edit Host" } else { "New Host" },
+ palette.text,
+ width,
+ )?;
+
+ let line_h = ctx.metrics.cell_size.height as f32;
+ let field_w = width.min(560.0);
+ let mut cur_y = y + line_h + 18.0;
+ for i in 0..FIELD_COUNT {
+ ctx.draw_text(
+ layers,
+ font,
+ x,
+ cur_y,
+ FIELD_LABELS[i],
+ palette.muted_text,
+ field_w,
+ )?;
+ let input_y = cur_y + line_h + 6.0;
+ // Mask the password field.
+ let masked = if i == FIELD_PASSWORD {
+ "•".repeat(fields[i].chars().count())
+ } else {
+ String::new()
+ };
+ let shown: &str = if i == FIELD_PASSWORD {
+ &masked
+ } else {
+ &fields[i]
+ };
+ draw_text_input(
+ ctx,
+ layers,
+ font,
+ &mut self.widgets,
+ &self.interaction,
+ palette,
+ tokens,
+ 12.0,
+ cursor_on,
+ TextInputSpec {
+ placeholder: "",
+ text: shown,
+ rect: rect(x, input_y, field_w, INPUT_H),
+ focused: focus == Focus::Field(i),
+ selected_all: focus == Focus::Field(i) && self.select_all,
+ action: SshViewAction::FocusField(i),
+ },
+ )?;
+ cur_y = input_y + INPUT_H + 18.0;
+ }
+
+ // Detect-OS toggle.
+ let toggle_w = 44.0;
+ let toggle_h = 24.0;
+ ctx.draw_text(
+ layers,
+ font,
+ x,
+ cur_y + (toggle_h - line_h) / 2.0,
+ "Detect OS on connect",
+ palette.text,
+ field_w - toggle_w - 12.0,
+ )?;
+ draw_toggle(
+ ctx,
+ layers,
+ &mut self.widgets,
+ palette,
+ rect(x + field_w - toggle_w, cur_y, toggle_w, toggle_h),
+ detect_os,
+ SshViewAction::ToggleDetect,
+ )?;
+ cur_y += toggle_h + 24.0;
+
+ if let Some(err) = &error {
+ ctx.draw_text(
+ layers,
+ font,
+ x,
+ cur_y,
+ &format!("⚠ {err}"),
+ palette.text,
+ field_w,
+ )?;
+ cur_y += line_h + 12.0;
+ }
+
+ // Buttons sized to their (measured) label so nothing is truncated.
+ let gap = 12.0;
+ let btn_w = |label: &str| ctx.measure_text_width(font, label) + 36.0;
+ let mut bx = x;
+ for (label, action, primary) in [
+ ("Save & Connect", SshViewAction::SaveAndConnect, true),
+ ("Save", SshViewAction::Save, false),
+ ("Cancel", SshViewAction::Cancel, false),
+ ] {
+ let w = btn_w(label);
+ let spec = ButtonSpec {
+ label,
+ action,
+ rect: rect(bx, cur_y, w, BTN_H),
+ state: self.button_state(action, primary),
+ kind: WidgetKind::Button,
+ };
+ draw_button(ctx, layers, font, &mut self.widgets, palette, spec)?;
+ bx += w + gap;
+ }
+ Ok(())
+ }
+
+ fn button_state(&self, action: SshViewAction, primary: bool) -> ControlState {
+ if self.interaction.pressed == Some(action) {
+ ControlState::Pressed
+ } else if self.interaction.hovered == Some(action) {
+ ControlState::Hovered
+ } else if primary {
+ ControlState::Active
+ } else {
+ ControlState::Normal
+ }
+ }
+}
+
+/// Close the view and connect to the given remote project on the main window.
+fn connect_response(project_id: String) -> ContentViewResponse {
+ ContentViewResponse::Run(Box::new(move |tw: &mut TermWindow| {
+ tw.close_content_view();
+ tw.connect_ssh_host(project_id, None);
+ }))
+}
+
+impl ContentView for SshHostsView {
+ fn title(&self) -> String {
+ "SSH Hosts".to_string()
+ }
+
+ fn wants_cursor_blink(&self) -> bool {
+ // A text field is always focused while this view is open.
+ true
+ }
+
+ fn paint(
+ &mut self,
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ area: RectF,
+ palette: UiPalette,
+ font: &Rc<LoadedFont>,
+ cursor_on: bool,
+ ) -> anyhow::Result<()> {
+ self.paint_impl(ctx, layers, area, palette, font, cursor_on)
+ }
+
+ fn on_mouse(&mut self, x: f32, y: f32, kind: WMEK) -> ContentViewResponse {
+ self.on_mouse_impl(x, y, kind)
+ }
+
+ fn on_key(&mut self, key: KeyCode, mods: KeyModifiers) -> ContentViewResponse {
+ self.on_key_impl(key, mods)
+ }
+
+ fn on_paste(&mut self, text: &str) -> ContentViewResponse {
+ self.on_paste_impl(text)
+ }
+
+ fn copy_text(&self) -> Option<String> {
+ let text = match self.focus {
+ Focus::Search => self.search.clone(),
+ Focus::Field(n) => self.form.as_ref()?.fields.get(n)?.clone(),
+ };
+ (!text.is_empty()).then_some(text)
+ }
+
+ fn cut_text(&mut self) -> Option<String> {
+ self.take_focused_selection()
+ }
+}
diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rs
index 253a59c1..7ce2579b 100644
--- a/wezterm-gui/src/termwindow/ui/icons.rs
+++ b/wezterm-gui/src/termwindow/ui/icons.rs
@@ -17,6 +17,7 @@ pub enum SvgIcon {
Globe,
Info,
Keyboard,
+ Link2,
Loader,
LoaderCircle,
Maximize2,
@@ -76,6 +77,7 @@ impl SvgIcon {
Self::Globe => include_bytes!("../../../../third_party/lucide/icons/globe.svg"),
Self::Info => include_bytes!("../../../../third_party/lucide/icons/info.svg"),
Self::Keyboard => include_bytes!("../../../../third_party/lucide/icons/keyboard.svg"),
+ Self::Link2 => include_bytes!("../../../../third_party/lucide/icons/link-2.svg"),
Self::Loader => include_bytes!("../../../../third_party/lucide/icons/loader.svg"),
Self::LoaderCircle => {
include_bytes!("../../../../third_party/lucide/icons/loader-circle.svg")
@@ -395,7 +397,11 @@ mod tests {
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);
+ assert!(
+ data.iter().any(|value| *value != 0),
+ "{:?} rendered empty",
+ icon
+ );
}
}
diff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rs
index 3a78fb82..df5d7460 100644
--- a/wezterm-gui/src/termwindow/ui/sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs
@@ -40,8 +40,8 @@ const SIDEBAR_SETTINGS_ROW_LIFT: usize = 18;
const SIDEBAR_TOP_FADE_HEIGHT: usize = 32;
const WORKSPACE_GROUP_EXTRA_GAP: usize = 8;
const WORKSPACE_SECTION_LABEL_GAP: usize = 12;
-const SESSION_ROW_MIN_HEIGHT: usize = 62;
-const SESSION_ROW_SIDE_PADDING: usize = 8;
+const SESSION_ROW_MIN_HEIGHT: usize = 66;
+const SESSION_ROW_SIDE_PADDING: usize = 10;
const SESSION_ACTION_MIN_SIZE: usize = 48;
const SESSION_ACTION_MAX_SIZE: usize = 52;
const SESSION_ACTION_ICON_INSET: usize = 12;
@@ -1627,7 +1627,17 @@ impl crate::TermWindow {
.saturating_add(settings_row_width)
.saturating_sub(settings_action_size);
let settings_action_y = settings_row_y;
- let settings_body_width = settings_action_x
+ // SSH hosts (link-2) button sits just left of the view-options button.
+ let ssh_action_x =
+ settings_action_x.saturating_sub(settings_action_size + SIDEBAR_INSET / 2);
+ let ssh_action_y = settings_row_y;
+ let ssh_action_hovered = self.is_pointer_over_ui_rect(
+ ssh_action_x,
+ ssh_action_y,
+ settings_action_size,
+ settings_action_size,
+ );
+ let settings_body_width = ssh_action_x
.saturating_sub(settings_row_x)
.saturating_sub(SIDEBAR_INSET / 2);
let settings_hovered = self.is_pointer_over_ui_rect(
@@ -1686,6 +1696,43 @@ impl crate::TermWindow {
height: settings_action_size,
item_type: UIItemType::WorkspaceSidebarViewOptions,
});
+ if ssh_action_hovered {
+ self.fill_rounded_rectangle(
+ layers,
+ 2,
+ euclid::rect(
+ ssh_action_x as f32,
+ ssh_action_y as f32,
+ settings_action_size as f32,
+ settings_action_size as f32,
+ ),
+ chrome.sidebar_button_hover_bg,
+ SIDEBAR_ROW_RADIUS + 4.0,
+ )
+ .context("sidebar ssh hosts hover")?;
+ }
+ self.ui_items.push(UIItem {
+ x: ssh_action_x,
+ y: ssh_action_y,
+ width: settings_action_size,
+ height: settings_action_size,
+ item_type: UIItemType::WorkspaceSidebarSshHosts,
+ });
+ {
+ let ssh_icon_size = icon_size.min(settings_row_height.saturating_sub(8));
+ self.paint_sidebar_icon(
+ layers,
+ SvgIcon::Link2,
+ ssh_action_x + ((settings_action_size.saturating_sub(ssh_icon_size)) / 2),
+ ssh_action_y + ((settings_action_size.saturating_sub(ssh_icon_size)) / 2),
+ ssh_icon_size,
+ if ssh_action_hovered {
+ foreground
+ } else {
+ muted_fg
+ },
+ )?;
+ }
let settings_icon_size = icon_size.min(settings_row_height.saturating_sub(8));
let settings_icon_x = settings_row_x + SIDEBAR_SETTINGS_ICON_EXTRA_INSET;
let settings_icon_y =
@@ -1828,7 +1875,9 @@ impl crate::TermWindow {
radius: f32,
) -> anyhow::Result<()> {
let radius = radius.min(rect.width() / 2.0).min(rect.height() / 2.0);
- if radius <= 0.0 {
+ // Sub-pixel radii round down to a 0px corner sprite (which panics when
+ // building its pixmap), so fall back to a plain rectangle below ~1px.
+ if !(radius >= 1.0) {
self.filled_rectangle(layers, layer_num, rect, color)?;
return Ok(());
}
diff --git a/wezterm-gui/src/termwindow/ui/tokens.rs b/wezterm-gui/src/termwindow/ui/tokens.rs
index eb252025..5d0a12d6 100644
--- a/wezterm-gui/src/termwindow/ui/tokens.rs
+++ b/wezterm-gui/src/termwindow/ui/tokens.rs
@@ -24,6 +24,7 @@ pub const WINDOW_TAB_LEADING_ACTION_GAP: usize = 8;
pub const WINDOW_TAB_LEADING_ACTION_ICON_SIZE: usize = 26;
pub const WINDOW_TAB_GAP: usize = 18;
pub const WINDOW_TAB_RADIUS: f32 = 12.0;
+pub const WINDOW_TAB_ADD_BUTTON_RADIUS: f32 = 999.0;
pub const TAB_CLOSE_HOVER_INSET: usize = 5;
pub const TAB_CLOSE_HOVER_RADIUS: f32 = 999.0;
pub const TAB_CLOSE_RIGHT_GAP: usize = 6;
@@ -38,5 +39,7 @@ pub const PANE_NAV_EXTRA_HEIGHT: usize = 32;
pub const PANE_NAV_MIN_HEIGHT: usize = 62;
pub const PANE_NAV_MAX_HEIGHT: usize = 72;
pub const PANE_NAV_TAB_RADIUS: f32 = 12.0;
+pub const PANE_NAV_ACTION_BUTTON_RADIUS: f32 = 999.0;
pub const CAPSULE_BORDER_WIDTH: f32 = 1.0;
+pub const ICON_BUTTON_BORDER_WIDTH: f32 = 1.0;
diff --git a/wezterm-gui/src/ui/draw.rs b/wezterm-gui/src/ui/draw.rs
new file mode 100644
index 00000000..e1949cae
--- /dev/null
+++ b/wezterm-gui/src/ui/draw.rs
@@ -0,0 +1,451 @@
+//! Low-level GPU drawing primitives shared by native ThinkTerm UI surfaces
+//! (the settings window and the in-window SSH hosts view).
+//!
+//! A [`DrawContext`] bundles the three things every primitive needs — the
+//! window's [`RenderState`], its [`Dimensions`], and [`RenderMetrics`] — so the
+//! same drawing code works regardless of which window/surface owns them. The
+//! method bodies are lifted verbatim from `settings_window.rs` (which keeps its
+//! own copies for now); the only change is `self.render_state.as_ref().unwrap()`
+//! becomes the borrowed `self.render_state` field.
+
+use crate::customglyph::{BlockKey, Poly};
+use crate::quad::{QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};
+use crate::renderstate::RenderState;
+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::{BrandIcon, SvgIcon};
+use crate::utilsprites::RenderMetrics;
+use std::rc::Rc;
+use wezterm_bidi::Direction;
+use wezterm_font::LoadedFont;
+use window::color::LinearRgba;
+use window::Dimensions;
+
+/// Borrowed handles needed by every primitive. Cheap to build each frame.
+pub(crate) struct DrawContext<'a> {
+ pub render_state: &'a RenderState,
+ pub dimensions: Dimensions,
+ pub metrics: &'a RenderMetrics,
+}
+
+impl<'a> DrawContext<'a> {
+ pub(crate) fn new(
+ render_state: &'a RenderState,
+ dimensions: Dimensions,
+ metrics: &'a RenderMetrics,
+ ) -> Self {
+ Self {
+ render_state,
+ dimensions,
+ metrics,
+ }
+ }
+
+ pub(crate) fn draw_rect(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ layer_num: usize,
+ x: f32,
+ y: f32,
+ width: f32,
+ height: f32,
+ color: LinearRgba,
+ ) -> anyhow::Result<()> {
+ if width <= 0.0 || height <= 0.0 {
+ return Ok(());
+ }
+
+ let render_state = self.render_state;
+ let mut quad = layers.allocate(layer_num)?;
+ let left_offset = self.dimensions.pixel_width as f32 / 2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / 2.0;
+ quad.set_position(
+ x - left_offset,
+ y - top_offset,
+ x + width - left_offset,
+ y + height - top_offset,
+ );
+ quad.set_texture(render_state.util_sprites.filled_box.texture_coords());
+ quad.set_is_background();
+ quad.set_fg_color(color);
+ quad.set_hsv(None);
+ Ok(())
+ }
+
+ pub(crate) fn draw_rounded_rect(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ layer_num: usize,
+ x: f32,
+ y: f32,
+ width: f32,
+ height: f32,
+ color: LinearRgba,
+ radius: f32,
+ ) -> anyhow::Result<()> {
+ if width <= 0.0 || height <= 0.0 {
+ return Ok(());
+ }
+
+ let radius = radius.min(width / 2.0).min(height / 2.0).round().max(0.0);
+ if radius <= 0.0 {
+ return self.draw_rect(layers, layer_num, x, y, width, height, color);
+ }
+
+ let corner_size = euclid::size2(radius, radius);
+ self.draw_corner(
+ layers,
+ layer_num,
+ x,
+ y,
+ TOP_LEFT_ROUNDED_CORNER,
+ corner_size,
+ color,
+ )?;
+ self.draw_corner(
+ layers,
+ layer_num,
+ x + width - radius,
+ y,
+ TOP_RIGHT_ROUNDED_CORNER,
+ corner_size,
+ color,
+ )?;
+ self.draw_corner(
+ layers,
+ layer_num,
+ x,
+ y + height - radius,
+ BOTTOM_LEFT_ROUNDED_CORNER,
+ corner_size,
+ color,
+ )?;
+ self.draw_corner(
+ layers,
+ layer_num,
+ x + width - radius,
+ y + height - radius,
+ BOTTOM_RIGHT_ROUNDED_CORNER,
+ corner_size,
+ color,
+ )?;
+
+ self.draw_rect(
+ layers,
+ layer_num,
+ x + radius,
+ y,
+ width - radius * 2.0,
+ height,
+ color,
+ )?;
+ self.draw_rect(
+ layers,
+ layer_num,
+ x,
+ y + radius,
+ radius,
+ height - radius * 2.0,
+ color,
+ )?;
+ self.draw_rect(
+ layers,
+ layer_num,
+ x + width - radius,
+ y + radius,
+ radius,
+ height - radius * 2.0,
+ color,
+ )?;
+
+ Ok(())
+ }
+
+ pub(crate) fn draw_rounded_frame(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ layer_num: usize,
+ x: f32,
+ y: f32,
+ width: f32,
+ height: f32,
+ fill: LinearRgba,
+ border: LinearRgba,
+ radius: f32,
+ ) -> anyhow::Result<()> {
+ self.draw_rounded_rect(layers, layer_num, x, y, width, height, border, radius)?;
+ self.draw_rounded_rect(
+ layers,
+ layer_num,
+ x + 1.0,
+ y + 1.0,
+ width - 2.0,
+ height - 2.0,
+ fill,
+ (radius - 1.0).max(0.0),
+ )?;
+ Ok(())
+ }
+
+ pub(crate) fn draw_corner(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ layer_num: usize,
+ x: f32,
+ y: f32,
+ polys: &'static [Poly],
+ size: euclid::Size2D<f32, window::PixelUnit>,
+ color: LinearRgba,
+ ) -> anyhow::Result<()> {
+ let render_state = self.render_state;
+ let sprite = render_state
+ .glyph_cache
+ .borrow_mut()
+ .cached_block(
+ BlockKey::PolyWithCustomMetrics {
+ polys,
+ underline_height: self.metrics.underline_height,
+ cell_size: euclid::size2(size.width as isize, size.height as isize),
+ },
+ self.metrics,
+ )?
+ .texture_coords();
+
+ let mut quad = layers.allocate(layer_num)?;
+ let left_offset = self.dimensions.pixel_width as f32 / 2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / 2.0;
+ quad.set_position(
+ x - left_offset,
+ y - top_offset,
+ x + size.width - left_offset,
+ y + size.height - top_offset,
+ );
+ quad.set_texture(sprite);
+ quad.set_fg_color(color);
+ quad.set_alt_color_and_mix_value(color, 0.0);
+ quad.set_hsv(None);
+ quad.set_has_color(false);
+ quad.set_grayscale();
+ Ok(())
+ }
+
+ pub(crate) fn draw_svg_icon(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ icon: SvgIcon,
+ x: f32,
+ y: f32,
+ size: f32,
+ color: LinearRgba,
+ ) -> anyhow::Result<()> {
+ if size <= 0.0 {
+ return Ok(());
+ }
+
+ let render_state = self.render_state;
+ let sprite = render_state
+ .glyph_cache
+ .borrow_mut()
+ .cached_svg_icon(icon, size.round() as usize)?
+ .texture_coords();
+ let mut quad = layers.allocate(2)?;
+ let left_offset = self.dimensions.pixel_width as f32 / 2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / 2.0;
+ quad.set_position(
+ x - left_offset,
+ y - top_offset,
+ x + size - left_offset,
+ y + size - top_offset,
+ );
+ quad.set_texture(sprite);
+ quad.set_fg_color(color);
+ quad.set_alt_color_and_mix_value(color, 0.0);
+ quad.set_hsv(None);
+ quad.set_has_color(false);
+ quad.set_grayscale();
+ Ok(())
+ }
+
+ /// Brand/OS logos bake their color into the sprite, so they render
+ /// full-color rather than being tinted (unlike [`Self::draw_svg_icon`]).
+ pub(crate) fn draw_brand_icon(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ icon: BrandIcon,
+ x: f32,
+ y: f32,
+ size: f32,
+ ) -> anyhow::Result<()> {
+ if size <= 0.0 {
+ return Ok(());
+ }
+
+ let render_state = self.render_state;
+ let sprite = render_state
+ .glyph_cache
+ .borrow_mut()
+ .cached_brand_icon(icon, size.round() as usize)?
+ .texture_coords();
+ let mut quad = layers.allocate(2)?;
+ let left_offset = self.dimensions.pixel_width as f32 / 2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / 2.0;
+ quad.set_position(
+ x - left_offset,
+ y - top_offset,
+ x + size - left_offset,
+ y + size - 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(())
+ }
+
+ pub(crate) fn draw_text(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ font: &Rc<LoadedFont>,
+ x: f32,
+ y: f32,
+ text: &str,
+ color: LinearRgba,
+ max_width: f32,
+ ) -> anyhow::Result<()> {
+ self.draw_text_on_layer(layers, 1, font, x, y, text, color, max_width)
+ }
+
+ pub(crate) fn draw_text_on_layer(
+ &self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ layer_num: usize,
+ font: &Rc<LoadedFont>,
+ x: f32,
+ y: f32,
+ text: &str,
+ color: LinearRgba,
+ max_width: f32,
+ ) -> anyhow::Result<()> {
+ if text.is_empty() || max_width <= 0.0 {
+ return Ok(());
+ }
+
+ let display_text = self.text_with_ellipsis(font, text, max_width);
+ if display_text.is_empty() {
+ return Ok(());
+ }
+
+ let infos = font.blocking_shape(&display_text, None, Direction::LeftToRight, None, None)?;
+ let render_state = self.render_state;
+ let mut glyph_cache = render_state.glyph_cache.borrow_mut();
+ let style = font.style();
+ let mut pos_x = x;
+ let baseline = self.metrics.cell_size.height as f32 + self.metrics.descender.get() as f32;
+ let left_offset = self.dimensions.pixel_width as f32 / 2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / 2.0;
+ let right_edge = x + max_width;
+
+ for info in infos {
+ let glyph = glyph_cache.cached_glyph(&info, style, false, font, self.metrics, 1)?;
+ if let Some(texture) = glyph.texture.as_ref() {
+ let glyph_x = (pos_x + (glyph.x_offset + glyph.bearing_x).get() as f32).round();
+ let glyph_y =
+ (y - (glyph.y_offset + glyph.bearing_y).get() as f32 + baseline).round();
+ let width = texture.coords.size.width as f32 * glyph.scale as f32;
+ let height = texture.coords.size.height as f32 * glyph.scale as f32;
+
+ if glyph_x + width > right_edge {
+ break;
+ }
+
+ let mut quad = layers.allocate(layer_num)?;
+ quad.set_position(
+ glyph_x - left_offset,
+ glyph_y - top_offset,
+ glyph_x + width - left_offset,
+ glyph_y + height - top_offset,
+ );
+ quad.set_texture(texture.texture_coords());
+ quad.set_has_color(glyph.has_color);
+ quad.set_fg_color(color);
+ quad.set_hsv(None);
+ }
+ pos_x += glyph.x_advance.get() as f32;
+ if pos_x > right_edge {
+ break;
+ }
+ }
+
+ Ok(())
+ }
+
+ pub(crate) fn measure_text_width(&self, font: &Rc<LoadedFont>, text: &str) -> f32 {
+ if text.is_empty() {
+ return 0.0;
+ }
+ let Ok(infos) = font.blocking_shape(text, None, Direction::LeftToRight, None, None) else {
+ return 0.0;
+ };
+ let render_state = self.render_state;
+ let mut glyph_cache = render_state.glyph_cache.borrow_mut();
+ let style = font.style();
+ infos
+ .into_iter()
+ .filter_map(|info| {
+ glyph_cache
+ .cached_glyph(&info, style, false, font, self.metrics, 1)
+ .ok()
+ .map(|glyph| glyph.x_advance.get() as f32)
+ })
+ .sum()
+ }
+
+ pub(crate) fn text_with_ellipsis(
+ &self,
+ font: &Rc<LoadedFont>,
+ text: &str,
+ max_width: f32,
+ ) -> String {
+ if max_width <= 0.0 || text.is_empty() {
+ return String::new();
+ }
+
+ if self.measure_text_width(font, text) <= max_width {
+ return text.to_string();
+ }
+
+ let ellipsis = "...";
+ let ellipsis_width = self.measure_text_width(font, ellipsis);
+ if ellipsis_width > max_width {
+ return String::new();
+ }
+
+ let mut boundaries = text
+ .char_indices()
+ .map(|(idx, _)| idx)
+ .chain(std::iter::once(text.len()))
+ .collect::<Vec<_>>();
+ boundaries.dedup();
+
+ let mut low = 0;
+ let mut high = boundaries.len().saturating_sub(1);
+ let mut best = 0;
+ while low <= high {
+ let mid = (low + high) / 2;
+ let candidate = &text[..boundaries[mid]];
+ let width = self.measure_text_width(font, candidate) + ellipsis_width;
+ if width <= max_width {
+ best = mid;
+ low = mid + 1;
+ } else if mid == 0 {
+ break;
+ } else {
+ high = mid - 1;
+ }
+ }
+
+ format!("{}{}", text[..boundaries[best]].trim_end(), ellipsis)
+ }
+}
diff --git a/wezterm-gui/src/ui/mod.rs b/wezterm-gui/src/ui/mod.rs
index 3f340168..aa952130 100644
--- a/wezterm-gui/src/ui/mod.rs
+++ b/wezterm-gui/src/ui/mod.rs
@@ -1,15 +1,19 @@
#![allow(dead_code)]
+pub(crate) mod draw;
pub(crate) mod events;
pub(crate) mod geometry;
pub(crate) mod icons;
pub(crate) mod primitives;
pub(crate) mod state;
pub(crate) mod tokens;
+pub(crate) mod widgets;
+pub(crate) use draw::*;
pub(crate) use events::*;
pub(crate) use geometry::*;
pub(crate) use icons::*;
pub(crate) use primitives::*;
pub(crate) use state::*;
pub(crate) use tokens::*;
+pub(crate) use widgets::*;
diff --git a/wezterm-gui/src/ui/state.rs b/wezterm-gui/src/ui/state.rs
index 8b11718d..7b1a069c 100644
--- a/wezterm-gui/src/ui/state.rs
+++ b/wezterm-gui/src/ui/state.rs
@@ -103,6 +103,15 @@ impl TextInputState {
self.selected_all = false;
}
+ pub(crate) fn take_selected_text(&mut self) -> Option<String> {
+ if self.selected_all && !self.text.is_empty() {
+ self.selected_all = false;
+ Some(std::mem::take(&mut self.text))
+ } else {
+ None
+ }
+ }
+
pub(crate) fn is_empty(&self) -> bool {
self.text.is_empty()
}
diff --git a/wezterm-gui/src/ui/widgets.rs b/wezterm-gui/src/ui/widgets.rs
new file mode 100644
index 00000000..c35b57b0
--- /dev/null
+++ b/wezterm-gui/src/ui/widgets.rs
@@ -0,0 +1,259 @@
+//! Reusable, action-generic UI controls drawn on top of [`DrawContext`].
+//!
+//! These mirror the control-drawing helpers in `settings_window.rs` but are
+//! parameterised over the caller's action type `A` and take the interaction /
+//! palette / hit-test context explicitly, so any native surface can use them.
+
+use crate::quad::TripleLayerQuadAllocator;
+use crate::termwindow::ui::icons::SvgIcon;
+use crate::ui::{
+ ButtonSpec, DrawContext, InteractionState, ScrollState, ScrollbarSpec, TextInputSpec,
+ UiContext, UiPalette, UiTokens, WidgetKind,
+};
+use std::rc::Rc;
+use wezterm_font::LoadedFont;
+use window::color::LinearRgba;
+use window::RectF;
+
+/// Vertically center single-line text of the UI font within `height`.
+fn control_text_y(ctx: &DrawContext, y: f32, height: f32) -> f32 {
+ let cell_height = ctx.metrics.cell_size.height as f32;
+ y + ((height - cell_height) / 2.0).max(0.0)
+}
+
+/// A filled, rounded button with a centered-left label. The caller fills
+/// `spec.state` (e.g. from its [`InteractionState`]).
+pub(crate) fn draw_button<A: Copy + PartialEq>(
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ font: &Rc<LoadedFont>,
+ widgets: &mut UiContext<A>,
+ palette: UiPalette,
+ spec: ButtonSpec<A>,
+) -> anyhow::Result<()> {
+ widgets.push(spec.rect, spec.kind, spec.action);
+ let (background, border) = spec.state.colors(palette);
+ ctx.draw_rounded_frame(
+ layers,
+ 0,
+ spec.rect.origin.x,
+ spec.rect.origin.y,
+ spec.rect.size.width,
+ spec.rect.size.height,
+ background,
+ border,
+ 8.0,
+ )?;
+ ctx.draw_text(
+ layers,
+ font,
+ spec.rect.origin.x + 14.0,
+ control_text_y(ctx, spec.rect.origin.y, spec.rect.size.height),
+ spec.label,
+ palette.text,
+ spec.rect.size.width - 28.0,
+ )?;
+ Ok(())
+}
+
+/// A transparent square button containing a tinted SVG icon; background fades
+/// in on hover/press.
+pub(crate) fn draw_icon_button<A: Copy + PartialEq>(
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ widgets: &mut UiContext<A>,
+ interaction: &InteractionState<A>,
+ palette: UiPalette,
+ x: f32,
+ y: f32,
+ size: f32,
+ icon: SvgIcon,
+ action: A,
+) -> anyhow::Result<()> {
+ let rect = RectF::new(euclid::point2(x, y), euclid::size2(size, size));
+ widgets.push(rect, WidgetKind::Button, action);
+ let hovered = interaction.hovered == Some(action);
+ let pressed = interaction.pressed == Some(action);
+ let bg = if pressed {
+ palette.control_pressed_bg
+ } else if hovered {
+ palette.control_hover_bg
+ } else {
+ LinearRgba::TRANSPARENT
+ };
+ if bg.3 > 0.0 {
+ ctx.draw_rounded_rect(layers, 0, x, y, size, size, bg, 8.0)?;
+ }
+ let icon_size = (ctx.metrics.cell_size.height as f32 + 4.0).clamp(20.0, 30.0);
+ ctx.draw_svg_icon(
+ layers,
+ icon,
+ x + (size - icon_size) / 2.0,
+ y + (size - icon_size) / 2.0,
+ icon_size,
+ if hovered || pressed {
+ palette.text
+ } else {
+ palette.muted_text
+ },
+ )
+}
+
+/// A single-line text field with placeholder, focus ring and caret. `text_pad`
+/// is the horizontal inset for the text (left/right).
+pub(crate) fn draw_text_input<A: Copy + PartialEq>(
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ font: &Rc<LoadedFont>,
+ widgets: &mut UiContext<A>,
+ interaction: &InteractionState<A>,
+ palette: UiPalette,
+ tokens: UiTokens,
+ text_pad: f32,
+ cursor_on: bool,
+ spec: TextInputSpec<'_, A>,
+) -> anyhow::Result<()> {
+ widgets.push(spec.rect, WidgetKind::TextInput, spec.action);
+ let border = if spec.focused {
+ palette.selected_bg
+ } else if interaction.hovered == Some(spec.action) {
+ palette.separator
+ } else {
+ palette.control_border
+ };
+ ctx.draw_rounded_frame(
+ layers,
+ 0,
+ spec.rect.origin.x,
+ spec.rect.origin.y,
+ spec.rect.size.width,
+ spec.rect.size.height,
+ palette.control_bg,
+ border,
+ tokens.control_radius,
+ )?;
+
+ let text = if spec.text.is_empty() && !spec.focused {
+ spec.placeholder
+ } else {
+ spec.text
+ };
+ let color = if spec.text.is_empty() && !spec.focused {
+ palette.muted_text
+ } else {
+ palette.text
+ };
+ if spec.focused && spec.selected_all && !spec.text.is_empty() {
+ let selection_width = ctx
+ .measure_text_width(font, spec.text)
+ .min((spec.rect.size.width - text_pad * 2.0).max(0.0));
+ ctx.draw_rounded_rect(
+ layers,
+ 1,
+ spec.rect.origin.x + text_pad - 4.0,
+ spec.rect.origin.y + 5.0,
+ selection_width + 8.0,
+ spec.rect.size.height - 10.0,
+ palette.selected_bg.mul_alpha(0.56),
+ (tokens.control_radius - 5.0).max(3.0),
+ )?;
+ }
+ ctx.draw_text(
+ layers,
+ font,
+ spec.rect.origin.x + text_pad,
+ control_text_y(ctx, spec.rect.origin.y, spec.rect.size.height),
+ text,
+ color,
+ (spec.rect.size.width - text_pad * 2.0).max(0.0),
+ )?;
+ if spec.focused && !spec.selected_all && cursor_on {
+ let caret_x = spec.rect.origin.x
+ + text_pad
+ + ctx
+ .measure_text_width(font, spec.text)
+ .min((spec.rect.size.width - text_pad * 2.0).max(0.0));
+ ctx.draw_rect(
+ layers,
+ 1,
+ caret_x - 1.0,
+ spec.rect.origin.y + 5.0,
+ 3.0,
+ spec.rect.size.height - 10.0,
+ palette.selected_bg,
+ )?;
+ }
+ Ok(())
+}
+
+/// A pill toggle (iOS-style). `on` selects accent vs muted track + knob side.
+pub(crate) fn draw_toggle<A: Copy + PartialEq>(
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ widgets: &mut UiContext<A>,
+ palette: UiPalette,
+ rect: RectF,
+ on: bool,
+ action: A,
+) -> anyhow::Result<()> {
+ widgets.push(rect, WidgetKind::Button, action);
+ let h = rect.size.height;
+ let track = if on {
+ palette.selected_bg
+ } else {
+ palette.control_border
+ };
+ ctx.draw_rounded_rect(
+ layers,
+ 0,
+ rect.origin.x,
+ rect.origin.y,
+ rect.size.width,
+ h,
+ track,
+ h / 2.0,
+ )?;
+ let knob = (h - 4.0).max(2.0);
+ let knob_x = if on {
+ rect.origin.x + rect.size.width - knob - 2.0
+ } else {
+ rect.origin.x + 2.0
+ };
+ ctx.draw_rounded_rect(
+ layers,
+ 1,
+ knob_x,
+ rect.origin.y + 2.0,
+ knob,
+ knob,
+ LinearRgba::with_components(1.0, 1.0, 1.0, 1.0),
+ knob / 2.0,
+ )?;
+ Ok(())
+}
+
+/// A vertical scrollbar thumb within `area` (no track), matching the settings
+/// window's look.
+pub(crate) fn draw_scrollbar(
+ ctx: &DrawContext,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ palette: UiPalette,
+ tokens: UiTokens,
+ area: RectF,
+ scroll: ScrollState,
+) -> anyhow::Result<()> {
+ let spec = ScrollbarSpec::from_area(area, tokens);
+ if let Some((thumb_y, thumb_h)) = scroll.thumb(spec.y, spec.height) {
+ ctx.draw_rounded_rect(
+ layers,
+ 0,
+ spec.x,
+ thumb_y,
+ spec.width,
+ thumb_h,
+ palette.scrollbar_thumb,
+ spec.width / 2.0,
+ )?;
+ }
+ Ok(())
+}
diff --git a/wezterm-toast-notification/src/macos.rs b/wezterm-toast-notification/src/macos.rs
index 1dfba50a..3ee6442f 100644
--- a/wezterm-toast-notification/src/macos.rs
+++ b/wezterm-toast-notification/src/macos.rs
@@ -94,11 +94,11 @@ impl Drop for NotifDelegate {
}
const CENTER: LazyLock<Retained<UNUserNotificationCenter>> =
- LazyLock::new(|| unsafe { UNUserNotificationCenter::currentNotificationCenter() });
+ LazyLock::new(UNUserNotificationCenter::currentNotificationCenter);
pub fn initialize() {
static INIT: Once = Once::new();
- INIT.call_once(|| unsafe {
+ INIT.call_once(|| {
CENTER.requestAuthorizationWithOptions_completionHandler(
UNAuthorizationOptions::Alert
| UNAuthorizationOptions::Provisional
diff --git a/window/Cargo.toml b/window/Cargo.toml
index 8de6bbf3..523daef2 100644
--- a/window/Cargo.toml
+++ b/window/Cargo.toml
@@ -15,6 +15,7 @@ k9.workspace = true
gl_generator.workspace = true
[features]
+cargo-clippy = []
wayland = ["wayland-client", "smithay-client-toolkit", "wayland-egl", "wayland-protocols", "wayland-backend", "wayland-protocols-plasma"]
[dependencies]
diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rs
index e77f6654..519d2aba 100644
--- a/window/src/os/macos/window.rs
+++ b/window/src/os/macos/window.rs
@@ -1025,6 +1025,13 @@ impl WindowOps for Window {
});
}
+ fn request_drag_move(&self) {
+ Connection::with_window_inner(self.id, move |inner| {
+ inner.request_drag_move();
+ Ok(())
+ });
+ }
+
fn set_text_cursor_position(&self, cursor: Rect) {
Connection::with_window_inner(self.id, move |inner| {
inner.set_text_cursor_position(cursor);
@@ -1559,6 +1566,16 @@ impl WindowInner {
set_window_position(*self.window, coords);
}
+ fn request_drag_move(&self) {
+ unsafe {
+ let app = NSApplication::sharedApplication(nil);
+ let event: id = msg_send![app, currentEvent];
+ if event != nil {
+ let () = msg_send![*self.window, performWindowDragWithEvent: event];
+ }
+ }
+ }
+
fn set_text_cursor_position(&mut self, cursor: Rect) {
if let Some(window_view) = WindowView::get_this(unsafe { &**self.view }) {
window_view.inner.borrow_mut().text_cursor_position = cursor;