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 SFTP-backed remote file browsing

RoversXc1ca03f546c6
diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rs
index 2cc1b928..3f6f0b92 100644
--- a/wezterm-client/src/domain.rs
+++ b/wezterm-client/src/domain.rs
@@ -549,6 +549,19 @@ impl ClientDomain {
self.config.connect_automatically()
}
+ /// Return the SSH transport configuration for callers that need to open a
+ /// separate, non-mux SSH channel (for example, ThinkTerm's opt-in SFTP
+ /// file browser). Unix and TLS client domains intentionally return None.
+ ///
+ /// The clone keeps `ClientDomain`'s live transport private: consumers
+ /// cannot accidentally share the mux Session and stall terminal traffic.
+ pub fn ssh_domain_config(&self) -> Option<SshDomain> {
+ match &self.config {
+ ClientDomainConfig::Ssh(ssh) => Some(ssh.clone()),
+ ClientDomainConfig::Unix(_) | ClientDomainConfig::Tls(_) => None,
+ }
+ }
+
/// The transport died and the background reconnect loop is trying to
/// get back; authoritative connection-health signal for indicators
/// (pane tardiness only trips after something is sent on the pane).
@@ -682,6 +695,11 @@ impl ClientDomain {
mut primary_window_id: Option<WindowId>,
) -> anyhow::Result<()> {
let mux = Mux::get();
+ // A native/mux window can disappear while an attach or structural RPC
+ // is in flight. Never trust mappings retained by the prior resync:
+ // remove entries whose local objects no longer exist before using
+ // them below.
+ inner.expire_stale_mappings();
log::debug!(
"domain {}: ListPanes result {:#?}",
inner.local_domain_id,
@@ -824,21 +842,29 @@ impl ClientDomain {
inner.local_domain_id,
local_window_id
);
- let needs_add = mux
- .get_window(local_window_id)
- .expect("no such window!?")
- .idx_by_id(tab.tab_id())
- .is_none();
- if needs_add {
- // Use add_tab_to_window rather than window.push so
- // that MuxNotification::TabAddedToWindow reaches the
- // GUI: it relies on that event to impose the local
- // window geometry on tabs that arrive via resync
- // (their wire size is the server's, which sits below
- // the local size by the pane nav bar reservation).
- mux.add_tab_to_window(&tab, local_window_id)?;
+ if let Some(window) = mux.get_window(local_window_id) {
+ let needs_add = window.idx_by_id(tab.tab_id()).is_none();
+ drop(window);
+ if needs_add {
+ // Use add_tab_to_window rather than window.push so
+ // that MuxNotification::TabAddedToWindow reaches
+ // the GUI: it relies on that event to impose the
+ // local window geometry on tabs that arrive via
+ // resync (their wire size is the server's, which
+ // sits below the local size by the pane nav bar
+ // reservation).
+ mux.add_tab_to_window(&tab, local_window_id)?;
+ }
+ continue;
}
- continue;
+ // The mapping went stale after the initial sweep. Fall
+ // through and adopt/create a live local window instead of
+ // panicking on an asynchronous resync.
+ inner
+ .remote_to_local_window
+ .lock()
+ .unwrap()
+ .remove(&remote_window_id);
}
if let Some(local_window_id) = primary_window_id {
@@ -890,10 +916,15 @@ impl ClientDomain {
for (remote_window_id, window_title) in panes.window_titles {
if let Some(local_window_id) = inner.remote_to_local_window(remote_window_id) {
- let mut window = mux
- .get_window_mut(local_window_id)
- .expect("no such window!?");
- window.set_title(&window_title);
+ if let Some(mut window) = mux.get_window_mut(local_window_id) {
+ window.set_title(&window_title);
+ } else {
+ inner
+ .remote_to_local_window
+ .lock()
+ .unwrap()
+ .remove(&remote_window_id);
+ }
}
}
diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rs
index a6918db4..e4c91543 100644
--- a/wezterm-gui/src/frontend.rs
+++ b/wezterm-gui/src/frontend.rs
@@ -445,11 +445,19 @@ impl GuiFrontEnd {
}
let mux = Mux::get();
- let Some(mux_window) = mux.get_window(mux_window_id) else {
- continue;
+ let (is_domain_owned, window_workspace) = {
+ let Some(mux_window) = mux.get_window(mux_window_id) else {
+ continue;
+ };
+ (
+ mux_window.origin_domain().is_some(),
+ mux_window.get_workspace().to_string(),
+ )
};
- let is_domain_owned = mux_window.origin_domain().is_some();
- let window_workspace = mux_window.get_workspace();
+ // `get_window` holds a read guard for the mux's complete
+ // window map. Drop it before awaiting native window creation:
+ // startup content views register a UI surface, which needs the
+ // write side of the same lock.
// Client domains mirror every remote mux window locally when
// they attach. That includes the server's own startup
@@ -459,7 +467,7 @@ impl GuiFrontEnd {
// giving them a GUI window creates the stray "local Space with
// a remote terminal" window and tangles its lifecycle with the
// real thread window.
- if !should_spawn_reconciled_gui_window(is_domain_owned, window_workspace) {
+ if !should_spawn_reconciled_gui_window(is_domain_owned, &window_workspace) {
log::debug!(
"reconcile: leaving background domain window {} in workspace {:?} hidden",
mux_window_id,
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index 036e07d8..aa7d344f 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -475,6 +475,13 @@ pub(crate) async fn connect_domain_into_space(
let config = config::configuration();
config.update_ulimit()?;
+ // Keep the claimed connect window alive from the authentication UI all
+ // the way through creation of its first remote pane. ClientDomain::attach
+ // has its own Activity, but drops it before returning; closing the
+ // ConnectionUI can then prune this still-empty window before spawn()
+ // installs the first tab.
+ let connect_activity = mux::activity::Activity::new();
+
// The ConnectionUI (auth prompts) appears as a tab inside this window.
// Transient network failures (VPN egress rotation, sleepy wifi) are
// common on the way to a remote mux; keep retrying with backoff instead
@@ -534,6 +541,7 @@ pub(crate) async fn connect_domain_into_space(
)
.await?;
}
+ drop(connect_activity);
trigger_and_log_gui_attached(MuxDomain(domain.domain_id())).await;
// No explicit workspace rename AFTER attach: the window was created in
diff --git a/wezterm-gui/src/markdown_editor/document.rs b/wezterm-gui/src/markdown_editor/document.rs
index 0db5dbb3..06c22c3a 100644
--- a/wezterm-gui/src/markdown_editor/document.rs
+++ b/wezterm-gui/src/markdown_editor/document.rs
@@ -507,7 +507,10 @@ impl MarkdownDocumentSession {
.saturating_sub(1);
let (line_start, delta) = deltas[index];
let shifted_start: isize = line_start as isize
- + deltas[..index].iter().map(|(_, delta)| *delta).sum::<isize>();
+ + deltas[..index]
+ .iter()
+ .map(|(_, delta)| *delta)
+ .sum::<isize>();
let relative = position - line_start;
let relative = if delta >= 0 {
relative + delta as usize
@@ -753,9 +756,7 @@ impl MarkdownDocumentSession {
&& (self.undo.len() > MAX_UNDO_RECORDS || self.undo_bytes > MAX_UNDO_BYTES)
{
let evicted = self.undo.remove(0);
- self.undo_bytes = self
- .undo_bytes
- .saturating_sub(edit_record_bytes(&evicted));
+ self.undo_bytes = self.undo_bytes.saturating_sub(edit_record_bytes(&evicted));
}
}
@@ -1141,9 +1142,12 @@ mod tests {
session.select_all(&mut view);
session.insert_text(&mut view, &big);
}
- assert!(session.undo_bytes <= MAX_UNDO_BYTES.max(edit_record_bytes(
- session.undo.last().expect("newest record retained")
- )));
+ assert!(
+ session.undo_bytes
+ <= MAX_UNDO_BYTES.max(edit_record_bytes(
+ session.undo.last().expect("newest record retained")
+ ))
+ );
// Older records were evicted to honor the byte cap...
assert!(session.undo.len() < 4);
// ...but the newest edit is always undoable.
diff --git a/wezterm-gui/src/markdown_editor/host.rs b/wezterm-gui/src/markdown_editor/host.rs
index eb92b88d..a8c2b1f4 100644
--- a/wezterm-gui/src/markdown_editor/host.rs
+++ b/wezterm-gui/src/markdown_editor/host.rs
@@ -301,8 +301,7 @@ impl NoteHostState {
// multi-megabyte note paints useful first-screen text immediately.
// The full background parse installs honest metrics right after.
self.refresh_wrap_work_metrics(snapshot.source.len());
- self.background_wrap_preferred =
- self.wrap_work_estimate >= BACKGROUND_WRAP_THRESHOLD_BYTES;
+ self.background_wrap_preferred = self.wrap_work_estimate >= BACKGROUND_WRAP_THRESHOLD_BYTES;
self.visual_key = Some((snapshot.revision, self.view.mode, active_start));
// This is deliberately not the complete revision. The regular
// background parse path will replace it with the full projection.
@@ -562,9 +561,7 @@ impl NoteHostState {
return false;
}
self.parse_in_flight_revision = None;
- let display_revision = self
- .display_snapshot()
- .map(|snapshot| snapshot.revision);
+ let display_revision = self.display_snapshot().map(|snapshot| snapshot.revision);
if display_revision != Some(revision)
|| self.view.mode != mode
|| self.view.selection.focus.byte != caret
@@ -658,8 +655,7 @@ impl NoteHostState {
self.wrap_work_estimate = self.visual.estimated_wrap_work_bytes();
self.displayed_source_bytes = displayed_source_bytes;
self.visual_line_count = self.visual.lines.len();
- self.background_wrap_preferred = self.wrap_work_estimate
- >= BACKGROUND_WRAP_THRESHOLD_BYTES
+ self.background_wrap_preferred = self.wrap_work_estimate >= BACKGROUND_WRAP_THRESHOLD_BYTES
|| self.displayed_source_bytes > PRIMED_SYNC_WRAP_MAX_SOURCE_BYTES
|| self.visual_line_count > PRIMED_SYNC_WRAP_MAX_LINES;
}
@@ -1035,9 +1031,8 @@ impl NoteHostState {
let (right_x, right_byte) = pair[1];
let min_x = left_x.min(right_x);
let max_x = left_x.max(right_x);
- (x >= min_x && x < max_x).then(|| {
- left_byte.min(right_byte)..left_byte.max(right_byte)
- })
+ (x >= min_x && x < max_x)
+ .then(|| left_byte.min(right_byte)..left_byte.max(right_byte))
})
.unwrap_or_else(|| run.source.clone());
self.projection
@@ -1225,7 +1220,9 @@ mod state_tests {
let mut other_view = EditorViewState::default();
let end = session.lock().source().len();
session.lock().set_caret(&mut other_view, end, false);
- assert!(session.lock().insert_text(&mut other_view, " and [[Extra]]"));
+ assert!(session
+ .lock()
+ .insert_text(&mut other_view, " and [[Extra]]"));
// The Published host must request its displayed (published) snapshot,
// not the newer dirty session text.
@@ -1414,10 +1411,7 @@ mod state_tests {
);
// Table-heavy note: same rule via the table rows.
- let table_source = format!(
- "| A | B |\n| - | - |\n{}",
- "| aa | bb |\n".repeat(5_000)
- );
+ let table_source = format!("| A | B |\n| - | - |\n{}", "| aa | bb |\n".repeat(5_000));
let mut table_host = host_with_source(&table_source);
assert!(table_host.visual_line_count > PRIMED_SYNC_WRAP_MAX_LINES);
assert!(table_host.prefers_background_wrap());
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rs
index c9968340..a6b81f58 100644
--- a/wezterm-gui/src/native_settings.rs
+++ b/wezterm-gui/src/native_settings.rs
@@ -8,18 +8,33 @@ use window::{Appearance, Connection, ConnectionOps};
// One point is one logical pixel on macOS but 4/3 px at 96dpi, so the
// non-mac size is 0.75x for the same visual size (14px UI text).
-pub(crate) const DEFAULT_SETTINGS_FONT_SIZE: f64 =
- if cfg!(target_os = "macos") { 14.0 } else { 10.5 };
+pub(crate) const DEFAULT_SETTINGS_FONT_SIZE: f64 = if cfg!(target_os = "macos") {
+ 14.0
+} else {
+ 10.5
+};
pub(crate) const DEFAULT_SETTINGS_FONT_WEIGHT: u16 =
if cfg!(target_os = "macos") { 600 } else { 500 };
-pub(crate) const DEFAULT_HOME_FONT_SIZE: f64 =
- if cfg!(target_os = "macos") { 15.0 } else { 11.25 };
-pub(crate) const DEFAULT_SIDEBAR_FONT_SIZE: f64 =
- if cfg!(target_os = "macos") { 15.0 } else { 11.25 };
-pub(crate) const DEFAULT_TAB_FONT_SIZE: f64 =
- if cfg!(target_os = "macos") { 14.0 } else { 10.5 };
-pub(crate) const DEFAULT_PANE_HEADER_FONT_SIZE: f64 =
- if cfg!(target_os = "macos") { 14.0 } else { 10.5 };
+pub(crate) const DEFAULT_HOME_FONT_SIZE: f64 = if cfg!(target_os = "macos") {
+ 15.0
+} else {
+ 11.25
+};
+pub(crate) const DEFAULT_SIDEBAR_FONT_SIZE: f64 = if cfg!(target_os = "macos") {
+ 15.0
+} else {
+ 11.25
+};
+pub(crate) const DEFAULT_TAB_FONT_SIZE: f64 = if cfg!(target_os = "macos") {
+ 14.0
+} else {
+ 10.5
+};
+pub(crate) const DEFAULT_PANE_HEADER_FONT_SIZE: f64 = if cfg!(target_os = "macos") {
+ 14.0
+} else {
+ 10.5
+};
pub(crate) const DEFAULT_BOTTOM_QUOTE_INTERVAL_MINUTES: u32 = 60;
pub(crate) const DEFAULT_BOTTOM_QUOTE_FONT_SIZE: f64 =
if cfg!(target_os = "macos") { 10.0 } else { 7.5 };
@@ -270,6 +285,22 @@ impl Default for NativeWindowSettings {
}
}
+pub(crate) const DEFAULT_REMOTE_SFTP_IDLE_MINUTES: u32 = 15;
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(default)]
+pub(crate) struct NativeWorkspaceSettings {
+ pub(crate) remote_sftp_idle_minutes: u32,
+}
+
+impl Default for NativeWorkspaceSettings {
+ fn default() -> Self {
+ Self {
+ remote_sftp_idle_minutes: DEFAULT_REMOTE_SFTP_IDLE_MINUTES,
+ }
+ }
+}
+
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub(crate) struct ThinkTermNativeSettings {
@@ -281,6 +312,7 @@ pub(crate) struct ThinkTermNativeSettings {
pub(crate) onboarding: NativeOnboardingSettings,
pub(crate) compatibility: NativeCompatibilitySettings,
pub(crate) window: NativeWindowSettings,
+ pub(crate) workspaces: NativeWorkspaceSettings,
}
impl Default for ThinkTermNativeSettings {
@@ -294,10 +326,15 @@ impl Default for ThinkTermNativeSettings {
onboarding: NativeOnboardingSettings::default(),
compatibility: NativeCompatibilitySettings::default(),
window: NativeWindowSettings::default(),
+ workspaces: NativeWorkspaceSettings::default(),
}
}
}
+pub(crate) fn remote_sftp_idle_minutes() -> u32 {
+ load().workspaces.remote_sftp_idle_minutes.clamp(1, 120)
+}
+
pub(crate) fn settings_path() -> PathBuf {
config::HOME_DIR
.join(".config")
@@ -634,4 +671,13 @@ mod tests {
assert_eq!(settings.onboarding.seen_version, ONBOARDING_VERSION);
}
+
+ #[test]
+ fn older_settings_default_remote_sftp_idle_timeout() {
+ let settings: ThinkTermNativeSettings = serde_json::from_str(r#"{"version":1}"#).unwrap();
+ assert_eq!(
+ settings.workspaces.remote_sftp_idle_minutes,
+ DEFAULT_REMOTE_SFTP_IDLE_MINUTES
+ );
+ }
}
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index b2e2b801..915b927a 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -8,9 +8,9 @@ use crate::termwindow::render::corners::{
use crate::termwindow::render::draw::draw_webgpu_layers;
use crate::termwindow::webgpu::WebGpuState;
use crate::ui::{
- rect, scale_ui_f32, scale_ui_usize, ButtonSpec, ControlState, InteractionState,
- ResizablePaneState, ScrollState, ScrollbarSpec, SettingsIcon, SvgIcon, TextInputSpec,
- TextInputState, UiContext, UiPalette, UiTokens, WidgetKind,
+ rect, scale_ui_f32, scale_ui_usize, ButtonSpec, ControlState, EditModifiers, InputCaret,
+ InteractionState, ResizablePaneState, ScrollState, ScrollbarSpec, SettingsIcon, SvgIcon,
+ TextInputSpec, TextInputState, UiContext, UiPalette, UiTokens, WidgetKind,
};
use crate::utilsprites::RenderMetrics;
use anyhow::Context;
@@ -239,7 +239,15 @@ impl SettingsSection {
"Reset Quotes JSON",
"Terminal",
],
- Self::Workspaces => &["Workspace", "Sidebar", "Session", "Layout"],
+ Self::Workspaces => &[
+ "Workspace",
+ "Sidebar",
+ "Session",
+ "Layout",
+ "Remote Files",
+ "SFTP",
+ "Idle Timeout",
+ ],
Self::Keymap => &["Keymap", "Keyboard", "Shortcut", "Command Palette"],
Self::Compatibility => &[
"ThinkTerm Config",
@@ -337,6 +345,9 @@ enum SettingsAction {
DecreaseBottomQuoteInterval,
IncreaseBottomQuoteInterval,
ResetBottomQuoteInterval,
+ DecreaseRemoteSftpIdle,
+ IncreaseRemoteSftpIdle,
+ ResetRemoteSftpIdle,
OpenBottomQuotesJson,
ResetBottomQuotesJson,
SearchInput,
@@ -1064,10 +1075,7 @@ mod config_candidate_tests {
settings_window_pixel_size(96, Some((1366, 768))),
(920, 603)
);
- assert_eq!(
- settings_window_pixel_size(96, Some((900, 620))),
- (810, 558)
- );
+ assert_eq!(settings_window_pixel_size(96, Some((900, 620))), (810, 558));
}
}
}
@@ -1273,6 +1281,11 @@ impl SettingsWindow {
scale_ui_f32(value, self.dimensions.dpi)
}
+ /// Design-pixel -> physical-pixel ratio for this window.
+ fn ui_scale(&self) -> f32 {
+ crate::ui::ui_scale_for_dpi(self.dimensions.dpi)
+ }
+
fn ui_usize(&self, value: usize) -> usize {
scale_ui_usize(value, self.dimensions.dpi)
}
@@ -1310,8 +1323,7 @@ impl SettingsWindow {
)
})
};
- let (pixel_width, pixel_height) =
- settings_window_pixel_size(dpi, active_screen_size);
+ let (pixel_width, pixel_height) = settings_window_pixel_size(dpi, active_screen_size);
let dimensions = Dimensions {
pixel_width,
pixel_height,
@@ -1319,16 +1331,23 @@ impl SettingsWindow {
};
let mut ui = SettingsUiState::new(dpi);
- ui.font_size_input.text = native_settings
- .terminal
- .font_size
- .map(|value| format!("{value:.1}"))
- .unwrap_or_else(|| format!("{:.1}", config.font_size));
- ui.font_family_input.text = native_settings
- .terminal
- .font_family
- .clone()
- .unwrap_or_else(|| Self::effective_font_family(&config));
+ // Must go through `set_text_end`: assigning `.text` leaves the caret at
+ // 0, so typing into a prefilled field would insert at the front and
+ // Backspace would do nothing.
+ ui.font_size_input.set_text_end(
+ native_settings
+ .terminal
+ .font_size
+ .map(|value| format!("{value:.1}"))
+ .unwrap_or_else(|| format!("{:.1}", config.font_size)),
+ );
+ ui.font_family_input.set_text_end(
+ native_settings
+ .terminal
+ .font_family
+ .clone()
+ .unwrap_or_else(|| Self::effective_font_family(&config)),
+ );
let settings = Rc::new(RefCell::new(Self {
instance_id,
@@ -1662,11 +1681,22 @@ impl SettingsWindow {
self.dimensions.pixel_width as f32 - sidebar_width - 1.0,
(self.content_bottom() - content_top).max(0.0),
);
- if crate::ui::apply_wheel_to_area(event, sidebar_area, &mut self.ui.sidebar_scroll) {
+ let ui_scale = self.ui_scale();
+ if crate::ui::apply_wheel_to_area(
+ event,
+ sidebar_area,
+ &mut self.ui.sidebar_scroll,
+ ui_scale,
+ ) {
self.show_sidebar_scrollbar(window);
return true;
}
- if crate::ui::apply_wheel_to_area(event, content_area, &mut self.ui.content_scroll) {
+ if crate::ui::apply_wheel_to_area(
+ event,
+ content_area,
+ &mut self.ui.content_scroll,
+ ui_scale,
+ ) {
self.show_content_scrollbar(window);
return true;
}
@@ -1840,20 +1870,8 @@ impl SettingsWindow {
return false;
};
- if event
- .modifiers
- .intersects(Modifiers::SUPER | Modifiers::CTRL)
- && !event.modifiers.intersects(Modifiers::ALT)
- {
- 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)
- }
- _ => false,
- };
+ if let Some(handled) = self.handle_focused_input_key(focused, &event, window) {
+ return handled;
}
if event
@@ -1883,54 +1901,30 @@ impl SettingsWindow {
}
}
- fn focused_input_text(&self, focused: SettingsAction) -> Option<&str> {
- match focused {
- SettingsAction::SearchInput => Some(&self.ui.search.text),
- SettingsAction::FontFamilyInput => Some(&self.ui.font_family_input.text),
- _ => None,
- }
- }
-
- fn select_all_focused_input(&mut self, focused: SettingsAction) -> bool {
- match focused {
- SettingsAction::SearchInput => {
- self.ui.search.select_all();
- true
- }
- SettingsAction::FontFamilyInput => {
- self.ui.font_family_input.select_all();
- true
- }
- _ => false,
- }
- }
-
+ /// Copies the selection when there is one, otherwise the whole field —
+ /// matching `SshHostsView::copy_text`.
fn copy_focused_input(&mut self, focused: SettingsAction, window: &Window) -> bool {
- let Some(text) = self.focused_input_text(focused) else {
+ let Some(input) = self.input_state_for(focused) else {
return false;
};
- window.set_clipboard(Clipboard::Clipboard, text.to_string());
+ let text = input
+ .caret_selected_text()
+ .unwrap_or_else(|| input.text().to_string());
+ if text.is_empty() {
+ return false;
+ }
+ window.set_clipboard(Clipboard::Clipboard, text);
true
}
+ /// Cut only ever acts on a real selection, like every native text field.
+ /// Routed through `edit_focused_input` so each field's side effects (search
+ /// re-filter, font-family dirty flag) still run.
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.ui.font_family_input_dirty = true;
- text
- }
- _ => return false,
+ let mut taken = None;
+ self.edit_focused_input(focused, |input| taken = input.caret_take_selected_text());
+ let Some(text) = taken.filter(|text| !text.is_empty()) else {
+ return false;
};
window.set_clipboard(Clipboard::Clipboard, text);
true
@@ -1963,16 +1957,59 @@ impl SettingsWindow {
true
}
+ /// Width of `text[..char_idx]` using the same measurement the renderer
+ /// uses, so a caret never drifts from the glyphs it sits between.
+ fn text_width_to_char(&self, font: &Rc<LoadedFont>, text: &str, char_idx: usize) -> f32 {
+ let byte_idx = text
+ .char_indices()
+ .nth(char_idx)
+ .map(|(idx, _)| idx)
+ .unwrap_or(text.len());
+ self.measure_text_width(font, &text[..byte_idx])
+ }
+
+ fn input_state_for(&self, action: SettingsAction) -> Option<&TextInputState> {
+ match action {
+ SettingsAction::SearchInput => Some(&self.ui.search),
+ SettingsAction::FontFamilyInput => Some(&self.ui.font_family_input),
+ _ => None,
+ }
+ }
+
+ /// Caret + selection to draw for `action`, or `None` when it is not focused.
+ fn caret_for_input(&self, action: SettingsAction) -> Option<InputCaret> {
+ if self.ui.interaction.focused != Some(action) {
+ return None;
+ }
+ let input = self.input_state_for(action)?;
+ Some(InputCaret {
+ cursor: input.cursor,
+ selection: input.caret_selection_range(),
+ })
+ }
+
fn backspace_focused_input(&mut self, focused: SettingsAction) -> bool {
+ self.edit_focused_input(focused, |input| input.caret_backspace())
+ }
+
+ /// Run `f` against the focused field's caret model, then apply that
+ /// field's side effects (search re-filter / font-family dirty flag).
+ /// Every editing key routes through here so the two inputs can never
+ /// drift apart again.
+ fn edit_focused_input(
+ &mut self,
+ focused: SettingsAction,
+ f: impl FnOnce(&mut TextInputState),
+ ) -> bool {
match focused {
SettingsAction::SearchInput => {
- self.ui.search.backspace();
+ f(&mut self.ui.search);
self.ui.sidebar_scroll.reset();
self.sync_selected_section_with_search();
true
}
SettingsAction::FontFamilyInput => {
- self.ui.font_family_input.backspace();
+ f(&mut self.ui.font_family_input);
self.ui.font_family_input_dirty = true;
true
}
@@ -1980,23 +2017,90 @@ impl SettingsWindow {
}
}
- fn push_focused_input(&mut self, focused: SettingsAction, text: &str) -> bool {
- match focused {
- SettingsAction::SearchInput => {
- self.ui.search.push_text(text);
- self.ui.sidebar_scroll.reset();
- self.sync_selected_section_with_search();
- true
+ /// Editing keys for the focused input. `None` means "not an editing key",
+ /// so the caller can fall through to its own handling.
+ fn handle_focused_input_key(
+ &mut self,
+ focused: SettingsAction,
+ event: &KeyEvent,
+ window: &Window,
+ ) -> Option<bool> {
+ let edit = EditModifiers::from(event.modifiers);
+ let shift = edit.shift;
+ let macos = cfg!(target_os = "macos");
+
+ if edit.command {
+ match event.key {
+ KeyCode::Char('a') | KeyCode::Char('A') => {
+ return Some(
+ self.edit_focused_input(focused, |input| input.caret_select_all()),
+ );
+ }
+ KeyCode::Char('c') | KeyCode::Char('C') => {
+ return Some(self.copy_focused_input(focused, window));
+ }
+ KeyCode::Char('x') | KeyCode::Char('X') => {
+ return Some(self.cut_focused_input(focused, window));
+ }
+ KeyCode::Char('v') | KeyCode::Char('V') => {
+ return Some(self.paste_focused_input_from_clipboard(focused, window));
+ }
+ KeyCode::LeftArrow if macos => {
+ return Some(
+ self.edit_focused_input(focused, |input| input.caret_move_home(shift)),
+ );
+ }
+ KeyCode::RightArrow if macos => {
+ return Some(
+ self.edit_focused_input(focused, |input| input.caret_move_end(shift)),
+ );
+ }
+ _ => {}
}
- SettingsAction::FontFamilyInput => {
- self.ui.font_family_input.push_text(text);
- self.ui.font_family_input_dirty = true;
- true
+ }
+
+ if edit.word {
+ match event.key {
+ KeyCode::LeftArrow => {
+ return Some(
+ self.edit_focused_input(focused, |input| input.caret_word_left(shift)),
+ );
+ }
+ KeyCode::RightArrow => {
+ return Some(
+ self.edit_focused_input(focused, |input| input.caret_word_right(shift)),
+ );
+ }
+ _ => {}
}
- _ => false,
+ }
+
+ if !edit.plain() {
+ return None;
+ }
+
+ match event.key {
+ KeyCode::LeftArrow => {
+ Some(self.edit_focused_input(focused, |input| input.caret_move_left(shift)))
+ }
+ KeyCode::RightArrow => {
+ Some(self.edit_focused_input(focused, |input| input.caret_move_right(shift)))
+ }
+ KeyCode::Home => {
+ Some(self.edit_focused_input(focused, |input| input.caret_move_home(shift)))
+ }
+ KeyCode::End => {
+ Some(self.edit_focused_input(focused, |input| input.caret_move_end(shift)))
+ }
+ _ => None,
}
}
+ fn push_focused_input(&mut self, focused: SettingsAction, text: &str) -> bool {
+ let text = text.to_string();
+ self.edit_focused_input(focused, move |input| input.caret_insert(&text, false))
+ }
+
fn set_focused_input(&mut self, focused: Option<SettingsAction>) {
if self.ui.interaction.focused != focused {
self.commit_focused_input();
@@ -2018,7 +2122,7 @@ impl SettingsWindow {
}
self.ui.font_family_input_dirty = false;
- let family = self.ui.font_family_input.text.trim();
+ let family = self.ui.font_family_input.text().trim();
let next = if family.is_empty() {
None
} else {
@@ -2042,7 +2146,7 @@ impl SettingsWindow {
fn current_terminal_font_size_value(&self) -> f64 {
self.ui
.font_size_input
- .text
+ .text()
.trim()
.parse::<f64>()
.ok()
@@ -2052,14 +2156,16 @@ impl SettingsWindow {
fn step_terminal_font_size(&mut self, delta: f64) {
let value = (self.current_terminal_font_size_value() + delta).clamp(8.0, 48.0);
- self.ui.font_size_input.text = format!("{value:.1}");
+ self.ui.font_size_input.set_text_end(format!("{value:.1}"));
self.native_settings.terminal.font_size = Some(value);
self.save_and_apply_native_terminal_settings();
}
fn reset_terminal_font_size(&mut self) {
let config = configuration();
- self.ui.font_size_input.text = format!("{:.1}", config.font_size);
+ self.ui
+ .font_size_input
+ .set_text_end(format!("{:.1}", config.font_size));
self.native_settings.terminal.font_size = None;
self.save_and_apply_native_terminal_settings();
}
@@ -2092,6 +2198,37 @@ impl SettingsWindow {
));
}
+ fn current_remote_sftp_idle_minutes(&self) -> u32 {
+ self.native_settings
+ .workspaces
+ .remote_sftp_idle_minutes
+ .clamp(1, 120)
+ }
+
+ fn step_remote_sftp_idle(&mut self, delta: i32) {
+ let value = (self.current_remote_sftp_idle_minutes() as i32 + delta).clamp(1, 120) as u32;
+ self.native_settings.workspaces.remote_sftp_idle_minutes = value;
+ self.save_remote_sftp_idle(value);
+ }
+
+ fn reset_remote_sftp_idle(&mut self) {
+ let value = crate::native_settings::DEFAULT_REMOTE_SFTP_IDLE_MINUTES;
+ self.native_settings.workspaces.remote_sftp_idle_minutes = value;
+ self.save_remote_sftp_idle(value);
+ }
+
+ fn save_remote_sftp_idle(&mut self, value: u32) {
+ match crate::native_settings::save(&self.native_settings) {
+ Ok(()) => {
+ crate::termwindow::remote_files::update_remote_connection_idle_timeout(value);
+ self.status = format!("Remote Files idle timeout is now {value} minutes.");
+ }
+ Err(err) => {
+ self.status = format!("Unable to save Remote Files idle timeout: {err:#}");
+ }
+ }
+ }
+
fn format_bottom_quote_interval(minutes: u32) -> String {
if minutes < 60 {
format!("{minutes} min")
@@ -2630,6 +2767,9 @@ impl SettingsWindow {
SettingsAction::DecreaseBottomQuoteInterval => self.step_bottom_quote_interval(-5),
SettingsAction::IncreaseBottomQuoteInterval => self.step_bottom_quote_interval(5),
SettingsAction::ResetBottomQuoteInterval => self.reset_bottom_quote_interval(),
+ SettingsAction::DecreaseRemoteSftpIdle => self.step_remote_sftp_idle(-5),
+ SettingsAction::IncreaseRemoteSftpIdle => self.step_remote_sftp_idle(5),
+ SettingsAction::ResetRemoteSftpIdle => self.reset_remote_sftp_idle(),
SettingsAction::OpenBottomQuotesJson => {
self.ui.open_dropdown = None;
match crate::bottom_quotes::ensure_quotes_file() {
@@ -2968,12 +3108,11 @@ impl SettingsWindow {
}
}
- let corner_radius =
- crate::termwindow::render::draw::effective_window_corner_radius(
- configuration().window_decorations,
- self.window_state,
- self.dimensions.dpi,
- );
+ let corner_radius = crate::termwindow::render::draw::effective_window_corner_radius(
+ configuration().window_decorations,
+ self.window_state,
+ self.dimensions.dpi,
+ );
let window_border = crate::termwindow::render::draw::effective_window_border(
configuration().window_decorations,
self.window_state,
@@ -3271,7 +3410,7 @@ impl SettingsWindow {
sidebar_width - tokens.sidebar_padding * 2.0,
tokens.control_height,
);
- let search_text = self.ui.search.text.clone();
+ let search_text = self.ui.search.text().to_string();
self.paint_text_input(
layers,
TextInputSpec {
@@ -3495,13 +3634,7 @@ impl SettingsWindow {
SettingsSection::Compatibility => self.paint_compatibility(layers, x, max_width)?,
SettingsSection::General => self.paint_general(layers, x, max_width)?,
SettingsSection::Terminal => self.paint_terminal(layers, x, max_width)?,
- SettingsSection::Workspaces => self.paint_placeholder(
- layers,
- &ui_font,
- x,
- "Workspace list, default workspace, sidebar behavior, and saved layouts.",
- max_width,
- )?,
+ SettingsSection::Workspaces => self.paint_workspaces(layers, x, max_width)?,
SettingsSection::Keymap => self.paint_placeholder(
layers,
&ui_font,
@@ -3773,6 +3906,55 @@ impl SettingsWindow {
Ok(())
}
+ fn paint_workspaces(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ max_width: f32,
+ ) -> anyhow::Result<()> {
+ let palette = self.palette();
+ let ui_font = Rc::clone(&self.ui_font);
+ let scroll = self.ui.content_scroll.offset;
+ let section_y = self.ui_px(CONTENT_SECTION_Y) - scroll;
+ let row_count = 1;
+ let (card_y, first_row_y) = self.settings_card_geometry(section_y, row_count);
+ let card_height = self.settings_card_height(row_count);
+ self.ui.content_scroll.set_extents(
+ self.content_viewport_extent(),
+ self.settings_content_extent(card_y + scroll + card_height),
+ );
+
+ self.draw_text(
+ layers,
+ &ui_font,
+ x,
+ section_y,
+ "Remote Files",
+ palette.muted_text,
+ max_width,
+ )?;
+ let padding = 36.0;
+ let row_x = x + padding;
+ let row_width = max_width - padding * 2.0;
+ self.paint_group_card(layers, x, card_y, max_width, card_height)?;
+ let minutes = self.current_remote_sftp_idle_minutes();
+ let value_label = format!("{minutes} min");
+ self.paint_font_size_stepper_row(
+ layers,
+ row_x,
+ first_row_y,
+ row_width,
+ "Remote Files Connection Idle Timeout",
+ "Disconnects an unused SFTP session; directory and preview data are released immediately.",
+ minutes as f64,
+ Some(&value_label),
+ SettingsAction::ResetRemoteSftpIdle,
+ SettingsAction::DecreaseRemoteSftpIdle,
+ SettingsAction::IncreaseRemoteSftpIdle,
+ false,
+ )
+ }
+
fn paint_terminal(
&mut self,
layers: &mut TripleLayerQuadAllocator<'_>,
@@ -3858,7 +4040,7 @@ impl SettingsWindow {
SettingsAction::IncreaseFontSize,
true,
)?;
- let native_font_family = self.ui.font_family_input.text.clone();
+ let native_font_family = self.ui.font_family_input.text().to_string();
self.paint_text_setting_row(
layers,
row_x,
@@ -4594,7 +4776,8 @@ impl SettingsWindow {
.memory_snapshot_copied_until
.is_some_and(|until| Instant::now() < until);
let copy_label = if copied { "Copied" } else { "Copy" };
- let copy_x = refresh_x + self.button_width_for_label("Refresh Now", 210.0) + self.ui_px(16.0);
+ let copy_x =
+ refresh_x + self.button_width_for_label("Refresh Now", 210.0) + self.ui_px(16.0);
self.draw_button(
layers,
copy_x,
@@ -4616,7 +4799,8 @@ impl SettingsWindow {
input_primary_label,
SettingsAction::ToggleInputDiagnostics,
)?;
- let reset_input_x = x + self.button_width_for_label(input_primary_label, 250.0) + self.ui_px(16.0);
+ let reset_input_x =
+ x + self.button_width_for_label(input_primary_label, 250.0) + self.ui_px(16.0);
self.draw_button(
layers,
reset_input_x,
@@ -4630,7 +4814,8 @@ impl SettingsWindow {
.input_diagnostics_copied_until
.is_some_and(|until| Instant::now() < until);
let input_copy_label = if input_copied { "Copied" } else { "Copy Input" };
- let copy_input_x = reset_input_x + self.button_width_for_label("Reset Input", 190.0) + self.ui_px(16.0);
+ let copy_input_x =
+ reset_input_x + self.button_width_for_label("Reset Input", 190.0) + self.ui_px(16.0);
self.draw_button(
layers,
copy_input_x,
@@ -5078,7 +5263,8 @@ impl SettingsWindow {
"Load WezTerm Source",
SettingsAction::LoadWezTermSource,
)?;
- let second_x = x + self.button_width_for_label("Load WezTerm Source", 290.0) + self.ui_px(16.0);
+ let second_x =
+ x + self.button_width_for_label("Load WezTerm Source", 290.0) + self.ui_px(16.0);
self.draw_button(
layers,
second_x,
@@ -5087,7 +5273,8 @@ impl SettingsWindow {
"Select All",
SettingsAction::SelectAllImportFields,
)?;
- let third_x = second_x + self.button_width_for_label("Select All", 180.0) + self.ui_px(16.0);
+ let third_x =
+ second_x + self.button_width_for_label("Select All", 180.0) + self.ui_px(16.0);
self.draw_button(
layers,
third_x,
@@ -5114,7 +5301,8 @@ impl SettingsWindow {
"Open WezTerm Source",
SettingsAction::OpenWezTermConfigFile,
)?;
- let fifth_x = x + self.button_width_for_label("Open WezTerm Source", 300.0) + self.ui_px(16.0);
+ let fifth_x =
+ x + self.button_width_for_label("Open WezTerm Source", 300.0) + self.ui_px(16.0);
self.draw_button(
layers,
fifth_x,
@@ -5515,7 +5703,8 @@ impl SettingsWindow {
palette.control_border,
self.ui_px(CONTROL_RADIUS),
)?;
- let preview = self.text_with_ellipsis(&ui_font, &field.preview, value_width - self.ui_px(28.0));
+ let preview =
+ self.text_with_ellipsis(&ui_font, &field.preview, value_width - self.ui_px(28.0));
self.draw_text(
layers,
&ui_font,
@@ -5781,47 +5970,58 @@ impl SettingsWindow {
} else {
palette.text
};
- let selected_all = match action {
- SettingsAction::FontFamilyInput => self.ui.font_family_input.selected_all,
- _ => 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 + 12.0,
- control_y + self.ui_px(6.0),
- selection_width + self.ui_px(8.0),
- self.ui_px(CONTROL_HEIGHT) - 12.0,
- palette.nav_selected_bg.mul_alpha(0.56),
- self.ui_px(CONTROL_RADIUS - 4.0),
- )?;
+ let text_left = control_x + self.ui_px(16.0);
+ let text_area = (control_width - self.ui_px(32.0)).max(0.0);
+ let selection = self
+ .caret_for_input(action)
+ .and_then(|caret| caret.selection)
+ .filter(|(start, end)| start != end)
+ .or_else(|| {
+ let selected_all = self
+ .input_state_for(action)
+ .is_some_and(|input| input.selected_all);
+ (selected_all && !value.is_empty()).then(|| (0, value.chars().count()))
+ });
+ if focused && !value.is_empty() {
+ if let Some((start, end)) = selection {
+ let start_x = self
+ .text_width_to_char(&ui_font, value, start)
+ .min(text_area);
+ let end_x = self.text_width_to_char(&ui_font, value, end).min(text_area);
+ self.draw_rounded_rect(
+ layers,
+ 1,
+ text_left + start_x - self.ui_px(4.0),
+ control_y + self.ui_px(6.0),
+ (end_x - start_x) + self.ui_px(8.0),
+ self.ui_px(CONTROL_HEIGHT - 12.0),
+ palette.nav_selected_bg.mul_alpha(0.56),
+ self.ui_px(CONTROL_RADIUS - 4.0),
+ )?;
+ }
}
self.draw_text(
layers,
&ui_font,
- control_x + self.ui_px(16.0),
+ text_left,
self.control_text_y(control_y, self.ui_px(CONTROL_HEIGHT)),
display,
text_color,
- control_width - 32.0,
+ text_area,
)?;
- if focused && !selected_all {
+ if focused && selection.is_none() {
let caret_text = if value.trim().is_empty() { "" } else { value };
- let caret_x = control_x
- + self.ui_px(18.0)
- + self
- .measure_text_width(&ui_font, caret_text)
- .min(control_width - 42.0);
+ let caret_dx = match self.caret_for_input(action) {
+ Some(caret) => self.text_width_to_char(&ui_font, caret_text, caret.cursor),
+ None => self.measure_text_width(&ui_font, caret_text),
+ };
+ let caret_width = self.ui_px(3.0).max(1.0);
self.draw_rect(
layers,
1,
- caret_x - 1.0,
+ text_left + caret_dx.min(text_area) - caret_width / 3.0,
control_y + self.ui_px(8.0),
- self.ui_px(3.0).max(1.0),
+ caret_width,
self.ui_px(CONTROL_HEIGHT - 16.0),
palette.nav_selected_bg,
)?;
@@ -5978,7 +6178,9 @@ impl SettingsWindow {
layers,
&ui_font,
x,
- self.settings_row_description_y(y) + self.metrics.cell_size.height as f32 + self.ui_px(4.0),
+ self.settings_row_description_y(y)
+ + self.metrics.cell_size.height as f32
+ + self.ui_px(4.0),
note,
palette.muted_text,
text_width,
@@ -6125,7 +6327,9 @@ impl SettingsWindow {
} else {
"Restart"
};
- let button_width = self.button_width_for_label(button_label, 0.0).max(self.ui_px(220.0));
+ let button_width = self
+ .button_width_for_label(button_label, 0.0)
+ .max(self.ui_px(220.0));
let button_x = x + width - button_width;
let text_width = (button_x - x - 24.0).max(width * 0.45);
let value = if self.main_renderer_restart_required() {
@@ -6165,7 +6369,11 @@ impl SettingsWindow {
} else {
220.0_f32.min(width * 0.44)
};
- (x + width - control_width, y + self.ui_px(4.0), control_width)
+ (
+ x + width - control_width,
+ y + self.ui_px(4.0),
+ control_width,
+ )
}
fn paint_open_dropdown_overlay(
@@ -6337,7 +6545,12 @@ impl SettingsWindow {
let mut row_y = y + menu_padding;
for (label, action, selected) in options.iter().copied() {
- let row_rect = rect(x + self.ui_px(8.0), row_y, width - self.ui_px(16.0), row_height);
+ let row_rect = rect(
+ x + self.ui_px(8.0),
+ row_y,
+ width - self.ui_px(16.0),
+ row_height,
+ );
self.ui_context.push(row_rect, WidgetKind::Button, action);
let hovered = self.ui.interaction.hovered == Some(action);
let pressed = self.ui.interaction.pressed == Some(action);
@@ -6419,7 +6632,7 @@ impl SettingsWindow {
}
fn filtered_sections(&self) -> Vec<SettingsSection> {
- let query = self.ui.search.text.trim().to_lowercase();
+ let query = self.ui.search.text().trim().to_lowercase();
let sections = self.visible_sections();
if query.is_empty() {
return sections;
@@ -6485,42 +6698,57 @@ impl SettingsWindow {
} else {
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 - self.ui_px(116.0)).max(0.0));
- self.draw_rounded_rect(
- layers,
- 1,
- spec.rect.origin.x + self.ui_px(54.0),
- spec.rect.origin.y + self.ui_px(6.0),
- selection_width + self.ui_px(8.0),
- spec.rect.size.height - 12.0,
- palette.nav_selected_bg.mul_alpha(0.56),
- self.ui.tokens.control_radius - self.ui_px(4.0),
- )?;
+ let font = Rc::clone(&self.ui_font);
+ let text_left = spec.rect.origin.x + self.ui_px(58.0);
+ let text_area = (spec.rect.size.width - self.ui_px(116.0)).max(0.0);
+ let selection = self
+ .caret_for_input(spec.action)
+ .and_then(|caret| caret.selection)
+ .filter(|(start, end)| start != end)
+ .or_else(|| {
+ (spec.selected_all && !spec.text.is_empty()).then(|| (0, spec.text.chars().count()))
+ });
+ if spec.focused && !spec.text.is_empty() {
+ if let Some((start, end)) = selection {
+ let start_x = self
+ .text_width_to_char(&font, spec.text, start)
+ .min(text_area);
+ let end_x = self
+ .text_width_to_char(&font, spec.text, end)
+ .min(text_area);
+ self.draw_rounded_rect(
+ layers,
+ 1,
+ text_left + start_x - self.ui_px(4.0),
+ spec.rect.origin.y + self.ui_px(6.0),
+ (end_x - start_x) + self.ui_px(8.0),
+ spec.rect.size.height - self.ui_px(12.0),
+ palette.nav_selected_bg.mul_alpha(0.56),
+ self.ui.tokens.control_radius - self.ui_px(4.0),
+ )?;
+ }
}
self.draw_text(
layers,
- &Rc::clone(&self.ui_font),
- spec.rect.origin.x + self.ui_px(58.0),
+ &font,
+ text_left,
self.control_text_y(spec.rect.origin.y, spec.rect.size.height),
text,
color,
- spec.rect.size.width - self.ui_px(116.0),
- )?;
- if spec.focused && !spec.selected_all {
- let caret_x = spec.rect.origin.x
- + self.ui_px(60.0)
- + self
- .measure_text_width(&Rc::clone(&self.ui_font), spec.text)
- .min((spec.rect.size.width - 124.0).max(0.0));
+ text_area,
+ )?;
+ if spec.focused && selection.is_none() {
+ let caret_dx = match self.caret_for_input(spec.action) {
+ Some(caret) => self.text_width_to_char(&font, spec.text, caret.cursor),
+ None => self.measure_text_width(&font, spec.text),
+ };
+ let caret_width = self.ui_px(3.0).max(1.0);
self.draw_rect(
layers,
1,
- caret_x - 1.0,
+ text_left + caret_dx.min(text_area) - caret_width / 3.0,
spec.rect.origin.y + self.ui_px(8.0),
- self.ui_px(3.0).max(1.0),
+ caret_width,
spec.rect.size.height - self.ui_px(16.0),
palette.nav_selected_bg,
)?;
diff --git a/wezterm-gui/src/shapecache.rs b/wezterm-gui/src/shapecache.rs
index 2475335f..6c30baba 100644
--- a/wezterm-gui/src/shapecache.rs
+++ b/wezterm-gui/src/shapecache.rs
@@ -235,8 +235,11 @@ pub fn estimate_shaped_entry_bytes(key: &ShapeCacheKey, value: &UiShapedValue) -
.saturating_add(key.text.capacity())
.saturating_add(estimate_text_style_heap_bytes(&key.style));
let value_bytes = match value {
- Ok(shaped) => std::mem::size_of::<Vec<ShapedInfo>>()
- .saturating_add(shaped.capacity().saturating_mul(std::mem::size_of::<ShapedInfo>())),
+ Ok(shaped) => std::mem::size_of::<Vec<ShapedInfo>>().saturating_add(
+ shaped
+ .capacity()
+ .saturating_mul(std::mem::size_of::<ShapedInfo>()),
+ ),
Err(_) => SHAPE_ERR_ENTRY_BYTES,
};
SHAPE_ENTRY_FIXED_OVERHEAD
@@ -478,13 +481,9 @@ mod ui_shape_cache_tests {
let mut caches = caches();
let chrome = caches.domain_mut(UiTextDomain::Chrome);
let probe = key("label");
- assert!(chrome
- .get(&probe as &dyn ShapeCacheKeyTrait)
- .is_none());
+ assert!(chrome.get(&probe as &dyn ShapeCacheKeyTrait).is_none());
chrome.put(key("label"), Ok(Rc::new(vec![])));
- assert!(chrome
- .get(&probe as &dyn ShapeCacheKeyTrait)
- .is_some());
+ assert!(chrome.get(&probe as &dyn ShapeCacheKeyTrait).is_some());
let stats = chrome.stats();
assert_eq!(stats.misses, 1);
assert_eq!(stats.hits, 1);
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index f7a02133..28fd0540 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -96,6 +96,7 @@ pub mod onboarding;
pub mod palette;
pub mod paneselect;
mod prevcursor;
+pub(crate) mod remote_files;
pub mod remote_thread_view;
pub mod render;
pub mod resize;
@@ -369,6 +370,11 @@ pub enum UIItemType {
RightSidebarFileOpenMenu,
RightSidebarFileReveal,
RightSidebarFileCopyText,
+ RightSidebarRemoteFileConnect,
+ RightSidebarRemoteFileRefresh,
+ RightSidebarRemoteFileRow(remote_files::RemotePath),
+ RightSidebarRemoteFileBack,
+ RightSidebarRemoteFileCopyText,
ContextMenuBackdrop,
ContextMenuItem(Vec<usize>),
AboveScrollThumb,
@@ -752,10 +758,7 @@ mod pane_drop_tests {
PaneDropZone::Top,
PaneDropZone::Bottom,
] {
- assert_eq!(
- pane_drop_action(zone, false, 1),
- Some(PaneDropKind::Split)
- );
+ assert_eq!(pane_drop_action(zone, false, 1), Some(PaneDropKind::Split));
}
}
}
@@ -1374,6 +1377,9 @@ pub struct TermWindow {
// re-scan don't lose where you were. Only a few KB of paths each; LRU-bounded.
right_sidebar_file_view_state_by_root: HashMap<(PathBuf, String), RightSidebarFileViewState>,
right_sidebar_file_view_state_order: VecDeque<(PathBuf, String)>,
+ right_sidebar_remote_files: remote_files::RemoteFilesState,
+ right_sidebar_remote_files_lease: Option<remote_files::RemoteConnectionLease>,
+ right_sidebar_remote_file_tree_scroll_offset: f32,
// Bumped to invalidate a pending periodic-rescan timer tick.
right_sidebar_file_rescan_token: u64,
// True while a keep-showing refresh build is in flight (drives the Refresh
@@ -2017,6 +2023,9 @@ impl TermWindow {
right_sidebar_file_preview_restore_scroll: None,
right_sidebar_file_view_state_by_root: HashMap::new(),
right_sidebar_file_view_state_order: VecDeque::new(),
+ right_sidebar_remote_files: remote_files::RemoteFilesState::default(),
+ right_sidebar_remote_files_lease: None,
+ right_sidebar_remote_file_tree_scroll_offset: 0.0,
right_sidebar_file_rescan_token: 0,
right_sidebar_file_refreshing: false,
right_sidebar_open_with_generation: 0,
@@ -3640,7 +3649,6 @@ impl TermWindow {
}
pub(crate) fn content_view_area(&self) -> RectF {
- 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)
@@ -3652,8 +3660,13 @@ impl TermWindow {
} else {
0.0
};
- let left = padding_left + border.left.get() as f32;
- let top = border.top.get() as f32 + top_tab_h + padding_top;
+ // Deliberately *not* inset by `window_padding`: that padding belongs to
+ // the terminal grid, and content views are UI panels that own the whole
+ // area. Applying it only added a left/top gap (the right/bottom edges
+ // never subtracted it) that nothing painted, so the window background
+ // showed through as an L-shaped border.
+ let left = self.workspace_sidebar_width() as f32 + border.left.get() as f32;
+ let top = border.top.get() as f32 + top_tab_h;
let right = self
.dimensions
.pixel_width
@@ -6621,6 +6634,12 @@ impl TermWindow {
impl Drop for TermWindow {
fn drop(&mut self) {
+ // WindowEvent::Destroyed normally releases this claim, but a mux
+ // window can disappear first (for example during an asynchronous
+ // remote attach) and tear down TermWindow without delivering that
+ // native event. Release is idempotent and prevents a vanished window
+ // from leaving its Space permanently marked as occupied.
+ crate::workspace_threads::release_window_space(self.space_owner_id);
crate::input_diagnostics::remove_gauges_for_source(self.space_owner_id);
gpu_debug(format!(
"drop main_window backend={} size={}x{} dpi={}",
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index 56103db8..3979e997 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -89,11 +89,37 @@ fn trailing_action_reserved_width(
})
}
+fn remote_connect_can_reveal(
+ status: Option<&SshConnectionStatus>,
+ workspace_has_window: bool,
+) -> bool {
+ workspace_has_window
+ && matches!(
+ status,
+ Some(SshConnectionStatus::Authenticating | SshConnectionStatus::Connected)
+ )
+}
+
+fn remote_thread_uses_ssh_connection_view(is_remote: bool, space_has_client_domain: bool) -> bool {
+ is_remote && !space_has_client_domain
+}
+
+fn missing_ssh_host_blocks_activation(
+ project_is_remote: bool,
+ has_ssh_host: bool,
+ space_has_client_domain: bool,
+) -> bool {
+ project_is_remote && !has_ssh_host && !space_has_client_domain
+}
+
#[cfg(test)]
mod window_tab_layout_tests {
use super::{
- note_drag_scroll_delta, note_horizontal_scroll_offset, trailing_action_reserved_width,
+ missing_ssh_host_blocks_activation, note_drag_scroll_delta, note_horizontal_scroll_offset,
+ remote_connect_can_reveal, remote_thread_uses_ssh_connection_view,
+ trailing_action_reserved_width,
};
+ use mux::ssh::SshConnectionStatus;
#[test]
fn trailing_actions_keep_tabs_before_the_new_tab_button() {
@@ -129,6 +155,49 @@ mod window_tab_layout_tests {
assert_eq!(note_horizontal_scroll_offset(5.0, -15.0, 100.0), 0.0);
assert_eq!(note_horizontal_scroll_offset(5.0, 15.0, 0.0), 0.0);
}
+
+ #[test]
+ fn remote_connect_reveals_only_after_the_target_workspace_exists() {
+ assert!(!remote_connect_can_reveal(
+ Some(&SshConnectionStatus::Authenticating),
+ false
+ ));
+ assert!(remote_connect_can_reveal(
+ Some(&SshConnectionStatus::Authenticating),
+ true
+ ));
+ assert!(!remote_connect_can_reveal(
+ Some(&SshConnectionStatus::Connected),
+ false
+ ));
+ assert!(remote_connect_can_reveal(
+ Some(&SshConnectionStatus::Connected),
+ true
+ ));
+ assert!(!remote_connect_can_reveal(
+ Some(&SshConnectionStatus::Connecting),
+ true
+ ));
+ assert!(!remote_connect_can_reveal(
+ Some(&SshConnectionStatus::Failed("failed".to_string())),
+ true
+ ));
+ }
+
+ #[test]
+ fn mux_domain_threads_bypass_the_ssh_connection_view() {
+ assert!(remote_thread_uses_ssh_connection_view(true, false));
+ assert!(!remote_thread_uses_ssh_connection_view(true, true));
+ assert!(!remote_thread_uses_ssh_connection_view(false, false));
+ }
+
+ #[test]
+ fn mux_domain_threads_do_not_require_an_ssh_host_record() {
+ assert!(missing_ssh_host_blocks_activation(true, false, false));
+ assert!(!missing_ssh_host_blocks_activation(true, false, true));
+ assert!(!missing_ssh_host_blocks_activation(true, true, false));
+ assert!(!missing_ssh_host_blocks_activation(false, false, false));
+ }
}
/// Overall ceiling on the "Connecting…" phase, as a backstop for the case where
@@ -935,6 +1004,11 @@ impl super::TermWindow {
| UIItemType::RightSidebarFileOpenMenu
| UIItemType::RightSidebarFileReveal
| UIItemType::RightSidebarFileCopyText
+ | UIItemType::RightSidebarRemoteFileConnect
+ | UIItemType::RightSidebarRemoteFileRefresh
+ | UIItemType::RightSidebarRemoteFileRow(_)
+ | UIItemType::RightSidebarRemoteFileBack
+ | UIItemType::RightSidebarRemoteFileCopyText
| UIItemType::ContextMenuBackdrop
| UIItemType::ContextMenuItem(_)
| UIItemType::AboveScrollThumb
@@ -1010,6 +1084,11 @@ impl super::TermWindow {
| UIItemType::RightSidebarFileOpenMenu
| UIItemType::RightSidebarFileReveal
| UIItemType::RightSidebarFileCopyText
+ | UIItemType::RightSidebarRemoteFileConnect
+ | UIItemType::RightSidebarRemoteFileRefresh
+ | UIItemType::RightSidebarRemoteFileRow(_)
+ | UIItemType::RightSidebarRemoteFileBack
+ | UIItemType::RightSidebarRemoteFileCopyText
| UIItemType::ContextMenuBackdrop
| UIItemType::ContextMenuItem(_)
| UIItemType::AboveScrollThumb
@@ -1269,14 +1348,17 @@ impl super::TermWindow {
}
return;
}
- if completed_drag
- .as_ref()
- .is_some_and(|(item, _)| matches!(item.item_type, UIItemType::PaneNav { .. }))
- {
+ if completed_drag.as_ref().is_some_and(|(item, _)| {
+ matches!(item.item_type, UIItemType::PaneNav { .. })
+ }) {
// Release coordinates can differ from the last move
// event (coalesced/fast motion); recompute the drop
// target from where the button actually went up.
- if self.pane_tab_drag.as_ref().is_some_and(|state| state.active) {
+ if self
+ .pane_tab_drag
+ .as_ref()
+ .is_some_and(|state| state.active)
+ {
self.update_pane_tab_drag_target(&event);
}
if let Some(state) = self.pane_tab_drag.take() {
@@ -2038,8 +2120,7 @@ impl super::TermWindow {
let Ok(rect) = self.pane_frame_rect(&pos) else {
continue;
};
- if x < rect.min_x() || x >= rect.max_x() || y < rect.min_y() || y >= rect.max_y()
- {
+ if x < rect.min_x() || x >= rect.max_x() || y < rect.min_y() || y >= rect.max_y() {
continue;
}
// TmuxDomain cannot move existing panes; remote mux panes
@@ -2498,6 +2579,13 @@ impl super::TermWindow {
| UIItemType::RightSidebarFileCopyText => {
self.mouse_event_right_sidebar_file(item.clone(), event, context);
}
+ UIItemType::RightSidebarRemoteFileConnect
+ | UIItemType::RightSidebarRemoteFileRefresh
+ | UIItemType::RightSidebarRemoteFileRow(_)
+ | UIItemType::RightSidebarRemoteFileBack
+ | UIItemType::RightSidebarRemoteFileCopyText => {
+ self.mouse_event_right_sidebar_remote_file(item.clone(), event, context);
+ }
UIItemType::WorkspaceSidebarSettings => {
self.mouse_event_workspace_sidebar_settings(event, context);
}
@@ -2986,6 +3074,13 @@ impl super::TermWindow {
| UIItemType::RightSidebarFileCopyText => {
self.mouse_event_right_sidebar_file(item.clone(), event, context);
}
+ UIItemType::RightSidebarRemoteFileConnect
+ | UIItemType::RightSidebarRemoteFileRefresh
+ | UIItemType::RightSidebarRemoteFileRow(_)
+ | UIItemType::RightSidebarRemoteFileBack
+ | UIItemType::RightSidebarRemoteFileCopyText => {
+ self.mouse_event_right_sidebar_remote_file(item.clone(), event, context);
+ }
UIItemType::ContentViewClose(id) => {
context.set_cursor(Some(MouseCursor::Hand));
if event.kind == WMEK::Press(MousePress::Left) {
@@ -3251,7 +3346,9 @@ impl super::TermWindow {
self.dragging.replace((item, event));
context.invalidate();
}
- WMEK::Press(MousePress::Right) => {
+ WMEK::Press(MousePress::Right)
+ if self.right_sidebar_remote_files.selected.is_none() =>
+ {
self.show_right_sidebar_file_open_with_menu(context, event.coords);
}
_ => {}
@@ -3293,8 +3390,10 @@ impl super::TermWindow {
// (re)starts the periodic re-scan.
if self.right_sidebar_file_view_active() {
self.kick_right_sidebar_file_rescan_cycle();
+ self.request_right_sidebar_remote_files_connect(false);
} else {
self.schedule_right_sidebar_file_memory_release();
+ self.release_right_sidebar_remote_files_if_hidden();
}
self.invalidate_or_reflow_right_sidebar(previous_width, context);
}
@@ -3478,6 +3577,38 @@ impl super::TermWindow {
self.invalidate_or_reflow_right_sidebar(previous_width, context);
}
+ pub fn mouse_event_right_sidebar_remote_file(
+ &mut self,
+ item: UIItem,
+ event: MouseEvent,
+ context: &dyn WindowOps,
+ ) {
+ context.set_cursor(Some(MouseCursor::Hand));
+ if event.kind != WMEK::Press(MousePress::Left) {
+ return;
+ }
+ let previous_width = self.right_sidebar_width();
+ match item.item_type {
+ UIItemType::RightSidebarRemoteFileConnect => {
+ self.request_right_sidebar_remote_files_connect(true);
+ }
+ UIItemType::RightSidebarRemoteFileRefresh => {
+ self.refresh_right_sidebar_remote_files();
+ }
+ UIItemType::RightSidebarRemoteFileRow(path) => {
+ self.open_right_sidebar_remote_file(path);
+ }
+ UIItemType::RightSidebarRemoteFileBack => {
+ self.close_right_sidebar_remote_file_preview();
+ }
+ UIItemType::RightSidebarRemoteFileCopyText => {
+ self.copy_right_sidebar_selected_file_preview_text();
+ }
+ _ => {}
+ }
+ self.invalidate_or_reflow_right_sidebar(previous_width, context);
+ }
+
pub fn mouse_event_workspace_sidebar_settings(
&mut self,
event: MouseEvent,
@@ -3952,8 +4083,8 @@ impl super::TermWindow {
}
fn workspace_sidebar_view_options_menu_items(&mut self) -> Vec<ContextMenuItem> {
- use config::keyassignment::KeyAssignment;
use crate::workspace_threads::WorkspaceThreadWorkStatus;
+ use config::keyassignment::KeyAssignment;
self.begin_context_menu_application_actions();
let hidden = crate::native_settings::workspace_sidebar_hidden_statuses();
@@ -4117,6 +4248,14 @@ impl super::TermWindow {
else {
return false;
};
+ let space_has_client_domain =
+ crate::workspace_threads::client_domain_for_space(&state.space_id).is_some();
+ if !remote_thread_uses_ssh_connection_view(state.is_remote, space_has_client_domain) {
+ // A mux-domain Space already has its transport. Its threads are
+ // materialized directly through that ClientDomain and must never
+ // be sent through the disconnected SSH-host content view.
+ return false;
+ }
if !state.is_remote || (!force_disconnected && state.is_live) {
if !state.is_remote {
@@ -4668,7 +4807,11 @@ impl super::TermWindow {
let remote_host_id =
crate::workspace_threads::remote_host_id_for_project_id(&plan.project_id).to_string();
let remote_spec = crate::ssh_hosts::host_spec(&remote_host_id);
- if remote_spec.is_none() && crate::workspace_threads::project_is_remote(&plan.project_id) {
+ if missing_ssh_host_blocks_activation(
+ crate::workspace_threads::project_is_remote(&plan.project_id),
+ remote_spec.is_some(),
+ space_client_domain.is_some(),
+ ) {
log::warn!(
"refusing to connect remote thread {:?}: SSH host {:?} no longer exists",
plan.thread_id,
@@ -4987,6 +5130,8 @@ impl super::TermWindow {
}
let materialize_workspace = workspace_name;
+ let materialize_workspace_for_error = materialize_workspace.clone();
+ let materialize_window = self.window.clone();
promise::spawn::spawn(async move {
if let Err(err) = crate::workspace_threads::materialize_thread(
materialize_workspace,
@@ -5000,6 +5145,20 @@ impl super::TermWindow {
.await
{
log::error!("failed to materialize connecting SSH thread: {err:#}");
+ let message = format!("Unable to open the remote terminal: {err:#}");
+ if let Some(window) = materialize_window {
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ let is_current = term_window
+ .remote_connects
+ .get(&view_id)
+ .is_some_and(|state| state.generation == generation);
+ if !is_current {
+ return;
+ }
+ term_window.kill_remote_connect_workspace(&materialize_workspace_for_error);
+ term_window.fail_remote_connect(view_id, &message);
+ })));
+ }
}
})
.detach();
@@ -5040,9 +5199,15 @@ impl super::TermWindow {
.downcast_ref::<RemoteSshDomain>()
.map(|ssh| ssh.connection_status())
});
+ let workspace_has_window = !Mux::get()
+ .iter_windows_in_workspace(&workspace_name)
+ .is_empty();
+ let can_reveal = remote_connect_can_reveal(status.as_ref(), workspace_has_window);
match status {
- Some(SshConnectionStatus::Authenticating) | Some(SshConnectionStatus::Connected) => {
+ Some(SshConnectionStatus::Authenticating | SshConnectionStatus::Connected)
+ if can_reveal =>
+ {
self.reveal_remote_connect(view_id, generation);
}
Some(SshConnectionStatus::Failed(message)) => {
diff --git a/wezterm-gui/src/termwindow/onboarding.rs b/wezterm-gui/src/termwindow/onboarding.rs
index f2b0edc6..81bbadc1 100644
--- a/wezterm-gui/src/termwindow/onboarding.rs
+++ b/wezterm-gui/src/termwindow/onboarding.rs
@@ -203,6 +203,8 @@ impl PendingProject {
}
pub(crate) struct OnboardingView {
+ /// UI scale captured at paint time; mouse handlers get no `DrawContext`.
+ last_ui_scale: f32,
step: Step,
widgets: UiContext<OnboardingAction>,
interaction: InteractionState<OnboardingAction>,
@@ -237,6 +239,7 @@ impl OnboardingView {
show_left_sidebar: settings.onboarding.show_left_sidebar_by_default,
status: None,
transition: None,
+ last_ui_scale: 1.0,
}
}
@@ -314,7 +317,8 @@ impl OnboardingView {
match kind {
WMEK::VertWheel(amount) if self.step == Step::ReviewProjects => {
let old = self.review_scroll.offset;
- self.review_scroll.scroll_by(wheel_delta_pixels(amount));
+ self.review_scroll
+ .scroll_by(wheel_delta_pixels(amount, self.last_ui_scale));
if (self.review_scroll.offset - old).abs() > 0.01 {
ContentViewResponse::Redraw
} else {
@@ -615,6 +619,7 @@ impl OnboardingView {
_cursor_on: bool,
) -> anyhow::Result<()> {
self.widgets.clear();
+ self.last_ui_scale = ctx.scale();
let tokens = UiTokens::for_dpi(ctx.dimensions.dpi);
ctx.draw_rect(
layers,
@@ -1171,7 +1176,9 @@ impl OnboardingView {
area.size.width * 0.42,
)?;
- let track_w = (area.size.width * 0.46).min(ctx.px(520.0)).max(ctx.px(280.0));
+ let track_w = (area.size.width * 0.46)
+ .min(ctx.px(520.0))
+ .max(ctx.px(280.0));
let track_x = area.origin.x + area.size.width - track_w;
let center_y = area.origin.y + area.size.height / 2.0;
let segment_w = track_w / steps.len().max(1) as f32;
@@ -1713,7 +1720,8 @@ impl OnboardingView {
)?;
let text_w = ctx.measure_text_width(font, label);
let max_text_w = (area.size.width - 24.0).max(0.0);
- let x = area.origin.x + ((area.size.width - text_w.min(max_text_w)) / 2.0).max(ctx.px(12.0));
+ let x =
+ area.origin.x + ((area.size.width - text_w.min(max_text_w)) / 2.0).max(ctx.px(12.0));
ctx.draw_text(
layers,
font,
diff --git a/wezterm-gui/src/termwindow/remote_files.rs b/wezterm-gui/src/termwindow/remote_files.rs
new file mode 100644
index 00000000..f4135e0d
--- /dev/null
+++ b/wezterm-gui/src/termwindow/remote_files.rs
@@ -0,0 +1,1527 @@
+use crate::workspace_threads::{RemoteFilesSource, RemoteFilesTarget};
+use config::SshDomain;
+use smol::channel::Sender;
+use smol::io::AsyncReadExt;
+use std::collections::{HashMap, HashSet};
+use std::future::Future;
+use std::hash::{DefaultHasher, Hash, Hasher};
+use std::pin::Pin;
+use std::sync::{Arc, Mutex, OnceLock, Weak};
+use std::time::{Duration, Instant};
+use wezterm_ssh::{Session, SessionEvent, SftpChannelError, SftpError};
+
+pub(crate) const REMOTE_FILE_TREE_ROW_LIMIT: usize = 2_000;
+
+type RemoteFuture<T> = Pin<Box<dyn Future<Output = Result<T, String>> + Send + 'static>>;
+
+/// A remote Unix path. It never uses the host OS path implementation, so a
+/// Windows client cannot introduce `\` while joining SFTP paths.
+#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct RemotePath(String);
+
+impl RemotePath {
+ pub(crate) fn from_server_absolute(path: &str) -> Result<Self, String> {
+ if !path.starts_with('/') {
+ return Err(format!("SFTP returned a non-absolute path: {path}"));
+ }
+ if path.as_bytes().contains(&0) {
+ return Err("remote path contains NUL".to_string());
+ }
+ let normalized = if path.len() > 1 {
+ path.trim_end_matches('/').to_string()
+ } else {
+ "/".to_string()
+ };
+ Ok(Self(normalized))
+ }
+
+ pub(crate) fn as_str(&self) -> &str {
+ &self.0
+ }
+
+ pub(crate) fn file_name(&self) -> &str {
+ self.0.rsplit('/').next().unwrap_or(&self.0)
+ }
+
+ pub(crate) fn extension(&self) -> Option<&str> {
+ let name = self.file_name();
+ let (stem, extension) = name.rsplit_once('.')?;
+ (!stem.is_empty() && !extension.is_empty()).then_some(extension)
+ }
+
+ pub(crate) fn join_name(&self, name: &str) -> Result<Self, String> {
+ if name.is_empty()
+ || matches!(name, "." | "..")
+ || name.contains('/')
+ || name.as_bytes().contains(&0)
+ {
+ return Err(format!("invalid SFTP directory entry name: {name:?}"));
+ }
+ let joined = if self.0 == "/" {
+ format!("/{name}")
+ } else {
+ format!("{}/{name}", self.0)
+ };
+ Ok(Self(joined))
+ }
+
+ pub(crate) fn is_descendant_of(&self, parent: &Self) -> bool {
+ if parent.0 == "/" {
+ self.0.len() > 1 && self.0.starts_with('/')
+ } else {
+ self.0
+ .strip_prefix(&parent.0)
+ .is_some_and(|suffix| suffix.starts_with('/'))
+ }
+ }
+}
+
+fn resolve_requested_root(home: RemotePath, requested: &str) -> Result<RemotePath, String> {
+ if requested == "~" {
+ return Ok(home);
+ }
+ if let Some(suffix) = requested.strip_prefix("~/") {
+ let mut path = home;
+ for component in suffix.split('/') {
+ if component.is_empty() || component == "." {
+ continue;
+ }
+ path = path.join_name(component)?;
+ }
+ return Ok(path);
+ }
+ RemotePath::from_server_absolute(requested)
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum RemoteFileKind {
+ Directory,
+ File,
+ Symlink,
+ Other,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct RemoteFileEntry {
+ pub path: RemotePath,
+ pub name: String,
+ pub kind: RemoteFileKind,
+ pub size: Option<u64>,
+}
+
+impl RemoteFileEntry {
+ pub(crate) fn is_directory(&self) -> bool {
+ self.kind == RemoteFileKind::Directory
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct RemoteDirectoryListing {
+ pub entries: Vec<RemoteFileEntry>,
+ pub truncated: bool,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct RemoteFileBytes {
+ pub bytes: Vec<u8>,
+ pub truncated: bool,
+}
+
+pub(crate) trait RemoteFileBackend: Send + Sync {
+ fn resolve_root(&self, requested: String) -> RemoteFuture<RemotePath>;
+ fn list_directory(
+ &self,
+ path: RemotePath,
+ limit: usize,
+ ) -> RemoteFuture<RemoteDirectoryListing>;
+ fn read_file(&self, path: RemotePath, limit: usize) -> RemoteFuture<RemoteFileBytes>;
+}
+
+pub(crate) trait RemoteFileConnector: Send + Sync {
+ fn connect(&self, config: SshDomain) -> RemoteFuture<Arc<dyn RemoteFileBackend>>;
+}
+
+pub(crate) fn remote_connection_key(source_key: &str, config: &SshDomain) -> String {
+ let mut hasher = DefaultHasher::new();
+ source_key.hash(&mut hasher);
+ config.remote_address.hash(&mut hasher);
+ config.username.hash(&mut hasher);
+ config.no_agent_auth.hash(&mut hasher);
+ format!("{:?}", config.ssh_backend).hash(&mut hasher);
+ let mut options = config.ssh_option.iter().collect::<Vec<_>>();
+ options.sort_by(|a, b| a.0.cmp(b.0).then_with(|| a.1.cmp(b.1)));
+ options.hash(&mut hasher);
+ // Include credentials in the fingerprint without retaining or logging
+ // another copy of the secret.
+ config.stored_password.hash(&mut hasher);
+ format!("{source_key}:{:016x}", hasher.finish())
+}
+
+struct SftpRemoteFileBackend {
+ // Sftp only retains a request sender. Keep the Session handle alive for
+ // the lifetime of this independent file connection.
+ _session: Session,
+ sftp: wezterm_ssh::Sftp,
+}
+
+impl RemoteFileBackend for SftpRemoteFileBackend {
+ fn resolve_root(&self, requested: String) -> RemoteFuture<RemotePath> {
+ let sftp = self.sftp.clone();
+ Box::pin(async move {
+ let home = sftp
+ .canonicalize(".")
+ .await
+ .map_err(|err| format!("Unable to resolve remote home: {err}"))?;
+ let home = RemotePath::from_server_absolute(home.as_str())?;
+ resolve_requested_root(home, &requested)
+ })
+ }
+
+ fn list_directory(
+ &self,
+ path: RemotePath,
+ limit: usize,
+ ) -> RemoteFuture<RemoteDirectoryListing> {
+ let sftp = self.sftp.clone();
+ Box::pin(async move {
+ let dir = sftp
+ .open_dir(path.as_str().to_string())
+ .await
+ .map_err(|err| format!("Unable to open {}: {err}", path.as_str()))?;
+ let mut entries = Vec::with_capacity(limit.min(256));
+ let mut truncated = false;
+ loop {
+ // The raw API reports normal end-of-directory as an error.
+ // Preserve other errors so a dead shared connection can be
+ // invalidated rather than appearing as a partial directory.
+ let (raw_name, metadata) = match dir.read_dir().await {
+ Ok(entry) => entry,
+ Err(err) if is_sftp_directory_eof(&err) => break,
+ Err(err) => {
+ return Err(format!(
+ "Unable to read directory {}: {err:#}",
+ path.as_str()
+ ))
+ }
+ };
+ let name = raw_name.as_str();
+ if matches!(name, "." | "..") {
+ continue;
+ }
+ let Ok(entry_path) = path.join_name(name) else {
+ continue;
+ };
+ if entries.len() >= limit {
+ truncated = true;
+ break;
+ }
+ let kind = if metadata.is_dir() {
+ RemoteFileKind::Directory
+ } else if metadata.is_file() {
+ RemoteFileKind::File
+ } else if metadata.is_symlink() {
+ RemoteFileKind::Symlink
+ } else {
+ RemoteFileKind::Other
+ };
+ entries.push(RemoteFileEntry {
+ path: entry_path,
+ name: name.to_string(),
+ kind,
+ size: metadata.size,
+ });
+ }
+ entries.sort_by(|a, b| {
+ b.is_directory()
+ .cmp(&a.is_directory())
+ .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
+ .then_with(|| a.name.cmp(&b.name))
+ });
+ Ok(RemoteDirectoryListing { entries, truncated })
+ })
+ }
+
+ fn read_file(&self, path: RemotePath, limit: usize) -> RemoteFuture<RemoteFileBytes> {
+ let sftp = self.sftp.clone();
+ Box::pin(async move {
+ let file = sftp
+ .open(path.as_str().to_string())
+ .await
+ .map_err(|err| format!("Unable to open {}: {err}", path.as_str()))?;
+ let mut bytes = Vec::with_capacity(limit.saturating_add(1).min(256 * 1024));
+ let mut limited = file.take(limit.saturating_add(1) as u64);
+ limited
+ .read_to_end(&mut bytes)
+ .await
+ .map_err(|err| format!("Unable to read {}: {err}", path.as_str()))?;
+ let truncated = bytes.len() > limit;
+ if truncated {
+ bytes.truncate(limit);
+ }
+ Ok(RemoteFileBytes { bytes, truncated })
+ })
+ }
+}
+
+fn is_sftp_directory_eof(err: &anyhow::Error) -> bool {
+ err.chain().any(|cause| {
+ let channel_eof = match cause.downcast_ref::<SftpChannelError>() {
+ Some(SftpChannelError::Sftp(SftpError::Eof)) => true,
+ Some(SftpChannelError::FileIo(io)) => io.kind() == std::io::ErrorKind::UnexpectedEof,
+ _ => false,
+ };
+ channel_eof
+ || cause
+ .downcast_ref::<std::io::Error>()
+ .is_some_and(|io| io.kind() == std::io::ErrorKind::UnexpectedEof)
+ })
+}
+
+#[derive(Default)]
+pub(crate) struct SshRemoteFileConnector;
+
+impl RemoteFileConnector for SshRemoteFileConnector {
+ fn connect(&self, config: SshDomain) -> RemoteFuture<Arc<dyn RemoteFileBackend>> {
+ Box::pin(async move {
+ let ssh_config =
+ mux::ssh::ssh_domain_to_ssh_config(&config).map_err(|err| format!("{err:#}"))?;
+ let (session, events) = Session::connect(ssh_config)
+ .map_err(|err| format!("Unable to connect to SSH server: {err:#}"))?;
+ let mut password = config
+ .stored_password
+ .filter(|password| !password.is_empty());
+ while let Ok(event) = events.recv().await {
+ match event {
+ SessionEvent::Banner(_) => {}
+ SessionEvent::HostVerify(verify) => {
+ return Err(format!(
+ "SSH host verification requires interactive confirmation: {}",
+ verify.message
+ ));
+ }
+ SessionEvent::Authenticate(auth) => {
+ let mut answers = Vec::with_capacity(auth.prompts.len());
+ for prompt in &auth.prompts {
+ if prompt.echo {
+ return Err(
+ "SSH authentication requires an interactive prompt".to_string()
+ );
+ }
+ let Some(stored) = password.take() else {
+ return Err(
+ "SSH authentication requires a saved password".to_string()
+ );
+ };
+ answers.push(stored);
+ }
+ auth.answer(answers).await.map_err(|err| {
+ format!("Unable to answer SSH authentication prompt: {err:#}")
+ })?;
+ }
+ SessionEvent::HostVerificationFailed(failed) => {
+ return Err(format!("SSH host verification failed: {failed}"));
+ }
+ SessionEvent::Error(err) => return Err(format!("SSH error: {err}")),
+ SessionEvent::Authenticated => {
+ let backend: Arc<dyn RemoteFileBackend> = Arc::new(SftpRemoteFileBackend {
+ sftp: session.sftp(),
+ _session: session,
+ });
+ return Ok(backend);
+ }
+ }
+ }
+ Err("SSH authentication did not complete".to_string())
+ })
+ }
+}
+
+enum ManagedConnection {
+ Connecting {
+ waiters: Vec<Sender<Result<(), String>>>,
+ },
+ Ready {
+ connection_id: u64,
+ backend: Arc<dyn RemoteFileBackend>,
+ leases: usize,
+ idle_generation: u64,
+ idle_since: Option<Instant>,
+ },
+}
+
+struct RemoteConnectionManagerInner {
+ entries: HashMap<String, ManagedConnection>,
+ idle_timeout: Duration,
+ next_connection_id: u64,
+}
+
+pub(crate) struct RemoteConnectionManager {
+ connector: Arc<dyn RemoteFileConnector>,
+ inner: Mutex<RemoteConnectionManagerInner>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) enum RemoteAcquireError {
+ NotConnected,
+ Failed(String),
+}
+
+pub(crate) struct RemoteConnectionLease {
+ key: String,
+ backend: Arc<dyn RemoteFileBackend>,
+ manager: Weak<RemoteConnectionManager>,
+ connection_id: u64,
+}
+
+impl RemoteConnectionLease {
+ pub(crate) fn backend(&self) -> Arc<dyn RemoteFileBackend> {
+ Arc::clone(&self.backend)
+ }
+
+ pub(crate) fn connection_key(&self) -> &str {
+ &self.key
+ }
+
+ pub(crate) fn operation_lease(&self) -> Option<RemoteConnectionLease> {
+ self.manager
+ .upgrade()
+ .and_then(|manager| manager.retain(&self.key, self.connection_id))
+ }
+}
+
+impl Drop for RemoteConnectionLease {
+ fn drop(&mut self) {
+ if let Some(manager) = self.manager.upgrade() {
+ manager.release(&self.key, self.connection_id);
+ }
+ }
+}
+
+impl RemoteConnectionManager {
+ fn new(
+ connector: Arc<dyn RemoteFileConnector>,
+ idle_timeout: Duration,
+ ) -> Arc<RemoteConnectionManager> {
+ Arc::new(Self {
+ connector,
+ inner: Mutex::new(RemoteConnectionManagerInner {
+ entries: HashMap::new(),
+ idle_timeout,
+ next_connection_id: 0,
+ }),
+ })
+ }
+
+ pub(crate) async fn acquire(
+ self: &Arc<Self>,
+ key: String,
+ config: SshDomain,
+ allow_connect: bool,
+ ) -> Result<RemoteConnectionLease, RemoteAcquireError> {
+ loop {
+ let waiter = {
+ let mut inner = self.inner.lock().unwrap();
+ match inner.entries.get_mut(&key) {
+ Some(ManagedConnection::Ready {
+ connection_id,
+ backend,
+ leases,
+ idle_generation,
+ idle_since,
+ }) => {
+ *leases = leases.saturating_add(1);
+ *idle_generation = idle_generation.wrapping_add(1);
+ *idle_since = None;
+ return Ok(RemoteConnectionLease {
+ key,
+ backend: Arc::clone(backend),
+ manager: Arc::downgrade(self),
+ connection_id: *connection_id,
+ });
+ }
+ Some(ManagedConnection::Connecting { waiters }) => {
+ let (tx, rx) = smol::channel::bounded(1);
+ waiters.push(tx);
+ Some(rx)
+ }
+ None if !allow_connect => return Err(RemoteAcquireError::NotConnected),
+ None => {
+ inner.entries.insert(
+ key.clone(),
+ ManagedConnection::Connecting { waiters: vec![] },
+ );
+ None
+ }
+ }
+ };
+
+ if let Some(waiter) = waiter {
+ match waiter.recv().await {
+ Ok(Ok(())) => continue,
+ Ok(Err(err)) => return Err(RemoteAcquireError::Failed(err)),
+ Err(_) => {
+ return Err(RemoteAcquireError::Failed(
+ "Remote Files connection was canceled".to_string(),
+ ))
+ }
+ }
+ }
+
+ let result = self.connector.connect(config.clone()).await;
+ let waiters = {
+ let mut inner = self.inner.lock().unwrap();
+ let waiters = match inner.entries.remove(&key) {
+ Some(ManagedConnection::Connecting { waiters }) => waiters,
+ _ => Vec::new(),
+ };
+ if let Ok(backend) = &result {
+ inner.next_connection_id = inner.next_connection_id.wrapping_add(1).max(1);
+ let connection_id = inner.next_connection_id;
+ inner.entries.insert(
+ key.clone(),
+ ManagedConnection::Ready {
+ connection_id,
+ backend: Arc::clone(backend),
+ leases: 0,
+ idle_generation: 0,
+ idle_since: None,
+ },
+ );
+ }
+ waiters
+ };
+ let wake = result.as_ref().map(|_| ()).map_err(Clone::clone);
+ for waiter in waiters {
+ let _ = waiter.try_send(wake.clone());
+ }
+ match result {
+ Ok(_) => continue,
+ Err(err) => return Err(RemoteAcquireError::Failed(err)),
+ }
+ }
+ }
+
+ fn retain(
+ self: &Arc<Self>,
+ key: &str,
+ expected_connection_id: u64,
+ ) -> Option<RemoteConnectionLease> {
+ let mut inner = self.inner.lock().unwrap();
+ let ManagedConnection::Ready {
+ connection_id,
+ backend,
+ leases,
+ idle_generation,
+ idle_since,
+ } = inner.entries.get_mut(key)?
+ else {
+ return None;
+ };
+ if *connection_id != expected_connection_id {
+ return None;
+ }
+ *leases = leases.saturating_add(1);
+ *idle_generation = idle_generation.wrapping_add(1);
+ *idle_since = None;
+ Some(RemoteConnectionLease {
+ key: key.to_string(),
+ backend: Arc::clone(backend),
+ manager: Arc::downgrade(self),
+ connection_id: *connection_id,
+ })
+ }
+
+ fn release(self: &Arc<Self>, key: &str, connection_id: u64) {
+ let Some((generation, timeout)) = self.release_state(key, connection_id, Instant::now())
+ else {
+ return;
+ };
+ self.schedule_expiry(key.to_string(), connection_id, generation, timeout);
+ }
+
+ fn release_state(
+ &self,
+ key: &str,
+ expected_connection_id: u64,
+ now: Instant,
+ ) -> Option<(u64, Duration)> {
+ {
+ let mut inner = self.inner.lock().unwrap();
+ let timeout = inner.idle_timeout;
+ let Some(ManagedConnection::Ready {
+ connection_id,
+ leases,
+ idle_generation,
+ idle_since,
+ ..
+ }) = inner.entries.get_mut(key)
+ else {
+ return None;
+ };
+ if *connection_id != expected_connection_id {
+ return None;
+ }
+ *leases = leases.saturating_sub(1);
+ if *leases != 0 {
+ return None;
+ }
+ *idle_generation = idle_generation.wrapping_add(1);
+ *idle_since = Some(now);
+ Some((*idle_generation, timeout))
+ }
+ }
+
+ fn schedule_expiry(
+ self: &Arc<Self>,
+ key: String,
+ connection_id: u64,
+ generation: u64,
+ timeout: Duration,
+ ) {
+ let manager = Arc::clone(self);
+ smol::spawn(async move {
+ smol::Timer::after(timeout).await;
+ manager.expire_if_idle(&key, connection_id, generation, Instant::now());
+ })
+ .detach();
+ }
+
+ fn expire_if_idle(
+ &self,
+ key: &str,
+ expected_connection_id: u64,
+ generation: u64,
+ now: Instant,
+ ) -> bool {
+ let mut inner = self.inner.lock().unwrap();
+ let timeout = inner.idle_timeout;
+ let should_remove = matches!(
+ inner.entries.get(key),
+ Some(ManagedConnection::Ready {
+ connection_id,
+ leases: 0,
+ idle_generation,
+ idle_since: Some(idle_since),
+ ..
+ }) if *connection_id == expected_connection_id
+ && *idle_generation == generation
+ && now.saturating_duration_since(*idle_since) >= timeout
+ );
+ if should_remove {
+ inner.entries.remove(key);
+ }
+ should_remove
+ }
+
+ pub(crate) fn set_idle_timeout(self: &Arc<Self>, timeout: Duration) {
+ let now = Instant::now();
+ let idle_entries = {
+ let mut inner = self.inner.lock().unwrap();
+ inner.idle_timeout = timeout;
+ inner
+ .entries
+ .iter_mut()
+ .filter_map(|(key, entry)| match entry {
+ ManagedConnection::Ready {
+ connection_id,
+ leases: 0,
+ idle_generation,
+ idle_since,
+ ..
+ } => {
+ *idle_generation = idle_generation.wrapping_add(1);
+ let since = *idle_since.get_or_insert(now);
+ let remaining =
+ timeout.saturating_sub(now.saturating_duration_since(since));
+ Some((key.clone(), *connection_id, *idle_generation, remaining))
+ }
+ _ => None,
+ })
+ .collect::<Vec<_>>()
+ };
+ for (key, connection_id, generation, remaining) in idle_entries {
+ self.schedule_expiry(key, connection_id, generation, remaining);
+ }
+ }
+
+ pub(crate) fn invalidate(&self, key: &str) {
+ self.inner.lock().unwrap().entries.remove(key);
+ }
+}
+
+pub(crate) fn remote_connection_manager() -> Arc<RemoteConnectionManager> {
+ static MANAGER: OnceLock<Arc<RemoteConnectionManager>> = OnceLock::new();
+ Arc::clone(MANAGER.get_or_init(|| {
+ RemoteConnectionManager::new(
+ Arc::new(SshRemoteFileConnector),
+ Duration::from_secs(crate::native_settings::remote_sftp_idle_minutes() as u64 * 60),
+ )
+ }))
+}
+
+pub(crate) fn update_remote_connection_idle_timeout(minutes: u32) {
+ remote_connection_manager().set_idle_timeout(Duration::from_secs(minutes as u64 * 60));
+}
+
+pub(crate) fn invalidate_remote_connection_if_dead(key: &str, message: &str) -> bool {
+ let lower = message.to_ascii_lowercase();
+ let dead = lower.contains("session is dead")
+ || lower.contains("channel is closed")
+ || lower.contains("channel closed")
+ || lower.contains("sending on a closed")
+ || lower.contains("no connection has been set up")
+ || lower.contains("connection, but we lost it")
+ || lower.contains("failed to send request")
+ || lower.contains("failed to receive response")
+ || lower.contains("broken pipe");
+ if dead {
+ remote_connection_manager().invalidate(key);
+ }
+ dead
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum RemoteFilesPhase {
+ Disconnected,
+ Connecting,
+ Connected,
+ Failed(String),
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct RemoteDirectory {
+ listing: RemoteDirectoryListing,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct RemoteFileRow {
+ pub entry: RemoteFileEntry,
+ pub depth: usize,
+ pub expanded: bool,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum RemotePreviewStatus {
+ None,
+ Loading(RemotePath),
+ Ready(RemotePath),
+ Failed(RemotePath, String),
+}
+
+#[derive(Clone, Debug)]
+pub(crate) struct RemoteFilesState {
+ pub target: Option<RemoteFilesTarget>,
+ pub phase: RemoteFilesPhase,
+ pub root: Option<RemotePath>,
+ directories: HashMap<RemotePath, RemoteDirectory>,
+ pub expanded: HashSet<RemotePath>,
+ loading_directories: HashSet<RemotePath>,
+ pub selected: Option<RemotePath>,
+ pub preview: RemotePreviewStatus,
+ pub error_message: Option<String>,
+ pub generation: u64,
+ authorized_sources: HashSet<String>,
+}
+
+impl Default for RemoteFilesState {
+ fn default() -> Self {
+ Self {
+ target: None,
+ phase: RemoteFilesPhase::Disconnected,
+ root: None,
+ directories: HashMap::new(),
+ expanded: HashSet::new(),
+ loading_directories: HashSet::new(),
+ selected: None,
+ preview: RemotePreviewStatus::None,
+ error_message: None,
+ generation: 0,
+ authorized_sources: HashSet::new(),
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum RemoteFilesEffect {
+ Connect {
+ generation: u64,
+ target: RemoteFilesTarget,
+ allow_connect: bool,
+ },
+ ListDirectory {
+ generation: u64,
+ source_key: String,
+ path: RemotePath,
+ limit: usize,
+ },
+ LoadPreview {
+ generation: u64,
+ source_key: String,
+ path: RemotePath,
+ },
+ ReleaseLease,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum RemoteFilesEvent {
+ TargetChanged(Option<RemoteFilesTarget>),
+ ConnectRequested,
+ ResumeRequested,
+ Connected {
+ generation: u64,
+ root: RemotePath,
+ listing: RemoteDirectoryListing,
+ },
+ ConnectionFailed {
+ generation: u64,
+ message: String,
+ },
+ ResumeUnavailable {
+ generation: u64,
+ },
+ ToggleDirectory(RemotePath),
+ DirectoryLoaded {
+ generation: u64,
+ path: RemotePath,
+ listing: RemoteDirectoryListing,
+ },
+ DirectoryFailed {
+ generation: u64,
+ path: RemotePath,
+ message: String,
+ },
+ SelectFile(RemotePath),
+ PreviewFinished {
+ generation: u64,
+ path: RemotePath,
+ error: Option<String>,
+ },
+ ClosePreview,
+ Refresh,
+ PanelHidden,
+}
+
+impl RemoteFilesState {
+ pub(crate) fn source_key(source: &RemoteFilesSource) -> String {
+ match source {
+ RemoteFilesSource::SshHost(host) => format!("ssh-host:{host}"),
+ RemoteFilesSource::ClientDomain(domain) => format!("client-domain:{domain}"),
+ }
+ }
+
+ pub(crate) fn current_source_key(&self) -> Option<String> {
+ self.target
+ .as_ref()
+ .map(|target| Self::source_key(&target.source))
+ }
+
+ pub(crate) fn can_resume_current(&self) -> bool {
+ self.current_source_key()
+ .is_some_and(|key| self.authorized_sources.contains(&key))
+ }
+
+ pub(crate) fn transition(&mut self, event: RemoteFilesEvent) -> Vec<RemoteFilesEffect> {
+ match event {
+ RemoteFilesEvent::TargetChanged(target) => {
+ if self.target == target {
+ return Vec::new();
+ }
+ self.clear_loaded_data();
+ self.target = target;
+ vec![RemoteFilesEffect::ReleaseLease]
+ }
+ RemoteFilesEvent::ConnectRequested => self.begin_connect(true),
+ RemoteFilesEvent::ResumeRequested => self.begin_connect(false),
+ RemoteFilesEvent::Connected {
+ generation,
+ root,
+ mut listing,
+ } => {
+ if generation != self.generation || self.target.is_none() {
+ return vec![RemoteFilesEffect::ReleaseLease];
+ }
+ if let Some(key) = self.current_source_key() {
+ self.authorized_sources.insert(key);
+ }
+ self.phase = RemoteFilesPhase::Connected;
+ self.error_message = None;
+ self.root = Some(root.clone());
+ self.expanded.insert(root.clone());
+ if listing.entries.len() > REMOTE_FILE_TREE_ROW_LIMIT {
+ listing.entries.truncate(REMOTE_FILE_TREE_ROW_LIMIT);
+ listing.truncated = true;
+ }
+ self.directories.insert(root, RemoteDirectory { listing });
+ Vec::new()
+ }
+ RemoteFilesEvent::ConnectionFailed {
+ generation,
+ message,
+ } => {
+ if generation == self.generation {
+ self.phase = RemoteFilesPhase::Failed(message);
+ self.error_message = None;
+ self.root = None;
+ self.directories.clear();
+ self.expanded.clear();
+ self.loading_directories.clear();
+ self.selected = None;
+ self.preview = RemotePreviewStatus::None;
+ }
+ Vec::new()
+ }
+ RemoteFilesEvent::ResumeUnavailable { generation } => {
+ if generation == self.generation {
+ self.phase = RemoteFilesPhase::Disconnected;
+ self.error_message = None;
+ }
+ Vec::new()
+ }
+ RemoteFilesEvent::ToggleDirectory(path) => {
+ if !matches!(self.phase, RemoteFilesPhase::Connected) {
+ return Vec::new();
+ }
+ if self.expanded.remove(&path) {
+ self.remove_descendants(&path);
+ return Vec::new();
+ }
+ self.expanded.insert(path.clone());
+ if self.directories.contains_key(&path)
+ || !self.loading_directories.insert(path.clone())
+ {
+ return Vec::new();
+ }
+ self.list_directory_effect(path)
+ }
+ RemoteFilesEvent::DirectoryLoaded {
+ generation,
+ path,
+ mut listing,
+ } => {
+ if generation != self.generation || !self.expanded.contains(&path) {
+ return Vec::new();
+ }
+ self.loading_directories.remove(&path);
+ self.error_message = None;
+ let retained_without_current = self.total_entries().saturating_sub(
+ self.directories
+ .get(&path)
+ .map_or(0, |directory| directory.listing.entries.len()),
+ );
+ let remaining = REMOTE_FILE_TREE_ROW_LIMIT.saturating_sub(retained_without_current);
+ if listing.entries.len() > remaining {
+ listing.entries.truncate(remaining);
+ listing.truncated = true;
+ }
+ self.directories.insert(path, RemoteDirectory { listing });
+ Vec::new()
+ }
+ RemoteFilesEvent::DirectoryFailed {
+ generation,
+ path,
+ message,
+ } => {
+ if generation == self.generation {
+ self.loading_directories.remove(&path);
+ self.error_message = Some(message);
+ }
+ Vec::new()
+ }
+ RemoteFilesEvent::SelectFile(path) => {
+ self.selected = Some(path.clone());
+ self.preview = RemotePreviewStatus::Loading(path.clone());
+ let Some(source_key) = self.current_source_key() else {
+ return Vec::new();
+ };
+ vec![RemoteFilesEffect::LoadPreview {
+ generation: self.generation,
+ source_key,
+ path,
+ }]
+ }
+ RemoteFilesEvent::PreviewFinished {
+ generation,
+ path,
+ error,
+ } => {
+ if generation != self.generation || self.selected.as_ref() != Some(&path) {
+ return Vec::new();
+ }
+ self.preview = match error {
+ Some(error) => RemotePreviewStatus::Failed(path, error),
+ None => RemotePreviewStatus::Ready(path),
+ };
+ Vec::new()
+ }
+ RemoteFilesEvent::ClosePreview => {
+ self.selected = None;
+ self.preview = RemotePreviewStatus::None;
+ Vec::new()
+ }
+ RemoteFilesEvent::Refresh => {
+ let Some(root) = self.root.clone() else {
+ return Vec::new();
+ };
+ self.generation = self.generation.wrapping_add(1);
+ self.directories.clear();
+ self.error_message = None;
+ self.expanded.clear();
+ self.expanded.insert(root.clone());
+ self.loading_directories.clear();
+ self.loading_directories.insert(root.clone());
+ self.selected = None;
+ self.preview = RemotePreviewStatus::None;
+ self.list_directory_effect(root)
+ }
+ RemoteFilesEvent::PanelHidden => {
+ self.clear_loaded_data();
+ vec![RemoteFilesEffect::ReleaseLease]
+ }
+ }
+ }
+
+ fn begin_connect(&mut self, allow_connect: bool) -> Vec<RemoteFilesEffect> {
+ let Some(target) = self.target.clone() else {
+ return Vec::new();
+ };
+ let source_key = Self::source_key(&target.source);
+ if !allow_connect && !self.authorized_sources.contains(&source_key) {
+ return Vec::new();
+ }
+ if matches!(
+ self.phase,
+ RemoteFilesPhase::Connecting | RemoteFilesPhase::Connected
+ ) {
+ return Vec::new();
+ }
+ self.generation = self.generation.wrapping_add(1);
+ self.phase = RemoteFilesPhase::Connecting;
+ vec![RemoteFilesEffect::Connect {
+ generation: self.generation,
+ target,
+ allow_connect,
+ }]
+ }
+
+ fn list_directory_effect(&self, path: RemotePath) -> Vec<RemoteFilesEffect> {
+ let Some(source_key) = self.current_source_key() else {
+ return Vec::new();
+ };
+ let remaining = REMOTE_FILE_TREE_ROW_LIMIT.saturating_sub(self.total_entries());
+ vec![RemoteFilesEffect::ListDirectory {
+ generation: self.generation,
+ source_key,
+ path,
+ limit: remaining,
+ }]
+ }
+
+ fn total_entries(&self) -> usize {
+ self.directories
+ .values()
+ .map(|directory| directory.listing.entries.len())
+ .sum()
+ }
+
+ fn remove_descendants(&mut self, path: &RemotePath) {
+ self.expanded
+ .retain(|candidate| !candidate.is_descendant_of(path));
+ self.loading_directories
+ .retain(|candidate| candidate != path && !candidate.is_descendant_of(path));
+ self.directories
+ .retain(|candidate, _| candidate != path && !candidate.is_descendant_of(path));
+ if self
+ .selected
+ .as_ref()
+ .is_some_and(|selected| selected.is_descendant_of(path))
+ {
+ self.selected = None;
+ self.preview = RemotePreviewStatus::None;
+ }
+ }
+
+ fn clear_loaded_data(&mut self) {
+ self.generation = self.generation.wrapping_add(1);
+ self.phase = RemoteFilesPhase::Disconnected;
+ self.root = None;
+ self.directories.clear();
+ self.expanded.clear();
+ self.loading_directories.clear();
+ self.selected = None;
+ self.preview = RemotePreviewStatus::None;
+ self.error_message = None;
+ }
+
+ pub(crate) fn rows(&self) -> Vec<RemoteFileRow> {
+ let Some(root) = self.root.as_ref() else {
+ return Vec::new();
+ };
+ let root_name = self
+ .target
+ .as_ref()
+ .map(|target| target.project_name.clone())
+ .unwrap_or_else(|| root.file_name().to_string());
+ let mut rows = vec![RemoteFileRow {
+ entry: RemoteFileEntry {
+ path: root.clone(),
+ name: root_name,
+ kind: RemoteFileKind::Directory,
+ size: None,
+ },
+ depth: 0,
+ expanded: self.expanded.contains(root),
+ }];
+ self.append_rows(root, 1, &mut rows);
+ rows
+ }
+
+ fn append_rows(&self, parent: &RemotePath, depth: usize, rows: &mut Vec<RemoteFileRow>) {
+ if !self.expanded.contains(parent) {
+ return;
+ }
+ let Some(directory) = self.directories.get(parent) else {
+ return;
+ };
+ for entry in &directory.listing.entries {
+ let expanded = entry.is_directory() && self.expanded.contains(&entry.path);
+ rows.push(RemoteFileRow {
+ entry: entry.clone(),
+ depth,
+ expanded,
+ });
+ if entry.is_directory() {
+ self.append_rows(&entry.path, depth.saturating_add(1), rows);
+ }
+ }
+ }
+
+ pub(crate) fn has_truncated_directory(&self) -> bool {
+ self.directories
+ .values()
+ .any(|directory| directory.listing.truncated)
+ }
+
+ pub(crate) fn kind_for_path(&self, path: &RemotePath) -> Option<RemoteFileKind> {
+ if self.root.as_ref() == Some(path) {
+ return Some(RemoteFileKind::Directory);
+ }
+ self.directories
+ .values()
+ .flat_map(|directory| directory.listing.entries.iter())
+ .find(|entry| &entry.path == path)
+ .map(|entry| entry.kind)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ fn target(source: &str) -> RemoteFilesTarget {
+ RemoteFilesTarget {
+ project_id: "project".to_string(),
+ project_name: "Project".to_string(),
+ source: RemoteFilesSource::ClientDomain(source.to_string()),
+ requested_root: "~".to_string(),
+ }
+ }
+
+ fn listing(parent: &RemotePath, names: &[(&str, RemoteFileKind)]) -> RemoteDirectoryListing {
+ RemoteDirectoryListing {
+ entries: names
+ .iter()
+ .map(|(name, kind)| RemoteFileEntry {
+ path: parent.join_name(name).unwrap(),
+ name: (*name).to_string(),
+ kind: *kind,
+ size: None,
+ })
+ .collect(),
+ truncated: false,
+ }
+ }
+
+ struct FakeBackend;
+
+ impl RemoteFileBackend for FakeBackend {
+ fn resolve_root(&self, _requested: String) -> RemoteFuture<RemotePath> {
+ Box::pin(async { RemotePath::from_server_absolute("/home/test") })
+ }
+
+ fn list_directory(
+ &self,
+ _path: RemotePath,
+ _limit: usize,
+ ) -> RemoteFuture<RemoteDirectoryListing> {
+ Box::pin(async {
+ Ok(RemoteDirectoryListing {
+ entries: Vec::new(),
+ truncated: false,
+ })
+ })
+ }
+
+ fn read_file(&self, _path: RemotePath, _limit: usize) -> RemoteFuture<RemoteFileBytes> {
+ Box::pin(async {
+ Ok(RemoteFileBytes {
+ bytes: Vec::new(),
+ truncated: false,
+ })
+ })
+ }
+ }
+
+ struct FakeConnector {
+ calls: Arc<AtomicUsize>,
+ }
+
+ impl RemoteFileConnector for FakeConnector {
+ fn connect(&self, _config: SshDomain) -> RemoteFuture<Arc<dyn RemoteFileBackend>> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ Box::pin(async { Ok(Arc::new(FakeBackend) as Arc<dyn RemoteFileBackend>) })
+ }
+ }
+
+ #[test]
+ fn remote_path_is_slash_only_and_treats_backslash_as_a_filename_character() {
+ let root = RemotePath::from_server_absolute("/root/app/").unwrap();
+ assert_eq!(root.as_str(), "/root/app");
+ assert_eq!(
+ RemotePath::from_server_absolute("/root/app ")
+ .unwrap()
+ .as_str(),
+ "/root/app "
+ );
+ assert_eq!(root.join_name("src").unwrap().as_str(), "/root/app/src");
+ assert_eq!(
+ root.join_name(r"odd\\name").unwrap().as_str(),
+ r"/root/app/odd\\name"
+ );
+ assert!(root.join_name("../escape").is_err());
+ assert!(root.join_name("a/b").is_err());
+ }
+
+ #[test]
+ fn tilde_is_resolved_from_canonical_dot_home() {
+ let home = RemotePath::from_server_absolute("/home/alice").unwrap();
+ assert_eq!(resolve_requested_root(home.clone(), "~").unwrap(), home);
+ assert_eq!(
+ resolve_requested_root(home, "~/src/app").unwrap().as_str(),
+ "/home/alice/src/app"
+ );
+ assert!(resolve_requested_root(
+ RemotePath::from_server_absolute("/home/alice").unwrap(),
+ "~/../etc"
+ )
+ .is_err());
+ }
+
+ #[test]
+ fn raw_directory_reader_only_treats_real_eof_as_completion() {
+ let protocol_eof = anyhow::Error::new(SftpChannelError::Sftp(SftpError::Eof));
+ assert!(is_sftp_directory_eof(&protocol_eof));
+ let io_eof = anyhow::Error::new(SftpChannelError::FileIo(std::io::Error::new(
+ std::io::ErrorKind::UnexpectedEof,
+ "no more files",
+ )));
+ assert!(is_sftp_directory_eof(&io_eof));
+ let lost = anyhow::Error::new(SftpChannelError::Sftp(SftpError::ConnectionLost));
+ assert!(!is_sftp_directory_eof(&lost));
+ }
+
+ #[test]
+ fn manager_single_flights_and_expires_only_after_last_lease() {
+ let calls = Arc::new(AtomicUsize::new(0));
+ let manager = RemoteConnectionManager::new(
+ Arc::new(FakeConnector {
+ calls: Arc::clone(&calls),
+ }),
+ Duration::from_secs(30),
+ );
+ let (first, second) = smol::block_on(async {
+ futures::future::join(
+ manager.acquire("source".to_string(), SshDomain::default(), true),
+ manager.acquire("source".to_string(), SshDomain::default(), true),
+ )
+ .await
+ });
+ let mut first = first.unwrap();
+ let mut second = second.unwrap();
+ let connection_id = first.connection_id;
+ assert_eq!(second.connection_id, connection_id);
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+ first.manager = Weak::new();
+ second.manager = Weak::new();
+ let idle_since = Instant::now();
+ assert!(manager
+ .release_state("source", connection_id, idle_since)
+ .is_none());
+ drop(first);
+ {
+ let inner = manager.inner.lock().unwrap();
+ assert!(matches!(
+ inner.entries.get("source"),
+ Some(ManagedConnection::Ready { leases: 1, .. })
+ ));
+ }
+ let (generation, _) = manager
+ .release_state("source", connection_id, idle_since)
+ .expect("last lease starts idle timer");
+ drop(second);
+ let stored_idle_since = {
+ let inner = manager.inner.lock().unwrap();
+ match inner.entries.get("source") {
+ Some(ManagedConnection::Ready {
+ leases: 0,
+ idle_generation,
+ idle_since: Some(idle_since),
+ ..
+ }) => {
+ assert_eq!(*idle_generation, generation);
+ *idle_since
+ }
+ _ => panic!("expected idle connection"),
+ }
+ };
+ assert!(!manager.expire_if_idle(
+ "source",
+ connection_id,
+ generation,
+ stored_idle_since + Duration::from_secs(29)
+ ));
+ assert!(manager.expire_if_idle(
+ "source",
+ connection_id,
+ generation,
+ stored_idle_since + Duration::from_secs(30)
+ ));
+ }
+
+ #[test]
+ fn stale_lease_cannot_release_a_replacement_connection() {
+ let calls = Arc::new(AtomicUsize::new(0));
+ let manager = RemoteConnectionManager::new(
+ Arc::new(FakeConnector {
+ calls: Arc::clone(&calls),
+ }),
+ Duration::from_secs(30),
+ );
+ let old = smol::block_on(manager.acquire("source".to_string(), SshDomain::default(), true))
+ .unwrap();
+ let old_id = old.connection_id;
+ manager.invalidate("source");
+ let replacement =
+ smol::block_on(manager.acquire("source".to_string(), SshDomain::default(), true))
+ .unwrap();
+ assert_ne!(old_id, replacement.connection_id);
+ drop(old);
+ let inner = manager.inner.lock().unwrap();
+ assert!(matches!(
+ inner.entries.get("source"),
+ Some(ManagedConnection::Ready { leases: 1, .. })
+ ));
+ assert_eq!(calls.load(Ordering::SeqCst), 2);
+ }
+
+ #[test]
+ fn connection_key_changes_with_endpoint_options_and_credentials() {
+ let mut first = SshDomain::default();
+ first.remote_address = "host:22".to_string();
+ first.username = Some("alice".to_string());
+ let base = remote_connection_key("source", &first);
+
+ let mut changed_host = first.clone();
+ changed_host.remote_address = "other:22".to_string();
+ assert_ne!(base, remote_connection_key("source", &changed_host));
+
+ let mut changed_option = first.clone();
+ changed_option
+ .ssh_option
+ .insert("proxycommand".to_string(), "ssh jump".to_string());
+ assert_ne!(base, remote_connection_key("source", &changed_option));
+
+ let mut changed_password = first;
+ changed_password.stored_password = Some("secret".to_string());
+ assert_ne!(base, remote_connection_key("source", &changed_password));
+ }
+
+ #[test]
+ fn no_click_never_connects_and_resume_requires_prior_success() {
+ let mut state = RemoteFilesState::default();
+ assert_eq!(
+ state.transition(RemoteFilesEvent::TargetChanged(Some(target("mux")))),
+ vec![RemoteFilesEffect::ReleaseLease]
+ );
+ assert!(state
+ .transition(RemoteFilesEvent::ResumeRequested)
+ .is_empty());
+ assert_eq!(state.phase, RemoteFilesPhase::Disconnected);
+ assert!(matches!(
+ state
+ .transition(RemoteFilesEvent::ConnectRequested)
+ .as_slice(),
+ [RemoteFilesEffect::Connect {
+ allow_connect: true,
+ ..
+ }]
+ ));
+ }
+
+ #[test]
+ fn successful_connection_authorizes_only_that_window_state() {
+ let root = RemotePath::from_server_absolute("/home/me").unwrap();
+ let mut first = RemoteFilesState::default();
+ first.transition(RemoteFilesEvent::TargetChanged(Some(target("mux"))));
+ let effect = first.transition(RemoteFilesEvent::ConnectRequested);
+ let generation = match effect[0] {
+ RemoteFilesEffect::Connect { generation, .. } => generation,
+ _ => unreachable!(),
+ };
+ first.transition(RemoteFilesEvent::Connected {
+ generation,
+ root: root.clone(),
+ listing: listing(&root, &[]),
+ });
+ first.transition(RemoteFilesEvent::PanelHidden);
+ assert!(matches!(
+ first
+ .transition(RemoteFilesEvent::ResumeRequested)
+ .as_slice(),
+ [RemoteFilesEffect::Connect {
+ allow_connect: false,
+ ..
+ }]
+ ));
+
+ let mut second = RemoteFilesState::default();
+ second.transition(RemoteFilesEvent::TargetChanged(Some(target("mux"))));
+ assert!(second
+ .transition(RemoteFilesEvent::ResumeRequested)
+ .is_empty());
+ }
+
+ #[test]
+ fn collapsing_directory_releases_descendants() {
+ let root = RemotePath::from_server_absolute("/home/me").unwrap();
+ let child = root.join_name("src").unwrap();
+ let mut state = RemoteFilesState::default();
+ state.transition(RemoteFilesEvent::TargetChanged(Some(target("mux"))));
+ let generation = match state.transition(RemoteFilesEvent::ConnectRequested)[0] {
+ RemoteFilesEffect::Connect { generation, .. } => generation,
+ _ => unreachable!(),
+ };
+ state.transition(RemoteFilesEvent::Connected {
+ generation,
+ root: root.clone(),
+ listing: listing(&root, &[("src", RemoteFileKind::Directory)]),
+ });
+ state.transition(RemoteFilesEvent::ToggleDirectory(child.clone()));
+ state.transition(RemoteFilesEvent::DirectoryLoaded {
+ generation,
+ path: child.clone(),
+ listing: listing(&child, &[("lib.rs", RemoteFileKind::File)]),
+ });
+ assert_eq!(state.rows().len(), 3);
+ state.transition(RemoteFilesEvent::ToggleDirectory(child));
+ assert_eq!(state.rows().len(), 2);
+ assert_eq!(state.total_entries(), 1);
+ }
+
+ #[test]
+ fn stale_directory_result_is_ignored_after_panel_closes() {
+ let path = RemotePath::from_server_absolute("/home/me/src").unwrap();
+ let mut state = RemoteFilesState::default();
+ state.transition(RemoteFilesEvent::TargetChanged(Some(target("mux"))));
+ let generation = state.generation;
+ state.transition(RemoteFilesEvent::PanelHidden);
+ state.transition(RemoteFilesEvent::DirectoryLoaded {
+ generation,
+ path: path.clone(),
+ listing: listing(&path, &[("stale", RemoteFileKind::File)]),
+ });
+ assert!(state.rows().is_empty());
+ }
+
+ #[test]
+ fn stale_directory_result_does_not_clear_a_new_loading_request() {
+ let root = RemotePath::from_server_absolute("/home/me").unwrap();
+ let child = root.join_name("src").unwrap();
+ let mut state = RemoteFilesState::default();
+ state.transition(RemoteFilesEvent::TargetChanged(Some(target("mux"))));
+ let first_generation = state.generation;
+ state.transition(RemoteFilesEvent::PanelHidden);
+ let effect = state.transition(RemoteFilesEvent::ConnectRequested);
+ let current_generation = match effect[0] {
+ RemoteFilesEffect::Connect { generation, .. } => generation,
+ _ => unreachable!(),
+ };
+ state.transition(RemoteFilesEvent::Connected {
+ generation: current_generation,
+ root: root.clone(),
+ listing: listing(&root, &[("src", RemoteFileKind::Directory)]),
+ });
+ state.transition(RemoteFilesEvent::ToggleDirectory(child.clone()));
+ assert!(state.loading_directories.contains(&child));
+
+ state.transition(RemoteFilesEvent::DirectoryFailed {
+ generation: first_generation,
+ path: child.clone(),
+ message: "stale".to_string(),
+ });
+ assert!(state.loading_directories.contains(&child));
+ assert!(state.error_message.is_none());
+ }
+
+ #[test]
+ fn resume_does_not_reload_an_already_connected_panel() {
+ let root = RemotePath::from_server_absolute("/home/me").unwrap();
+ let mut state = RemoteFilesState::default();
+ state.transition(RemoteFilesEvent::TargetChanged(Some(target("mux"))));
+ let generation = match state.transition(RemoteFilesEvent::ConnectRequested)[0] {
+ RemoteFilesEffect::Connect { generation, .. } => generation,
+ _ => unreachable!(),
+ };
+ state.transition(RemoteFilesEvent::Connected {
+ generation,
+ root: root.clone(),
+ listing: listing(&root, &[]),
+ });
+
+ assert!(state
+ .transition(RemoteFilesEvent::ResumeRequested)
+ .is_empty());
+ assert_eq!(state.phase, RemoteFilesPhase::Connected);
+ assert_eq!(state.generation, generation);
+ }
+
+ #[test]
+ fn directory_results_are_capped_to_the_global_row_budget() {
+ let root = RemotePath::from_server_absolute("/home/me").unwrap();
+ let mut state = RemoteFilesState::default();
+ state.transition(RemoteFilesEvent::TargetChanged(Some(target("mux"))));
+ let generation = match state.transition(RemoteFilesEvent::ConnectRequested)[0] {
+ RemoteFilesEffect::Connect { generation, .. } => generation,
+ _ => unreachable!(),
+ };
+ let entries = (0..REMOTE_FILE_TREE_ROW_LIMIT + 10)
+ .map(|index| RemoteFileEntry {
+ path: root.join_name(&format!("file-{index}")).unwrap(),
+ name: format!("file-{index}"),
+ kind: RemoteFileKind::File,
+ size: None,
+ })
+ .collect();
+ state.transition(RemoteFilesEvent::Connected {
+ generation,
+ root,
+ listing: RemoteDirectoryListing {
+ entries,
+ truncated: true,
+ },
+ });
+ // One synthetic root row plus at most the configured remote entries.
+ assert_eq!(state.rows().len(), REMOTE_FILE_TREE_ROW_LIMIT + 1);
+ assert!(state.has_truncated_directory());
+ }
+}
diff --git a/wezterm-gui/src/termwindow/remote_thread_view.rs b/wezterm-gui/src/termwindow/remote_thread_view.rs
index fddeac26..c91e3d70 100644
--- a/wezterm-gui/src/termwindow/remote_thread_view.rs
+++ b/wezterm-gui/src/termwindow/remote_thread_view.rs
@@ -4,7 +4,8 @@ use crate::termwindow::content_view::{ContentView, ContentViewResponse, RemoteCo
use crate::termwindow::ui::icons::SvgIcon;
use crate::termwindow::TermWindow;
use crate::ui::{
- rect, ControlState, DrawContext, InteractionState, UiContext, UiPalette, WidgetKind,
+ draw_scrollbar, rect, wheel_delta_pixels, ControlState, DrawContext, InteractionState,
+ ScrollState, UiContext, UiPalette, UiTokens, WidgetKind,
};
use crate::workspace_threads::{self, ThreadConnectionState};
use mux::Mux;
@@ -48,6 +49,9 @@ pub(crate) struct RemoteThreadView {
phase: ViewPhase,
widgets: UiContext<RemoteThreadAction>,
interaction: InteractionState<RemoteThreadAction>,
+ scroll: ScrollState,
+ /// UI scale captured at paint time; mouse handlers get no `DrawContext`.
+ last_ui_scale: f32,
}
struct RemoteThreadSnapshot {
@@ -69,6 +73,8 @@ impl RemoteThreadView {
phase: ViewPhase::Idle,
widgets: UiContext::default(),
interaction: InteractionState::default(),
+ scroll: ScrollState::new(),
+ last_ui_scale: 1.0,
}
}
@@ -105,6 +111,7 @@ impl RemoteThreadView {
title_font: &Rc<LoadedFont>,
) -> anyhow::Result<()> {
self.widgets.clear();
+ self.last_ui_scale = ctx.scale();
ctx.draw_rect(
layers,
0,
@@ -115,11 +122,30 @@ impl RemoteThreadView {
palette.window_bg,
)?;
- let shell_w = (area.size.width - PAD * 2.0).min(CONTENT_MAX_W).max(0.0);
- let x = area.origin.x + ((area.size.width - shell_w) / 2.0).max(PAD);
- let mut y = area.origin.y + (area.size.height * 0.12).clamp(PAD, 112.0);
+ let pad = ctx.px(PAD);
+ let shell_w = (area.size.width - pad * 2.0)
+ .min(ctx.px(CONTENT_MAX_W))
+ .max(0.0);
+ let x = area.origin.x + ((area.size.width - shell_w) / 2.0).max(pad);
let width = shell_w;
- let line_h = (ctx.metrics.cell_size.height as f32 + 8.0).max(34.0);
+ // cell_size already tracks the window DPI; only the padding and the
+ // floor are design pixels.
+ let line_h = (ctx.metrics.cell_size.height as f32 + ctx.px(8.0)).max(ctx.px(34.0));
+
+ // Lay the stack out first so the scroll extents are known before
+ // anything is drawn.
+ let top_margin = (area.size.height * 0.12).clamp(pad, ctx.px(112.0));
+ let hero_h = ctx.px(112.0);
+ let info_h = ctx.px(214.0);
+ let info_gap = ctx.px(22.0);
+ let note_h = line_h * 2.0 + ctx.px(34.0);
+ let note_gap = ctx.px(28.0);
+ let button_h = (line_h + ctx.px(22.0)).max(ctx.px(BUTTON_MIN_H));
+ let content_h =
+ top_margin + hero_h + info_h + info_gap + note_h + note_gap + button_h + pad;
+ self.scroll.set_extents(area.size.height, content_h);
+
+ let mut y = area.origin.y + top_margin - self.scroll.offset;
let is_error =
matches!(self.phase, ViewPhase::Failed { .. }) || self.stale_message.is_some();
@@ -128,31 +154,32 @@ impl RemoteThreadView {
} else {
SvgIcon::Server
};
+ let hero_icon_size = ctx.px(HERO_ICON_SIZE);
ctx.draw_rounded_frame(
layers,
0,
x,
- y + 4.0,
- HERO_ICON_SIZE,
- HERO_ICON_SIZE,
+ y + ctx.px(4.0),
+ hero_icon_size,
+ hero_icon_size,
palette.control_bg,
palette.control_border,
- 20.0,
+ ctx.px(20.0),
)?;
ctx.draw_svg_icon(
layers,
hero_icon,
- x + 18.0,
- y + 22.0,
- 28.0,
+ x + ctx.px(18.0),
+ y + ctx.px(22.0),
+ ctx.px(28.0),
if is_error {
palette.secondary_text
} else {
palette.text
},
)?;
- let hero_text_x = x + HERO_ICON_SIZE + 22.0;
- let hero_text_w = (width - HERO_ICON_SIZE - 22.0).max(0.0);
+ let hero_text_x = x + hero_icon_size + ctx.px(22.0);
+ let hero_text_w = (width - hero_icon_size - ctx.px(22.0)).max(0.0);
ctx.draw_text(
layers,
title_font,
@@ -175,24 +202,47 @@ impl RemoteThreadView {
layers,
font,
hero_text_x,
- y + line_h + 16.0,
+ y + line_h + ctx.px(16.0),
&status,
palette.muted_text,
hero_text_w,
)?;
- y += 112.0;
+ y += hero_h;
- let info_h = 214.0;
self.paint_info_panel(ctx, layers, font, palette, x, y, width, info_h, line_h)?;
- y += info_h + 22.0;
+ y += info_h + info_gap;
- let note_h = line_h * 2.0 + 34.0;
self.paint_status_panel(ctx, layers, font, palette, x, y, width, note_h, line_h)?;
- y += note_h + 28.0;
+ y += note_h + note_gap;
- let button_h = (line_h + 22.0).max(BUTTON_MIN_H);
self.paint_phase_buttons(ctx, layers, font, palette, x, y, button_h)?;
+ // Nothing here can clip, so scrolled-away content would bleed into the
+ // window chrome above. Repaint that strip in the chrome colour; the
+ // tab bar / window buttons are drawn after content views and land on
+ // top of it again.
+ if self.scroll.offset > 0.0 && area.origin.y > 0.0 {
+ ctx.draw_rect(
+ layers,
+ 2,
+ area.origin.x,
+ 0.0,
+ area.size.width,
+ area.origin.y,
+ palette.sidebar_bg,
+ )?;
+ }
+ if self.scroll.has_overflow() {
+ draw_scrollbar(
+ ctx,
+ layers,
+ palette,
+ UiTokens::for_dpi(ctx.dimensions.dpi),
+ area,
+ self.scroll,
+ )?;
+ }
+
Ok(())
}
@@ -218,27 +268,27 @@ impl RemoteThreadView {
height,
palette.control_bg,
palette.control_border,
- CARD_RADIUS,
+ ctx.px(CARD_RADIUS),
)?;
- let pad = 24.0;
+ let pad = ctx.px(24.0);
ctx.draw_text(
layers,
font,
x + pad,
- y + 22.0,
+ y + ctx.px(22.0),
"Connection",
palette.text,
width - pad * 2.0,
)?;
- let row_y = y + 70.0;
- let label_w = (width * 0.32).clamp(118.0, 168.0);
+ let row_y = y + ctx.px(70.0);
+ let label_w = (width * 0.32).clamp(ctx.px(118.0), ctx.px(168.0));
let details = [
("Project", self.state.project_name.as_str()),
("Endpoint", self.endpoint.as_str()),
("Thread", self.state.thread_name.as_str()),
];
for (idx, (label, value)) in details.iter().enumerate() {
- let y = row_y + idx as f32 * (line_h + 6.0);
+ let y = row_y + idx as f32 * (line_h + ctx.px(6.0));
ctx.draw_text(layers, font, x + pad, y, label, palette.muted_text, label_w)?;
ctx.draw_text(
layers,
@@ -275,9 +325,9 @@ impl RemoteThreadView {
height,
palette.control_bg,
palette.control_border,
- CARD_RADIUS,
+ ctx.px(CARD_RADIUS),
)?;
- let pad = 20.0;
+ let pad = ctx.px(20.0);
let text_w = width - pad * 2.0;
let (line_one, line_two) = match &self.phase {
ViewPhase::Connecting { started } => {
@@ -316,7 +366,7 @@ impl RemoteThreadView {
layers,
font,
x + pad,
- y + 16.0,
+ y + ctx.px(16.0),
&line_one,
palette.text,
text_w,
@@ -325,7 +375,7 @@ impl RemoteThreadView {
layers,
font,
x + pad,
- y + 16.0 + line_h,
+ y + ctx.px(16.0) + line_h,
&line_two,
palette.muted_text,
text_w,
@@ -389,7 +439,7 @@ impl RemoteThreadView {
};
let mut bx = x;
for (label, icon, action, primary, enabled) in buttons {
- let w = (ctx.measure_text_width(font, label) + 92.0).max(168.0);
+ let w = (ctx.measure_text_width(font, label) + ctx.px(92.0)).max(ctx.px(168.0));
self.paint_action_button(
ctx,
layers,
@@ -402,7 +452,7 @@ impl RemoteThreadView {
primary,
enabled,
)?;
- bx += w + 16.0;
+ bx += w + ctx.px(16.0);
}
Ok(())
}
@@ -446,13 +496,13 @@ impl RemoteThreadView {
area.size.height,
bg,
border,
- BUTTON_RADIUS,
+ ctx.px(BUTTON_RADIUS),
)?;
- let icon_size = 22.0;
- let icon_x = area.origin.x + 18.0;
+ let icon_size = ctx.px(22.0);
+ let icon_x = area.origin.x + ctx.px(18.0);
let icon_y = area.origin.y + (area.size.height - icon_size) / 2.0;
ctx.draw_svg_icon(layers, icon, icon_x, icon_y, icon_size, text)?;
- let text_x = icon_x + icon_size + 12.0;
+ let text_x = icon_x + icon_size + ctx.px(12.0);
ctx.draw_text(
layers,
font,
@@ -460,7 +510,7 @@ impl RemoteThreadView {
Self::centered_text_y(ctx, area),
label,
text,
- area.size.width - (text_x - area.origin.x) - 16.0,
+ area.size.width - (text_x - area.origin.x) - ctx.px(16.0),
)?;
Ok(())
}
@@ -468,6 +518,16 @@ impl RemoteThreadView {
fn on_mouse_impl(&mut self, x: f32, y: f32, kind: WMEK) -> ContentViewResponse {
let hit = self.widgets.hit_test(x, y).map(|target| target.action);
match kind {
+ WMEK::VertWheel(amount) => {
+ let old = self.scroll.offset;
+ self.scroll
+ .scroll_by(wheel_delta_pixels(amount, self.last_ui_scale));
+ if (self.scroll.offset - old).abs() > 0.01 {
+ ContentViewResponse::Redraw
+ } else {
+ ContentViewResponse::Ignored
+ }
+ }
WMEK::Move => {
if self.interaction.hovered != hit {
self.interaction.hovered = hit;
diff --git a/wezterm-gui/src/termwindow/render/draw.rs b/wezterm-gui/src/termwindow/render/draw.rs
index fa50c5ca..3e4ee63d 100644
--- a/wezterm-gui/src/termwindow/render/draw.rs
+++ b/wezterm-gui/src/termwindow/render/draw.rs
@@ -3,12 +3,12 @@ use crate::renderstate::{LoggedSrgbTexture2d, RenderState};
use crate::termwindow::webgpu::{ShaderUniform, WebGpuState, WebGpuTexture};
use crate::termwindow::RenderFrame;
use crate::uniforms::UniformBuilder;
+use ::window::color::LinearRgba;
use ::window::glium;
use ::window::glium::uniforms::{
MagnifySamplerFilter, MinifySamplerFilter, Sampler, SamplerWrapFunction,
};
use ::window::glium::{BlendingFunction, LinearBlendingFactor, Surface};
-use ::window::color::LinearRgba;
use ::window::{Appearance, Dimensions, WindowDecorations, WindowState};
use config::FreeTypeLoadTarget;
@@ -69,9 +69,7 @@ pub(crate) fn effective_window_border(
Appearance::Light | Appearance::LightHighContrast => {
LinearRgba::with_srgba(199, 199, 204, 255)
}
- Appearance::Dark | Appearance::DarkHighContrast => {
- LinearRgba::with_srgba(68, 68, 76, 255)
- }
+ Appearance::Dark | Appearance::DarkHighContrast => LinearRgba::with_srgba(68, 68, 76, 255),
};
WindowBorder {
width: LINUX_WINDOW_BORDER_WIDTH * dpi.max(1) as f32 / 96.0,
@@ -433,8 +431,7 @@ mod tests {
#[test]
fn linux_corner_radius_only_applies_to_floating_client_chrome() {
let decorations = WindowDecorations::INTEGRATED_BUTTONS | WindowDecorations::RESIZE;
- let radius =
- effective_window_corner_radius(decorations, WindowState::COMPOSITED, 96);
+ let radius = effective_window_corner_radius(decorations, WindowState::COMPOSITED, 96);
if cfg!(target_os = "linux") {
assert_eq!(radius, LINUX_WINDOW_CORNER_RADIUS);
} else {
@@ -448,11 +445,7 @@ mod tests {
WindowState::SERVER_DECORATED,
] {
assert_eq!(
- effective_window_corner_radius(
- decorations,
- state | WindowState::COMPOSITED,
- 96,
- ),
+ effective_window_corner_radius(decorations, state | WindowState::COMPOSITED, 96,),
0.0
);
}
@@ -473,18 +466,10 @@ mod tests {
#[test]
fn linux_window_border_tracks_appearance_and_floating_state() {
let decorations = WindowDecorations::INTEGRATED_BUTTONS | WindowDecorations::RESIZE;
- let dark = effective_window_border(
- decorations,
- WindowState::COMPOSITED,
- 96,
- Appearance::Dark,
- );
- let light = effective_window_border(
- decorations,
- WindowState::COMPOSITED,
- 96,
- Appearance::Light,
- );
+ let dark =
+ effective_window_border(decorations, WindowState::COMPOSITED, 96, Appearance::Dark);
+ let light =
+ effective_window_border(decorations, WindowState::COMPOSITED, 96, Appearance::Light);
if cfg!(target_os = "linux") {
assert_eq!(dark.width, 1.0);
assert_eq!(light.width, 1.0);
diff --git a/wezterm-gui/src/termwindow/render/mod.rs b/wezterm-gui/src/termwindow/render/mod.rs
index 94e4372e..91745098 100644
--- a/wezterm-gui/src/termwindow/render/mod.rs
+++ b/wezterm-gui/src/termwindow/render/mod.rs
@@ -627,8 +627,8 @@ impl crate::TermWindow {
};
}
- let dead_key_or_leader = *self.terminal_dead_key_status() != DeadKeyStatus::None
- || self.leader_is_active();
+ let dead_key_or_leader =
+ *self.terminal_dead_key_status() != DeadKeyStatus::None || self.leader_is_active();
if dead_key_or_leader && focused_and_active {
let (fg_color, bg_color) = if self.use_reverse_video_cursor(&params) {
diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rs
index e8208662..77b74d22 100644
--- a/wezterm-gui/src/termwindow/render/paint.rs
+++ b/wezterm-gui/src/termwindow/render/paint.rs
@@ -515,9 +515,7 @@ impl crate::TermWindow {
};
let gl_state = self.render_state.as_ref().unwrap();
- let layer = gl_state
- .layer_for_zindex(0)
- .context("drag ghost layer")?;
+ let layer = gl_state.layer_for_zindex(0).context("drag ghost layer")?;
let mut layers = layer.quad_allocator();
let ctx = DrawContext::new(gl_state, self.dimensions, &metrics);
diff --git a/wezterm-gui/src/termwindow/ssh_hosts_view.rs b/wezterm-gui/src/termwindow/ssh_hosts_view.rs
index abfb2881..a3aabf02 100644
--- a/wezterm-gui/src/termwindow/ssh_hosts_view.rs
+++ b/wezterm-gui/src/termwindow/ssh_hosts_view.rs
@@ -10,9 +10,10 @@ 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,
+ char_index_for_x, contains, draw_button, draw_icon_button, draw_scrollbar, draw_text_input,
+ draw_toggle, rect, text_width_to_char, wheel_delta_pixels, ButtonSpec, ControlState,
+ DrawContext, EditModifiers, InputCaret, InteractionState, ScrollState, TextInputSpec,
+ TextInputState, UiContext, UiPalette, UiTokens, WidgetKind,
};
use crate::workspace_threads;
use std::rc::Rc;
@@ -43,6 +44,59 @@ const FIELD_LABELS: [&str; BASE_FIELD_COUNT] = [
"Workspace",
];
+/// Heading emitted before the field at the given index, so the form reads as
+/// Connection / Authentication / Session rather than one flat column.
+/// Where focus lands when the Advanced section is collapsed. Rows inside it
+/// stop being drawn, so a focus still pointing at one would silently edit an
+/// invisible field; anything else keeps its place.
+fn focus_after_collapsing_advanced(focus: Focus) -> Focus {
+ match focus {
+ Focus::OptionKey(_) | Focus::OptionValue(_) => Focus::Field(FIELD_HOST),
+ other => other,
+ }
+}
+
+/// Tab order: the regular fields, then each visible `ssh_options` row as a
+/// key/value pair.
+fn tab_stops_for(form: &HostForm) -> Vec<Focus> {
+ let mut stops: Vec<Focus> = (0..SshHostsView::visible_field_count(form))
+ .map(Focus::Field)
+ .collect();
+ if form.advanced_open {
+ for index in 0..form.options.len() {
+ stops.push(Focus::OptionKey(index));
+ stops.push(Focus::OptionValue(index));
+ }
+ }
+ stops
+}
+
+/// Collapse the edited rows into the map the ssh layer consumes. Rows whose
+/// key is blank are still being typed and are dropped rather than written as a
+/// nameless option.
+fn ssh_options_from_rows(
+ rows: &[(TextInputState, TextInputState)],
+) -> std::collections::HashMap<String, String> {
+ rows.iter()
+ .filter_map(|(key, value)| {
+ let key = key.text().trim();
+ (!key.is_empty()).then(|| (key.to_string(), value.text().trim().to_string()))
+ })
+ .collect()
+}
+
+fn text_input_with(text: String) -> TextInputState {
+ let mut input = TextInputState::new();
+ input.set_text_end(text);
+ input
+}
+
+const FIELD_GROUP_HEADINGS: [(usize, &str); 3] = [
+ (FIELD_NAME, "Connection"),
+ (FIELD_PASSWORD, "Authentication"),
+ (FIELD_WORKSPACE, "Session"),
+];
+
const PAD: f32 = 20.0;
const LEFT_DEFAULT_W: f32 = 500.0;
const LEFT_MIN_W: f32 = 360.0;
@@ -78,19 +132,33 @@ enum SshViewAction {
Cancel,
ToggleSystemHosts,
ResizeLeftPane,
+ ToggleAdvanced,
+ FocusOptionKey(usize),
+ FocusOptionValue(usize),
+ RemoveOption(usize),
+ AddOption,
}
-#[derive(Clone, Copy, PartialEq, Eq)]
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Focus {
Search,
Field(usize),
+ /// `ssh_options` row `n`, key column.
+ OptionKey(usize),
+ /// `ssh_options` row `n`, value column.
+ OptionValue(usize),
}
#[derive(Default, Clone)]
struct HostForm {
editing: Option<String>,
original: Option<SshHostSpec>,
- fields: [String; FIELD_COUNT],
+ fields: [TextInputState; FIELD_COUNT],
+ /// Free-form `ssh_config` overrides, edited as key/value rows. Kept as a
+ /// Vec (not a map) so a half-typed key does not collide or reorder while
+ /// the user is still typing.
+ options: Vec<(TextInputState, TextInputState)>,
+ advanced_open: bool,
detect_os: bool,
use_mosh: bool,
multiplexing: bool,
@@ -98,7 +166,7 @@ struct HostForm {
}
pub(crate) struct SshHostsView {
- search: String,
+ search: TextInputState,
selected: usize,
focus: Focus,
form: Option<HostForm>,
@@ -114,8 +182,18 @@ pub(crate) struct SshHostsView {
/// can convert pointer pixels back into design pixels.
last_ui_scale: f32,
list_area: RectF,
- /// When true the focused field is "select-all"; the next edit replaces it.
- select_all: bool,
+ /// Absolute x of a click that should become a caret position. Mouse
+ /// handlers have no `DrawContext`, so glyph measurement is deferred to the
+ /// next paint, which knows the font and the field's text origin.
+ pending_caret_click: Option<(Focus, f32)>,
+ /// Independent scroll for the right-hand form column; the left host list
+ /// has its own `scroll`.
+ form_scroll: ScrollState,
+ /// Height the form needed on the previous frame. Immediate-mode layout
+ /// only learns it after drawing, so extents lag by one frame and settle.
+ form_content_h: f32,
+ /// Bounds of the form column, remembered for wheel hit-testing.
+ form_area: RectF,
widgets: UiContext<SshViewAction>,
interaction: InteractionState<SshViewAction>,
scroll: ScrollState,
@@ -124,7 +202,7 @@ pub(crate) struct SshHostsView {
impl SshHostsView {
pub(crate) fn new() -> Self {
let mut view = Self {
- search: String::new(),
+ search: TextInputState::new(),
selected: 0,
focus: Focus::Search,
form: None,
@@ -137,7 +215,10 @@ impl SshHostsView {
last_area_w: 0.0,
last_ui_scale: 1.0,
list_area: rect(0.0, 0.0, 0.0, 0.0),
- select_all: false,
+ pending_caret_click: None,
+ form_scroll: ScrollState::new(),
+ form_content_h: 0.0,
+ form_area: rect(0.0, 0.0, 0.0, 0.0),
widgets: UiContext::default(),
interaction: InteractionState::default(),
scroll: ScrollState::new(),
@@ -147,7 +228,7 @@ impl SshHostsView {
}
fn refresh(&mut self) {
- let needle = self.search.trim().to_ascii_lowercase();
+ let needle = self.search.text().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()
@@ -193,11 +274,13 @@ impl SshHostsView {
fn open_new_form(&mut self) {
let mut form = HostForm::default();
- form.fields[FIELD_PORT] = "22".to_string();
- form.fields[FIELD_MOSH_SERVER] = ssh_hosts::DEFAULT_MOSH_SERVER_COMMAND.to_string();
+ form.fields[FIELD_PORT].set_text_end("22".to_string());
+ form.fields[FIELD_MOSH_SERVER]
+ .set_text_end(ssh_hosts::DEFAULT_MOSH_SERVER_COMMAND.to_string());
form.detect_os = true;
self.form = Some(form);
self.focus = Focus::Field(FIELD_HOST);
+ self.reset_form_scroll();
}
fn open_edit_form(&mut self, project_id: &str) {
@@ -220,36 +303,65 @@ impl SshHostsView {
fields[FIELD_IDENTITY] = spec.identity_file.clone().unwrap_or_default();
fields[FIELD_WORKSPACE] = spec.default_workspace.clone().unwrap_or_default();
fields[FIELD_MOSH_SERVER] = spec.mosh_server_command.clone();
+ let fields = fields.map(|text| {
+ let mut input = TextInputState::new();
+ input.set_text_end(text);
+ input
+ });
let detect_os = spec.detect_os;
let use_mosh = spec.use_mosh;
let multiplexing = spec.multiplexing;
+ // Sorted so the rows keep a stable order between opens.
+ let mut option_pairs: Vec<(String, String)> = spec
+ .ssh_options
+ .iter()
+ .map(|(key, value)| (key.clone(), value.clone()))
+ .collect();
+ option_pairs.sort();
+ let options = option_pairs
+ .into_iter()
+ .map(|(key, value)| (text_input_with(key), text_input_with(value)))
+ .collect::<Vec<_>>();
+ let advanced_open = !options.is_empty();
self.form = Some(HostForm {
editing: Some(project_id.to_string()),
original: Some(spec),
fields,
+ options,
+ advanced_open,
detect_os,
use_mosh,
multiplexing,
error: None,
});
self.focus = Focus::Field(FIELD_HOST);
+ self.reset_form_scroll();
}
fn close_form(&mut self) {
self.form = None;
self.focus = Focus::Search;
+ self.reset_form_scroll();
+ }
+
+ /// A newly installed form must start at the top. `form_content_h` is the
+ /// previous frame's measurement, so it has to go too — otherwise the first
+ /// frame sizes the scroll extents from the old form's height.
+ fn reset_form_scroll(&mut self) {
+ self.form_scroll.reset();
+ self.form_content_h = 0.0;
}
/// 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();
+ let host = form.fields[FIELD_HOST].text().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() {
+ let port = match form.fields[FIELD_PORT].text().trim() {
"" => None,
value => match value.parse::<u16>() {
Ok(p) => Some(p),
@@ -263,7 +375,7 @@ impl SshHostsView {
let t = s.trim();
(!t.is_empty()).then(|| t.to_string())
};
- let label = opt(&form.fields[FIELD_NAME]).unwrap_or_else(|| host.clone());
+ let label = opt(&form.fields[FIELD_NAME].text()).unwrap_or_else(|| host.clone());
let mut spec = form.original.clone().unwrap_or_else(|| SshHostSpec {
label: label.clone(),
@@ -283,10 +395,10 @@ impl SshHostsView {
spec.label = label;
spec.host = host;
spec.port = port;
- spec.username = opt(&form.fields[FIELD_USER]);
+ spec.username = opt(&form.fields[FIELD_USER].text());
// 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]) {
+ spec.password = match opt(&form.fields[FIELD_PASSWORD].text()) {
Some(password) => match crate::secret::encrypt(&password) {
Ok(encrypted) => Some(encrypted),
Err(err) => {
@@ -297,12 +409,15 @@ impl SshHostsView {
},
None => None,
};
- spec.identity_file = opt(&form.fields[FIELD_IDENTITY]);
- spec.default_workspace = opt(&form.fields[FIELD_WORKSPACE]);
+ spec.identity_file = opt(&form.fields[FIELD_IDENTITY].text());
+ spec.default_workspace = opt(&form.fields[FIELD_WORKSPACE].text());
+ // Rows with an empty key are still being typed; drop them rather than
+ // writing a nameless option the ssh layer would ignore.
+ spec.ssh_options = ssh_options_from_rows(&form.options);
spec.detect_os = form.detect_os;
spec.use_mosh = form.use_mosh;
spec.multiplexing = form.multiplexing;
- let mosh_server_command = form.fields[FIELD_MOSH_SERVER].trim();
+ let mosh_server_command = form.fields[FIELD_MOSH_SERVER].text().trim();
if spec.use_mosh && mosh_server_command.is_empty() {
form.error = Some("Mosh server command is required".to_string());
return None;
@@ -344,14 +459,20 @@ impl SshHostsView {
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
- }
+ let scroll = if self.point_in_host_list(x, y) {
+ Some(&mut self.scroll)
+ } else if contains(self.form_area, x, y) {
+ Some(&mut self.form_scroll)
+ } else {
+ None
+ };
+ let Some(scroll) = scroll else {
+ return ContentViewResponse::Ignored;
+ };
+ let old = scroll.offset;
+ scroll.scroll_by(wheel_delta_pixels(amount, self.last_ui_scale));
+ if (scroll.offset - old).abs() > 0.01 {
+ ContentViewResponse::Redraw
} else {
ContentViewResponse::Ignored
}
@@ -359,11 +480,10 @@ impl SshHostsView {
WMEK::Move => {
if self.dragging_left_pane {
let scale = self.last_ui_scale.max(0.01);
- self.left_width =
- Self::clamp_left_width(
- (x - self.last_area_x) / scale,
- self.last_area_w / scale,
- );
+ self.left_width = Self::clamp_left_width(
+ (x - self.last_area_x) / scale,
+ self.last_area_w / scale,
+ );
return ContentViewResponse::Redraw;
}
if self.interaction.hovered != hit {
@@ -389,6 +509,13 @@ impl SshHostsView {
let pressed = self.interaction.pressed.take();
if let (Some(a), Some(b)) = (hit, pressed) {
if a == b {
+ self.pending_caret_click = match a {
+ SshViewAction::Search => Some((Focus::Search, x)),
+ SshViewAction::FocusField(n) => Some((Focus::Field(n), x)),
+ SshViewAction::FocusOptionKey(n) => Some((Focus::OptionKey(n), x)),
+ SshViewAction::FocusOptionValue(n) => Some((Focus::OptionValue(n), x)),
+ _ => None,
+ };
return self.apply(a);
}
}
@@ -406,12 +533,52 @@ impl SshHostsView {
}
fn apply(&mut self, action: SshViewAction) -> ContentViewResponse {
- self.select_all = false;
+ self.clear_focused_selection();
match action {
SshViewAction::Search => {
self.focus = Focus::Search;
ContentViewResponse::Redraw
}
+ SshViewAction::ToggleAdvanced => {
+ if let Some(form) = self.form.as_mut() {
+ form.advanced_open = !form.advanced_open;
+ if !form.advanced_open {
+ // Leaving focus on a row that is no longer drawn would
+ // let the next keystroke edit an invisible field.
+ self.focus = focus_after_collapsing_advanced(self.focus);
+ }
+ }
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::FocusOptionKey(n) => {
+ self.focus = Focus::OptionKey(n);
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::FocusOptionValue(n) => {
+ self.focus = Focus::OptionValue(n);
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::AddOption => {
+ if let Some(form) = self.form.as_mut() {
+ form.advanced_open = true;
+ form.options
+ .push((TextInputState::new(), TextInputState::new()));
+ self.focus = Focus::OptionKey(form.options.len() - 1);
+ }
+ ContentViewResponse::Redraw
+ }
+ SshViewAction::RemoveOption(n) => {
+ if let Some(form) = self.form.as_mut() {
+ if n < form.options.len() {
+ form.options.remove(n);
+ }
+ }
+ // The removed row's index would now point at its neighbour.
+ if matches!(self.focus, Focus::OptionKey(_) | Focus::OptionValue(_)) {
+ self.focus = Focus::Field(FIELD_HOST);
+ }
+ ContentViewResponse::Redraw
+ }
SshViewAction::New => {
self.open_new_form();
ContentViewResponse::Redraw
@@ -462,9 +629,9 @@ impl SshHostsView {
// transports; only one can drive the connection.
form.multiplexing = false;
}
- if form.use_mosh && form.fields[FIELD_MOSH_SERVER].trim().is_empty() {
- form.fields[FIELD_MOSH_SERVER] =
- ssh_hosts::DEFAULT_MOSH_SERVER_COMMAND.to_string();
+ if form.use_mosh && form.fields[FIELD_MOSH_SERVER].text().trim().is_empty() {
+ form.fields[FIELD_MOSH_SERVER]
+ .set_text_end(ssh_hosts::DEFAULT_MOSH_SERVER_COMMAND.to_string());
}
if !form.use_mosh && self.focus == Focus::Field(FIELD_MOSH_SERVER) {
self.focus = Focus::Field(FIELD_WORKSPACE);
@@ -510,6 +677,14 @@ impl SshHostsView {
}
fn on_key_impl(&mut self, key: KeyCode, mods: KeyModifiers) -> ContentViewResponse {
+ // Up/Down drive the host list, so they must reach the navigation match
+ // below even while a field has focus.
+ if !matches!(key, KeyCode::UpArrow | KeyCode::DownArrow) {
+ if let Some(response) = self.handle_text_editing_key(key, mods) {
+ return response;
+ }
+ }
+
let in_form = self.form.is_some();
match (key, mods) {
(KeyCode::Escape, _) => {
@@ -548,107 +723,260 @@ impl SshHostsView {
}
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::Ignored,
+ }
+ }
+
+ /// Text-editing keys shared by the search box and every form field.
+ /// Returns `None` when the key is not an editing key, so the caller falls
+ /// through to view-level navigation (Tab / Enter / Escape / list arrows).
+ ///
+ /// Chords are resolved through [`EditModifiers`] rather than testing raw
+ /// modifiers, so ⌘ on macOS and Ctrl on Windows/Linux behave identically.
+ fn handle_text_editing_key(
+ &mut self,
+ key: KeyCode,
+ mods: KeyModifiers,
+ ) -> Option<ContentViewResponse> {
+ let edit = EditModifiers::from(mods);
+ let shift = edit.shift;
+ let macos = cfg!(target_os = "macos");
+
+ if edit.command {
+ match key {
+ KeyCode::Char('a') | KeyCode::Char('A') => {
+ self.edit_focused(|input| input.caret_select_all());
+ return Some(ContentViewResponse::Redraw);
}
- ContentViewResponse::Redraw
+ // Clipboard lives on TermWindow (it owns the window handle), so
+ // hand the work back rather than duplicating it here.
+ KeyCode::Char('c') | KeyCode::Char('C') => {
+ return Some(ContentViewResponse::Run(Box::new(|term_window| {
+ term_window.content_view_copy()
+ })));
+ }
+ KeyCode::Char('x') | KeyCode::Char('X') => {
+ return Some(ContentViewResponse::Run(Box::new(|term_window| {
+ term_window.content_view_cut()
+ })));
+ }
+ KeyCode::Char('v') | KeyCode::Char('V') => {
+ return Some(ContentViewResponse::Run(Box::new(|term_window| {
+ term_window.content_view_paste()
+ })));
+ }
+ // ⌘←/→/⌫ are line-start/end/delete-to-start on macOS. Elsewhere
+ // the same physical chord is the word modifier, handled below.
+ KeyCode::LeftArrow if macos => {
+ self.edit_focused(|input| input.caret_move_home(shift));
+ return Some(ContentViewResponse::Redraw);
+ }
+ KeyCode::RightArrow if macos => {
+ self.edit_focused(|input| input.caret_move_end(shift));
+ return Some(ContentViewResponse::Redraw);
+ }
+ KeyCode::Backspace if macos => {
+ self.edit_focused(|input| input.caret_delete_to_start());
+ return Some(ContentViewResponse::Redraw);
+ }
+ _ => {}
}
- (KeyCode::Char(c), KeyModifiers::NONE) | (KeyCode::Char(c), KeyModifiers::SHIFT) => {
- if self.select_all {
- self.clear_focused();
- self.select_all = false;
+ }
+
+ if edit.word {
+ match key {
+ KeyCode::LeftArrow => {
+ self.edit_focused(|input| input.caret_word_left(shift));
+ return Some(ContentViewResponse::Redraw);
}
- self.edit_focused(|s| s.push(c));
- if matches!(self.focus, Focus::Search) {
- self.selected = 0;
- self.refresh();
+ KeyCode::RightArrow => {
+ self.edit_focused(|input| input.caret_word_right(shift));
+ return Some(ContentViewResponse::Redraw);
}
- ContentViewResponse::Redraw
+ KeyCode::Backspace => {
+ self.edit_focused(|input| input.caret_delete_word_back());
+ return Some(ContentViewResponse::Redraw);
+ }
+ _ => {}
}
- _ => ContentViewResponse::Ignored,
+ }
+
+ if !edit.plain() {
+ return None;
+ }
+
+ match key {
+ KeyCode::LeftArrow => {
+ self.edit_focused(|input| input.caret_move_left(shift));
+ Some(ContentViewResponse::Redraw)
+ }
+ KeyCode::RightArrow => {
+ self.edit_focused(|input| input.caret_move_right(shift));
+ Some(ContentViewResponse::Redraw)
+ }
+ KeyCode::Home => {
+ self.edit_focused(|input| input.caret_move_home(shift));
+ Some(ContentViewResponse::Redraw)
+ }
+ KeyCode::End => {
+ self.edit_focused(|input| input.caret_move_end(shift));
+ Some(ContentViewResponse::Redraw)
+ }
+ KeyCode::Backspace => {
+ self.edit_focused(|input| input.caret_backspace());
+ Some(ContentViewResponse::Redraw)
+ }
+ KeyCode::Delete => {
+ self.edit_focused(|input| input.caret_delete_forward());
+ Some(ContentViewResponse::Redraw)
+ }
+ KeyCode::Char(c) if !c.is_control() => {
+ self.edit_focused(|input| input.caret_insert(&c.to_string(), false));
+ Some(ContentViewResponse::Redraw)
+ }
+ _ => None,
}
}
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();
- }
+ self.edit_focused(|input| input.caret_insert(&cleaned, false));
ContentViewResponse::Redraw
}
+ /// Tab order: the regular fields, then each visible `ssh_options` row as a
+ /// key/value pair. Wraps in both directions.
+ fn form_tab_stops(&self) -> Vec<Focus> {
+ self.form.as_ref().map(tab_stops_for).unwrap_or_default()
+ }
+
fn step_field(&mut self, delta: isize) {
- self.select_all = false;
- if let Focus::Field(n) = self.focus {
- let count = self
- .form
- .as_ref()
- .map(Self::visible_field_count)
- .unwrap_or(BASE_FIELD_COUNT);
- let next = (n.min(count - 1) as isize + delta).rem_euclid(count as isize) as usize;
- self.focus = Focus::Field(next);
- } else {
+ self.clear_focused_selection();
+ let stops = self.form_tab_stops();
+ if stops.is_empty() {
self.focus = Focus::Field(FIELD_HOST);
+ return;
}
+ let current = stops.iter().position(|stop| *stop == self.focus);
+ self.focus = match current {
+ Some(index) => {
+ let next = (index as isize + delta).rem_euclid(stops.len() as isize) as usize;
+ stops[next]
+ }
+ // Coming from the search box (or a row that just disappeared).
+ None => 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() {
- if n >= FIELD_COUNT {
- return;
- }
- form.error = None;
- f(&mut form.fields[n]);
- }
- }
+ /// Turn a recorded click into a caret position now that a `DrawContext`
+ /// and the field's laid-out text origin are available. `text` is what is
+ /// actually drawn (the password field passes its mask, which is one glyph
+ /// per character, so indices still line up).
+ fn resolve_pending_caret_click(
+ &mut self,
+ ctx: &DrawContext,
+ font: &Rc<LoadedFont>,
+ focus: Focus,
+ text: &str,
+ text_left: f32,
+ ) {
+ let Some((target, x)) = self.pending_caret_click else {
+ return;
+ };
+ if target != focus {
+ return;
+ }
+ self.pending_caret_click = None;
+ let index = char_index_for_x(ctx, font, text, x - text_left);
+ if let Some(input) = self.focused_input_mut() {
+ input.caret_set(index, false);
}
}
- fn clear_focused(&mut self) {
- self.edit_focused(|s| s.clear());
+ fn clear_focused_selection(&mut self) {
+ if let Some(input) = self.focused_input_mut() {
+ input.clear_selection();
+ }
}
- fn take_focused_selection(&mut self) -> Option<String> {
- if !self.select_all {
+ /// Caret + selection to render for `focus`, or `None` when that field is
+ /// not the focused one (an unfocused field never shows a caret).
+ fn caret_for(&self, focus: Focus) -> Option<InputCaret> {
+ if self.focus != focus {
return None;
}
- self.select_all = false;
- let text = match self.focus {
- Focus::Search => std::mem::take(&mut self.search),
+ let input = self.focused_input()?;
+ Some(InputCaret {
+ cursor: input.cursor,
+ selection: input.caret_selection_range(),
+ })
+ }
+
+ fn focused_input(&self) -> Option<&TextInputState> {
+ match self.focus {
+ Focus::Search => Some(&self.search),
+ Focus::Field(n) => self.form.as_ref()?.fields.get(n),
+ Focus::OptionKey(n) => {
+ let form = self.form.as_ref()?;
+ form.advanced_open
+ .then(|| form.options.get(n).map(|(key, _)| key))
+ .flatten()
+ }
+ Focus::OptionValue(n) => {
+ let form = self.form.as_ref()?;
+ form.advanced_open
+ .then(|| form.options.get(n).map(|(_, value)| value))
+ .flatten()
+ }
+ }
+ }
+
+ /// Mutable access to whatever field currently has focus. Clears the form's
+ /// error banner, since any edit invalidates the last validation result.
+ fn focused_input_mut(&mut self) -> Option<&mut TextInputState> {
+ match self.focus {
+ Focus::Search => Some(&mut self.search),
Focus::Field(n) => {
let form = self.form.as_mut()?;
- if n >= FIELD_COUNT {
+ form.error = None;
+ form.fields.get_mut(n)
+ }
+ Focus::OptionKey(n) => {
+ let form = self.form.as_mut()?;
+ if !form.advanced_open {
+ return None;
+ }
+ form.error = None;
+ form.options.get_mut(n).map(|(key, _)| key)
+ }
+ Focus::OptionValue(n) => {
+ let form = self.form.as_mut()?;
+ if !form.advanced_open {
return None;
}
form.error = None;
- std::mem::take(&mut form.fields[n])
+ form.options.get_mut(n).map(|(_, value)| value)
}
+ }
+ }
+
+ /// Run `f` against the focused field, then re-filter the host list if the
+ /// search box was the one edited.
+ fn edit_focused(&mut self, f: impl FnOnce(&mut TextInputState)) {
+ let Some(input) = self.focused_input_mut() else {
+ return;
};
+ f(input);
if matches!(self.focus, Focus::Search) {
self.selected = 0;
self.refresh();
}
- (!text.is_empty()).then_some(text)
+ }
+
+ fn take_focused_selection(&mut self) -> Option<String> {
+ let mut taken = None;
+ self.edit_focused(|input| taken = input.caret_take_selected_text());
+ taken
}
// ---- paint ------------------------------------------------------------
@@ -719,7 +1047,7 @@ impl SshHostsView {
.filter(|entry| entry.source == SshHostSource::ThinkTerm)
.count();
let visible_system_count =
- if !self.system_hosts_collapsed || !self.search.trim().is_empty() {
+ if !self.system_hosts_collapsed || !self.search.text().trim().is_empty() {
filtered
.iter()
.filter(|entry| entry.source == SshHostSource::System)
@@ -783,7 +1111,7 @@ impl SshHostsView {
)?;
row_y += ctx.px(GROUP_ROW_H + 10.0);
}
- if !self.system_hosts_collapsed || !self.search.trim().is_empty() {
+ if !self.system_hosts_collapsed || !self.search.text().trim().is_empty() {
for (i, entry) in filtered
.iter()
.enumerate()
@@ -881,6 +1209,7 @@ impl SshHostsView {
);
if self.form.is_some() {
+ let form_top = oy + ctx.px(PAD);
self.paint_form(
ctx,
layers,
@@ -889,8 +1218,9 @@ impl SshHostsView {
tokens,
cursor_on,
right_x,
- oy + ctx.px(PAD),
+ form_top,
right_w,
+ (oy + h) - form_top,
)?;
} else {
ctx.draw_text(
@@ -960,23 +1290,38 @@ impl SshHostsView {
tokens.control_radius,
)?;
+ // Hand-rolled rather than `draw_text_input` because this box sits on
+ // layer 2, above the list's scroll fade. Geometry mirrors that widget,
+ // including the design-pixel conversions.
let text_pad = ctx.px(12.0);
- let (search_text, search_color) = if self.search.is_empty() && !search_focused {
+ let text_left = search_rect.origin.x + text_pad;
+ let text_area = (search_rect.size.width - text_pad * 2.0).max(0.0);
+ let inset_y = ctx.px(5.0);
+ let highlight_y = search_rect.origin.y + inset_y;
+ let highlight_h = (search_rect.size.height - inset_y * 2.0).max(0.0);
+ // Must run before anything borrows `self.search` for the rest of the
+ // frame, since it may move the caret.
+ let search_text_owned = self.search.text().to_string();
+ self.resolve_pending_caret_click(ctx, font, Focus::Search, &search_text_owned, text_left);
+ let (search_text, search_color) = if search_text_owned.is_empty() && !search_focused {
("Search hosts...", palette.muted_text)
} else {
- (self.search.as_str(), palette.text)
+ (search_text_owned.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));
+ let selection = search_focused
+ .then(|| self.search.caret_selection_range())
+ .flatten()
+ .filter(|(start, end)| start != end);
+ if let Some((start, end)) = selection {
+ let start_x = text_width_to_char(ctx, font, &search_text_owned, start).min(text_area);
+ let end_x = text_width_to_char(ctx, font, &search_text_owned, end).min(text_area);
ctx.draw_rounded_rect(
layers,
2,
- search_rect.origin.x + text_pad - ctx.px(4.0),
- search_rect.origin.y + ctx.px(5.0),
- selection_width + ctx.px(8.0),
- search_rect.size.height - 10.0,
+ text_left + start_x - ctx.px(4.0),
+ highlight_y,
+ (end_x - start_x) + ctx.px(8.0),
+ highlight_h,
palette.selected_bg.mul_alpha(0.56),
(tokens.control_radius - ctx.px(5.0)).max(ctx.px(3.0)),
)?;
@@ -985,25 +1330,23 @@ impl SshHostsView {
layers,
2,
font,
- search_rect.origin.x + text_pad,
+ text_left,
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),
+ text_area,
)?;
- 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));
+ if search_focused && selection.is_none() && cursor_on {
+ let caret_dx = text_width_to_char(ctx, font, &search_text_owned, self.search.cursor)
+ .min(text_area);
+ let caret_width = ctx.px(3.0);
ctx.draw_rect(
layers,
2,
- caret_x - 1.0,
- search_rect.origin.y + ctx.px(5.0),
- ctx.px(3.0),
- search_rect.size.height - 10.0,
+ text_left + caret_dx - caret_width / 3.0,
+ highlight_y,
+ caret_width,
+ highlight_h,
palette.selected_bg,
)?;
}
@@ -1165,7 +1508,7 @@ impl SshHostsView {
10.0,
)?;
}
- let icon = if self.system_hosts_collapsed && self.search.trim().is_empty() {
+ let icon = if self.system_hosts_collapsed && self.search.text().trim().is_empty() {
SvgIcon::ChevronRight
} else {
SvgIcon::ChevronDown
@@ -1349,6 +1692,7 @@ impl SshHostsView {
x: f32,
y: f32,
width: f32,
+ height: f32,
) -> anyhow::Result<()> {
let form = self.form.as_ref().unwrap();
let editing = form.editing.is_some();
@@ -1356,44 +1700,57 @@ impl SshHostsView {
let use_mosh = form.use_mosh;
let multiplexing = form.multiplexing;
let fields = form.fields.clone();
+ let options = form.options.clone();
+ let advanced_open = form.advanced_open;
let error = form.error.clone();
let focus = self.focus;
+ // A form pinned to the left of a wide column reads badly, so cap the
+ // width and centre what is left over.
+ let field_w = width.min(ctx.px(560.0));
+ let x = x + ((width - field_w) / 2.0).max(0.0);
+ self.form_area = rect(x, y, field_w, height);
+ self.form_scroll.set_extents(height, self.form_content_h);
+ let top = y - self.form_scroll.offset;
+ let mut cur_y = top;
+
ctx.draw_text(
layers,
font,
x,
- y,
+ cur_y,
if editing { "Edit Host" } else { "New Host" },
palette.text,
- width,
+ field_w,
)?;
+ cur_y += ctx.metrics.cell_size.height as f32 + ctx.px(18.0);
let line_h = ctx.metrics.cell_size.height as f32;
- let field_w = width.min(ctx.px(560.0));
- let mut cur_y = y + line_h + ctx.px(18.0);
- for i in 0..BASE_FIELD_COUNT {
- ctx.draw_text(
- layers,
- font,
- x,
- cur_y,
- FIELD_LABELS[i],
- palette.muted_text,
- field_w,
- )?;
+ for (i, label) in FIELD_LABELS.iter().enumerate() {
+ if let Some(heading) = FIELD_GROUP_HEADINGS
+ .iter()
+ .find_map(|(at, heading)| (*at == i).then_some(*heading))
+ {
+ cur_y += ctx.px(if i == 0 { 0.0 } else { 10.0 });
+ ctx.draw_text(layers, font, x, cur_y, heading, palette.text, field_w)?;
+ cur_y += line_h + ctx.px(10.0);
+ }
+ ctx.draw_text(layers, font, x, cur_y, label, palette.muted_text, field_w)?;
let input_y = cur_y + line_h + ctx.px(6.0);
// Mask the password field.
let masked = if i == FIELD_PASSWORD {
- "•".repeat(fields[i].chars().count())
+ "•".repeat(fields[i].text().chars().count())
} else {
String::new()
};
let shown: &str = if i == FIELD_PASSWORD {
&masked
} else {
- &fields[i]
+ &fields[i].text()
};
+ // Resolved up front: the call below borrows `self.widgets` mutably.
+ self.resolve_pending_caret_click(ctx, font, Focus::Field(i), shown, x + ctx.px(12.0));
+ let field_caret = self.caret_for(Focus::Field(i));
draw_text_input(
ctx,
layers,
@@ -1409,9 +1766,10 @@ impl SshHostsView {
text: shown,
rect: rect(x, input_y, field_w, ctx.px(INPUT_H)),
focused: focus == Focus::Field(i),
- selected_all: focus == Focus::Field(i) && self.select_all,
+ selected_all: false,
action: SshViewAction::FocusField(i),
},
+ field_caret,
)?;
cur_y = input_y + ctx.px(INPUT_H + 18.0);
}
@@ -1462,6 +1820,14 @@ impl SshHostsView {
cur_y += toggle_h + ctx.px(24.0);
if use_mosh {
+ self.resolve_pending_caret_click(
+ ctx,
+ font,
+ Focus::Field(FIELD_MOSH_SERVER),
+ &fields[FIELD_MOSH_SERVER].text(),
+ x + ctx.px(12.0),
+ );
+ let mosh_caret = self.caret_for(Focus::Field(FIELD_MOSH_SERVER));
draw_text_input(
ctx,
layers,
@@ -1474,12 +1840,13 @@ impl SshHostsView {
cursor_on,
TextInputSpec {
placeholder: ssh_hosts::DEFAULT_MOSH_SERVER_COMMAND,
- text: &fields[FIELD_MOSH_SERVER],
+ text: &fields[FIELD_MOSH_SERVER].text(),
rect: rect(x, cur_y, field_w, ctx.px(INPUT_H)),
focused: focus == Focus::Field(FIELD_MOSH_SERVER),
- selected_all: focus == Focus::Field(FIELD_MOSH_SERVER) && self.select_all,
+ selected_all: false,
action: SshViewAction::FocusField(FIELD_MOSH_SERVER),
},
+ mosh_caret,
)?;
cur_y += ctx.px(INPUT_H + 24.0);
}
@@ -1507,6 +1874,128 @@ impl SshHostsView {
)?;
cur_y += toggle_h + ctx.px(24.0);
+ // Advanced: raw ssh_config overrides (ProxyJump, ServerAliveInterval,
+ // …). `build_ssh_domain` already feeds these straight into the ssh
+ // config, so nothing downstream needs to change.
+ let disclosure = if advanced_open { "▾" } else { "▸" };
+ let advanced_h = line_h + ctx.px(12.0);
+ self.widgets.push(
+ rect(x, cur_y, field_w, advanced_h),
+ WidgetKind::Button,
+ SshViewAction::ToggleAdvanced,
+ );
+ ctx.draw_text(
+ layers,
+ font,
+ x,
+ cur_y + (advanced_h - line_h) / 2.0,
+ &format!("{disclosure} Advanced (ssh_config options)"),
+ palette.text,
+ field_w,
+ )?;
+ cur_y += advanced_h + ctx.px(8.0);
+
+ if advanced_open {
+ let remove_w = ctx.px(INPUT_H);
+ let gap = ctx.px(8.0);
+ let pair_w = (field_w - remove_w - gap * 2.0).max(0.0);
+ let key_w = pair_w * 0.42;
+ let value_w = pair_w - key_w;
+ for (index, (key, value)) in options.iter().enumerate() {
+ let key_x = x;
+ let value_x = key_x + key_w + gap;
+ self.resolve_pending_caret_click(
+ ctx,
+ font,
+ Focus::OptionKey(index),
+ &key.text(),
+ key_x + ctx.px(12.0),
+ );
+ let key_caret = self.caret_for(Focus::OptionKey(index));
+ draw_text_input(
+ ctx,
+ layers,
+ font,
+ &mut self.widgets,
+ &self.interaction,
+ palette,
+ tokens,
+ ctx.px(12.0),
+ cursor_on,
+ TextInputSpec {
+ placeholder: "ProxyJump",
+ text: &key.text(),
+ rect: rect(key_x, cur_y, key_w, ctx.px(INPUT_H)),
+ focused: focus == Focus::OptionKey(index),
+ selected_all: false,
+ action: SshViewAction::FocusOptionKey(index),
+ },
+ key_caret,
+ )?;
+ self.resolve_pending_caret_click(
+ ctx,
+ font,
+ Focus::OptionValue(index),
+ &value.text(),
+ value_x + ctx.px(12.0),
+ );
+ let value_caret = self.caret_for(Focus::OptionValue(index));
+ draw_text_input(
+ ctx,
+ layers,
+ font,
+ &mut self.widgets,
+ &self.interaction,
+ palette,
+ tokens,
+ ctx.px(12.0),
+ cursor_on,
+ TextInputSpec {
+ placeholder: "user@bastion",
+ text: &value.text(),
+ rect: rect(value_x, cur_y, value_w, ctx.px(INPUT_H)),
+ focused: focus == Focus::OptionValue(index),
+ selected_all: false,
+ action: SshViewAction::FocusOptionValue(index),
+ },
+ value_caret,
+ )?;
+ draw_icon_button(
+ ctx,
+ layers,
+ &mut self.widgets,
+ &self.interaction,
+ palette,
+ value_x + value_w + gap,
+ cur_y,
+ remove_w,
+ SvgIcon::Trash2,
+ SshViewAction::RemoveOption(index),
+ )?;
+ cur_y += ctx.px(INPUT_H) + gap;
+ }
+
+ let add_label = "+ Add option";
+ let add_w = ctx.measure_text_width(font, add_label) + ctx.px(36.0);
+ // Resolved before `self.widgets` is borrowed mutably below.
+ let add_state = self.button_state(SshViewAction::AddOption, false);
+ draw_button(
+ ctx,
+ layers,
+ font,
+ &mut self.widgets,
+ palette,
+ ButtonSpec {
+ label: add_label,
+ action: SshViewAction::AddOption,
+ rect: rect(x, cur_y, add_w, ctx.px(BTN_H)),
+ state: add_state,
+ kind: WidgetKind::Button,
+ },
+ )?;
+ cur_y += ctx.px(BTN_H) + ctx.px(24.0);
+ }
+
if let Some(err) = &error {
ctx.draw_text(
layers,
@@ -1540,6 +2029,32 @@ impl SshHostsView {
draw_button(ctx, layers, font, &mut self.widgets, palette, spec)?;
bx += w + gap;
}
+ cur_y += ctx.px(BTN_H) + ctx.px(PAD);
+
+ self.form_content_h = cur_y - top;
+ // These draws cannot clip, so hide anything that scrolled above the
+ // column by repainting the strip over it (still inside our own area).
+ if self.form_scroll.offset > 0.0 {
+ ctx.draw_rect(
+ layers,
+ 2,
+ x,
+ y - ctx.px(PAD),
+ field_w,
+ ctx.px(PAD),
+ palette.window_bg,
+ )?;
+ }
+ if self.form_scroll.has_overflow() {
+ draw_scrollbar(
+ ctx,
+ layers,
+ palette,
+ tokens,
+ self.form_area,
+ self.form_scroll,
+ )?;
+ }
Ok(())
}
@@ -1609,10 +2124,10 @@ impl ContentView for SshHostsView {
}
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(),
- };
+ let input = self.focused_input()?;
+ let text = input
+ .caret_selected_text()
+ .unwrap_or_else(|| input.text().to_string());
(!text.is_empty()).then_some(text)
}
@@ -1620,3 +2135,95 @@ impl ContentView for SshHostsView {
self.take_focused_selection()
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::{
+ focus_after_collapsing_advanced, ssh_options_from_rows, tab_stops_for, text_input_with,
+ Focus, HostForm, BASE_FIELD_COUNT, FIELD_HOST, FIELD_WORKSPACE,
+ };
+
+ fn row(key: &str, value: &str) -> (super::TextInputState, super::TextInputState) {
+ (
+ text_input_with(key.to_string()),
+ text_input_with(value.to_string()),
+ )
+ }
+
+ #[test]
+ fn ssh_options_are_trimmed_and_blank_keys_dropped() {
+ let rows = vec![
+ row(" ProxyJump ", " user@bastion "),
+ row("", "orphaned-value"),
+ row(" ", ""),
+ row("ServerAliveInterval", "30"),
+ ];
+ let options = ssh_options_from_rows(&rows);
+ assert_eq!(options.len(), 2);
+ assert_eq!(
+ options.get("ProxyJump").map(String::as_str),
+ Some("user@bastion")
+ );
+ assert_eq!(
+ options.get("ServerAliveInterval").map(String::as_str),
+ Some("30")
+ );
+ }
+
+ #[test]
+ fn a_present_key_with_an_empty_value_is_kept() {
+ // `Option=` is meaningful to ssh_config; only a blank *key* is noise.
+ let options = ssh_options_from_rows(&[row("Compression", "")]);
+ assert_eq!(options.get("Compression").map(String::as_str), Some(""));
+ }
+
+ #[test]
+ fn collapsing_advanced_pulls_focus_out_of_hidden_rows() {
+ // Rows inside Advanced stop being drawn, so focus must not stay on one:
+ // `focused_input_mut` would otherwise keep routing keystrokes into an
+ // invisible field.
+ assert_eq!(
+ focus_after_collapsing_advanced(Focus::OptionKey(2)),
+ Focus::Field(FIELD_HOST)
+ );
+ assert_eq!(
+ focus_after_collapsing_advanced(Focus::OptionValue(0)),
+ Focus::Field(FIELD_HOST)
+ );
+ // Anything already visible keeps its place.
+ assert_eq!(
+ focus_after_collapsing_advanced(Focus::Field(FIELD_WORKSPACE)),
+ Focus::Field(FIELD_WORKSPACE)
+ );
+ assert_eq!(
+ focus_after_collapsing_advanced(Focus::Search),
+ Focus::Search
+ );
+ }
+
+ #[test]
+ fn hidden_option_rows_are_not_reachable_for_editing() {
+ let mut form = HostForm::default();
+ form.options = vec![row("ProxyJump", "bastion")];
+ form.advanced_open = false;
+ // Tab order is the visible surface; a collapsed section contributes
+ // nothing, which is the same invariant `focused_input_mut` enforces.
+ assert_eq!(tab_stops_for(&form).len(), BASE_FIELD_COUNT);
+ }
+
+ #[test]
+ fn tab_order_covers_option_rows_only_while_advanced_is_open() {
+ let mut form = HostForm::default();
+ form.options = vec![row("A", "1"), row("B", "2")];
+
+ form.advanced_open = false;
+ assert_eq!(tab_stops_for(&form).len(), BASE_FIELD_COUNT);
+
+ form.advanced_open = true;
+ let stops = tab_stops_for(&form);
+ assert_eq!(stops.len(), BASE_FIELD_COUNT + 4);
+ assert_eq!(stops[BASE_FIELD_COUNT], Focus::OptionKey(0));
+ assert_eq!(stops[BASE_FIELD_COUNT + 1], Focus::OptionValue(0));
+ assert_eq!(stops[BASE_FIELD_COUNT + 3], Focus::OptionValue(1));
+ }
+}
diff --git a/wezterm-gui/src/termwindow/ui/context_menu.rs b/wezterm-gui/src/termwindow/ui/context_menu.rs
index 59abee0e..a48c1b14 100644
--- a/wezterm-gui/src/termwindow/ui/context_menu.rs
+++ b/wezterm-gui/src/termwindow/ui/context_menu.rs
@@ -362,9 +362,8 @@ impl crate::TermWindow {
.title_font_with_size(menu_font_size)
.context("context menu ui font")?;
let ui_metrics = RenderMetrics::with_font_metrics(&ui_font.metrics());
- let row_height = (ui_metrics.cell_size.height as usize
- + self.ui_px(MENU_ROW_EXTRA_HEIGHT))
- .max(self.ui_px(44));
+ let row_height = (ui_metrics.cell_size.height as usize + self.ui_px(MENU_ROW_EXTRA_HEIGHT))
+ .max(self.ui_px(44));
let palette = context_menu_palette(crate::native_settings::effective_appearance());
let gl_state = self.render_state.as_ref().unwrap();
@@ -695,11 +694,21 @@ fn paint_menu_rows(
layers,
2,
euclid::rect(
- item_rect.x.saturating_add(term.ui_px(MENU_ROW_HOVER_INSET_X)) as f32,
- item_rect.y.saturating_add(term.ui_px(MENU_ROW_HOVER_INSET_Y)) as f32,
- item_rect.width.saturating_sub(term.ui_px(MENU_ROW_HOVER_INSET_X) * 2)
+ item_rect
+ .x
+ .saturating_add(term.ui_px(MENU_ROW_HOVER_INSET_X))
as f32,
- item_rect.height.saturating_sub(term.ui_px(MENU_ROW_HOVER_INSET_Y) * 2)
+ item_rect
+ .y
+ .saturating_add(term.ui_px(MENU_ROW_HOVER_INSET_Y))
+ as f32,
+ item_rect
+ .width
+ .saturating_sub(term.ui_px(MENU_ROW_HOVER_INSET_X) * 2)
+ as f32,
+ item_rect
+ .height
+ .saturating_sub(term.ui_px(MENU_ROW_HOVER_INSET_Y) * 2)
as f32,
),
palette.control_hover_bg,
@@ -723,8 +732,8 @@ fn paint_menu_rows(
} else {
palette.secondary_text
};
- let icon_y =
- item_rect.y + (item_rect.height.saturating_sub(term.ui_px(MENU_ICON_SIZE))) / 2;
+ let icon_y = item_rect.y
+ + (item_rect.height.saturating_sub(term.ui_px(MENU_ICON_SIZE))) / 2;
let check_x = item_rect.x + term.ui_px(MENU_PADDING_X);
let icon_x = check_x + term.ui_px(MENU_CHECK_SLOT);
if *checked {
diff --git a/wezterm-gui/src/termwindow/ui/platform_chrome.rs b/wezterm-gui/src/termwindow/ui/platform_chrome.rs
index dcb93bea..53a3a386 100644
--- a/wezterm-gui/src/termwindow/ui/platform_chrome.rs
+++ b/wezterm-gui/src/termwindow/ui/platform_chrome.rs
@@ -255,9 +255,7 @@ mod tests {
let px = |v: usize| scale_ui_usize(v, 96);
let fixed = px(WINDOW_TAB_LEADING_ACTION_BUTTON_SIZE);
// Capsule = row - spacer - 2 * vertical padding
- let capsule = |row: usize| {
- row - px(WINDOW_TAB_TOP_SPACER) - px(TAB_VERTICAL_PADDING) * 2
- };
+ let capsule = |row: usize| row - px(WINDOW_TAB_TOP_SPACER) - px(TAB_VERTICAL_PADDING) * 2;
// Normal and large tab fonts follow the row height
assert_eq!(
sidebar_toggle_size_px(96, WindowState::default(), Some(38)),
@@ -268,7 +266,10 @@ mod tests {
capsule(58)
);
// Hidden, retro or bottom tab bars keep the fixed usable size
- assert_eq!(sidebar_toggle_size_px(96, WindowState::default(), None), fixed);
+ assert_eq!(
+ sidebar_toggle_size_px(96, WindowState::default(), None),
+ fixed
+ );
// Tiny rows never shrink the control below the fixed size
assert_eq!(
sidebar_toggle_size_px(96, WindowState::default(), Some(8)),
@@ -291,7 +292,10 @@ mod tests {
for row in [38, 58, 90] {
let params = test_params(0, WindowState::default(), Some(row));
let painted = params.sidebar_toggle_button_size();
- assert_eq!(painted, sidebar_toggle_size_px(96, WindowState::default(), Some(row)));
+ assert_eq!(
+ painted,
+ sidebar_toggle_size_px(96, WindowState::default(), Some(row))
+ );
assert!(
params.leading_action_area_width_pixels() >= painted as f32,
"row {row}: reserved {} < painted {painted}",
diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
index 92edc30b..fcdb3a05 100644
--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
@@ -1,14 +1,19 @@
use crate::markdown_editor::{
- AutosaveWakeAction, BlockKind, EditorMode, NoteCodeBlockLayout, NoteLineGeometry,
- NoteLineLayout, NoteRunLayout, NoteSpellingIssue, ProjectedCodeBlock, ProjectedObject,
- SaveState, SourceSelection, TableAlignment, VisualLineKind, build_spell_check_chunks_in_range,
- build_visual_document, fit_table_columns, load_remote_image, open_vault_document,
- resolve_local_image, save_document_revision, vault_file_paths, vault_markdown_paths,
- wrap_visual_document_by_width_cached,
+ build_spell_check_chunks_in_range, build_visual_document, fit_table_columns, load_remote_image,
+ open_vault_document, resolve_local_image, save_document_revision, vault_file_paths,
+ vault_markdown_paths, wrap_visual_document_by_width_cached, AutosaveWakeAction, BlockKind,
+ EditorMode, NoteCodeBlockLayout, NoteLineGeometry, NoteLineLayout, NoteRunLayout,
+ NoteSpellingIssue, ProjectedCodeBlock, ProjectedObject, SaveState, SourceSelection,
+ TableAlignment, VisualLineKind,
};
use crate::quad::{QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};
+use crate::termwindow::remote_files::{
+ invalidate_remote_connection_if_dead, remote_connection_key, remote_connection_manager,
+ RemoteAcquireError, RemoteFileBytes, RemoteFileKind, RemoteFileRow, RemoteFilesEffect,
+ RemoteFilesEvent, RemoteFilesPhase, RemotePath,
+};
use crate::termwindow::ui::icons::{
- MaterialIcon, SvgIcon, material_file_icon_for_name, material_folder_icon_for_name,
+ material_file_icon_for_name, material_folder_icon_for_name, MaterialIcon, SvgIcon,
};
use crate::termwindow::ui::platform_chrome::uses_integrated_window_buttons;
use crate::termwindow::ui::tokens::{
@@ -27,7 +32,7 @@ use crate::termwindow::{
RightSidebarOpenWithCacheEntry, RightSidebarSnippetField, RightSidebarSnippetView,
TermWindowNotif, UIItem, UIItemType, UiShapeCacheLookup,
};
-use crate::ui::{TextInputState, UiPalette, scale_ui_usize, unscale_ui_usize};
+use crate::ui::{scale_ui_usize, unscale_ui_usize, EditModifiers, TextInputState, UiPalette};
use crate::utilsprites::RenderMetrics;
use crate::workspace_threads;
use anyhow::Context;
@@ -110,7 +115,11 @@ const NOTE_VAULT_RESCAN_SECS: u64 = 10;
// Points render 4/3 larger at 96dpi than on macOS, so the floor follows
// the same 0.75x rule as the default font sizes; otherwise it pins the
// Files panel above any reasonable Home Font Size setting on Linux.
-const FILE_FONT_MIN_SIZE: f64 = if cfg!(target_os = "macos") { 14.0 } else { 10.5 };
+const FILE_FONT_MIN_SIZE: f64 = if cfg!(target_os = "macos") {
+ 14.0
+} else {
+ 10.5
+};
const FILE_FILTER_HEIGHT: usize = 66;
const FILE_TREE_TOP_GAP: usize = 14;
const FILE_SCROLL_FADE_HEIGHT: usize = 32;
@@ -786,8 +795,7 @@ struct NotePaintProfile {
impl NotePaintProfile {
fn new() -> Self {
static ENABLED: OnceLock<bool> = OnceLock::new();
- let enabled =
- *ENABLED.get_or_init(|| std::env::var_os("THINKTERM_PROFILE_NOTE").is_some());
+ let enabled = *ENABLED.get_or_init(|| std::env::var_os("THINKTERM_PROFILE_NOTE").is_some());
Self {
enabled,
start: enabled.then(Instant::now),
@@ -928,7 +936,8 @@ impl crate::TermWindow {
!self.right_sidebar_collapsed
&& self.right_sidebar_mode == RightSidebarMode::Chat
&& self.right_sidebar_file_view == RightSidebarFileView::Preview
- && self.right_sidebar_file_selected.is_some()
+ && (self.right_sidebar_file_selected.is_some()
+ || self.right_sidebar_remote_files.selected.is_some())
}
fn right_sidebar_tree_width(&self) -> usize {
@@ -968,7 +977,8 @@ impl crate::TermWindow {
if self.right_sidebar_collapsed
|| self.right_sidebar_mode != RightSidebarMode::Chat
|| self.right_sidebar_file_view != RightSidebarFileView::Preview
- || self.right_sidebar_file_selected.is_none()
+ || (self.right_sidebar_file_selected.is_none()
+ && self.right_sidebar_remote_files.selected.is_none())
{
return None;
}
@@ -1159,9 +1169,11 @@ impl crate::TermWindow {
self.clear_right_sidebar_text_focus();
}
self.schedule_right_sidebar_file_memory_release();
+ self.release_right_sidebar_remote_files_if_hidden();
self.schedule_right_sidebar_note_memory_release();
} else {
self.kick_right_sidebar_file_rescan_cycle();
+ self.request_right_sidebar_remote_files_connect(false);
if self.right_sidebar_mode == RightSidebarMode::Tasks {
self.right_sidebar_note_memory_release_token =
self.right_sidebar_note_memory_release_token.wrapping_add(1);
@@ -1172,6 +1184,7 @@ impl crate::TermWindow {
pub fn expand_right_sidebar(&mut self) {
self.right_sidebar_collapsed = false;
self.kick_right_sidebar_file_rescan_cycle();
+ self.request_right_sidebar_remote_files_connect(false);
if self.right_sidebar_mode == RightSidebarMode::Tasks {
self.right_sidebar_note_memory_release_token =
self.right_sidebar_note_memory_release_token.wrapping_add(1);
@@ -1463,12 +1476,12 @@ impl crate::TermWindow {
}
pub(crate) fn save_snippet_editor(&mut self) {
- let body = self.right_sidebar_snippet_body.text.trim().to_string();
+ let body = self.right_sidebar_snippet_body.text().trim().to_string();
if body.is_empty() {
self.right_sidebar_snippet_focus = Some(RightSidebarSnippetField::Body);
return;
}
- let title = self.right_sidebar_snippet_title.text.trim().to_string();
+ let title = self.right_sidebar_snippet_title.text().trim().to_string();
let result = match self.right_sidebar_snippet_view.clone() {
RightSidebarSnippetView::List => return,
RightSidebarSnippetView::EditNew => {
@@ -1527,10 +1540,14 @@ impl crate::TermWindow {
}
pub(crate) fn scroll_right_sidebar_files_by(&mut self, delta: f32) -> bool {
- let old = self.right_sidebar_file_tree_scroll_offset;
- self.right_sidebar_file_tree_scroll_offset =
- (self.right_sidebar_file_tree_scroll_offset + delta).max(0.0);
- (old - self.right_sidebar_file_tree_scroll_offset).abs() > f32::EPSILON
+ let offset = if self.right_sidebar_remote_files.target.is_some() {
+ &mut self.right_sidebar_remote_file_tree_scroll_offset
+ } else {
+ &mut self.right_sidebar_file_tree_scroll_offset
+ };
+ let old = *offset;
+ *offset = (*offset + delta).max(0.0);
+ (old - *offset).abs() > f32::EPSILON
}
pub(crate) fn scroll_right_sidebar_file_preview_by(&mut self, delta: f32) -> bool {
@@ -1545,7 +1562,8 @@ impl crate::TermWindow {
if self.right_sidebar_collapsed
|| self.right_sidebar_mode != RightSidebarMode::Chat
|| self.right_sidebar_file_view != RightSidebarFileView::Preview
- || self.right_sidebar_file_selected.is_none()
+ || (self.right_sidebar_file_selected.is_none()
+ && self.right_sidebar_remote_files.selected.is_none())
|| amount == 0
{
return false;
@@ -2331,7 +2349,11 @@ impl crate::TermWindow {
text.push_str(&preview_text_range(&line.plain, line_start, line_end));
}
}
- if text.is_empty() { None } else { Some(text) }
+ if text.is_empty() {
+ None
+ } else {
+ Some(text)
+ }
}
fn right_sidebar_file_preview_selection_range(
@@ -2440,7 +2462,7 @@ impl crate::TermWindow {
fn mark_right_sidebar_file_filter_changed(&mut self) {
self.right_sidebar_file_tree_scroll_offset = 0.0;
- if self.right_sidebar_file_filter.text == self.right_sidebar_file_applied_filter {
+ if self.right_sidebar_file_filter.text() == self.right_sidebar_file_applied_filter {
self.right_sidebar_file_filter_debounce_until = None;
} else {
self.right_sidebar_file_filter_debounce_until =
@@ -2449,7 +2471,7 @@ impl crate::TermWindow {
}
fn right_sidebar_file_filter_for_tree(&mut self) -> String {
- let current = self.right_sidebar_file_filter.text.clone();
+ let current = self.right_sidebar_file_filter.text().to_string();
if current == self.right_sidebar_file_applied_filter {
self.right_sidebar_file_filter_debounce_until = None;
return self.right_sidebar_file_applied_filter.clone();
@@ -2661,6 +2683,9 @@ impl crate::TermWindow {
/// keeping the tree + view state on screen. Used by the periodic timer,
/// window/panel focus, and the manual Refresh button.
pub(crate) fn force_right_sidebar_file_rescan(&mut self) {
+ if matches!(self.active_remote_project_for_files(), Ok(Some(_))) {
+ return;
+ }
if !self.right_sidebar_file_view_active() || self.right_sidebar_file_refreshing {
return;
}
@@ -2686,6 +2711,9 @@ impl crate::TermWindow {
/// re-scan cycle. Called on window focus and when entering the file view; a
/// fresh open builds via the normal index path, so we only force when Ready.
pub(crate) fn kick_right_sidebar_file_rescan_cycle(&mut self) {
+ if matches!(self.active_remote_project_for_files(), Ok(Some(_))) {
+ return;
+ }
if !(self.right_sidebar_file_view_active() && self.focused.is_some()) {
return;
}
@@ -2707,6 +2735,9 @@ impl crate::TermWindow {
/// Schedule the next periodic re-scan tick (token-guarded so close / blur /
/// root change makes a pending tick a no-op and the cycle stops).
pub(crate) fn schedule_right_sidebar_file_rescan(&mut self) {
+ if matches!(self.active_remote_project_for_files(), Ok(Some(_))) {
+ return;
+ }
let Some(window) = self.window.as_ref().cloned() else {
return;
};
@@ -2730,6 +2761,9 @@ impl crate::TermWindow {
{
return;
}
+ if matches!(self.active_remote_project_for_files(), Ok(Some(_))) {
+ return;
+ }
self.force_right_sidebar_file_rescan();
self.schedule_right_sidebar_file_rescan();
}
@@ -2895,7 +2929,7 @@ impl crate::TermWindow {
};
let text = input
.caret_selected_text()
- .unwrap_or_else(|| input.text.clone());
+ .unwrap_or_else(|| input.text().to_string());
if !text.is_empty() {
self.copy_to_clipboard(destination, text);
}
@@ -3334,7 +3368,7 @@ impl crate::TermWindow {
let text = if let Some(text) = input.caret_take_selected_text() {
text
} else {
- let text = input.text.clone();
+ let text = input.text().to_string();
input.clear();
text
};
@@ -3389,87 +3423,93 @@ impl crate::TermWindow {
return false;
}
- let shift = mods.contains(TermModifiers::SHIFT);
- let super_ = mods.contains(TermModifiers::SUPER);
- let alt = mods.contains(TermModifiers::ALT);
- let ctrl = mods.contains(TermModifiers::CTRL);
+ // Resolved once, platform-normalized: ⌘ on macOS, Ctrl on
+ // Windows/Linux. Testing raw modifiers here is what left these inputs
+ // macOS-only while the Note editor next door worked everywhere.
+ let edit = EditModifiers::from(mods);
+ let shift = edit.shift;
let multiline = self.right_sidebar_focused_is_multiline();
if self.right_sidebar_mode == RightSidebarMode::Tasks {
return self.handle_right_sidebar_note_key(key, mods);
}
- // Cmd shortcuts (macOS): clipboard, select-all, jump to line start/end.
- if super_ && !alt && !ctrl {
- return match key {
+ // Clipboard and select-all. Deliberately falls through rather than
+ // returning on an unhandled key: off macOS the same Ctrl chord is also
+ // the word modifier, which is handled just below.
+ if edit.command {
+ match key {
TermKeyCode::Char('a') | TermKeyCode::Char('A') => {
if let Some(input) = self.right_sidebar_focused_input_mut() {
input.caret_select_all();
}
- true
+ return true;
}
TermKeyCode::Char('c') | TermKeyCode::Char('C') => {
self.copy_right_sidebar_focused_input(ClipboardCopyDestination::Clipboard);
- true
+ return true;
}
TermKeyCode::Char('x') | TermKeyCode::Char('X') => {
self.cut_right_sidebar_focused_input();
- true
+ return true;
}
TermKeyCode::Char('v') | TermKeyCode::Char('V') => {
self.paste_into_right_sidebar_from_clipboard(ClipboardPasteSource::Clipboard);
- true
+ return true;
}
- TermKeyCode::LeftArrow if !multiline => {
+ // ⌘←/→/⌫ are line-start/end/delete-to-start on macOS only;
+ // elsewhere Home/End cover it and Ctrl means word-wise.
+ TermKeyCode::LeftArrow if !multiline && cfg!(target_os = "macos") => {
if let Some(input) = self.right_sidebar_focused_input_mut() {
input.caret_move_home(shift);
}
- true
+ return true;
}
- TermKeyCode::RightArrow if !multiline => {
+ TermKeyCode::RightArrow if !multiline && cfg!(target_os = "macos") => {
if let Some(input) = self.right_sidebar_focused_input_mut() {
input.caret_move_end(shift);
}
- true
+ return true;
}
- TermKeyCode::Backspace if !multiline => {
+ TermKeyCode::Backspace if !multiline && cfg!(target_os = "macos") => {
if let Some(input) = self.right_sidebar_focused_input_mut() {
input.caret_delete_to_start();
}
self.after_right_sidebar_text_edit();
- true
+ return true;
}
- _ => false,
- };
+ _ => {}
+ }
}
- // Option/Alt shortcuts (macOS): word navigation / deletion.
- if alt && !super_ && !ctrl {
- return match key {
+ // Word navigation / deletion (⌥ on macOS, Ctrl elsewhere).
+ if edit.word {
+ match key {
TermKeyCode::LeftArrow if !multiline => {
if let Some(input) = self.right_sidebar_focused_input_mut() {
input.caret_word_left(shift);
}
- true
+ return true;
}
TermKeyCode::RightArrow if !multiline => {
if let Some(input) = self.right_sidebar_focused_input_mut() {
input.caret_word_right(shift);
}
- true
+ return true;
}
TermKeyCode::Backspace if !multiline => {
if let Some(input) = self.right_sidebar_focused_input_mut() {
input.caret_delete_word_back();
}
self.after_right_sidebar_text_edit();
- true
+ return true;
}
- _ => false,
- };
+ _ => {}
+ }
}
- if ctrl {
+ // Any chord we did not claim belongs to the app, not to this input.
+ if !edit.plain() {
return false;
}
@@ -3630,16 +3670,18 @@ impl crate::TermWindow {
// begin_live_editing() is deliberately deferred until a key is known
// to be handled: an unrelated key must not flip the display source to
// Live and invalidate the projection caches.
- let shift = mods.contains(TermModifiers::SHIFT);
+ // This handler is where the correct cross-platform rule was first
+ // written; it now lives in `EditModifiers` so every text surface shares
+ // it. `command` stays slightly looser than the shared flag here because
+ // the editor also accepts ⌘ chords that arrive alongside other
+ // modifiers.
+ let edit = EditModifiers::from(mods);
+ let shift = edit.shift;
let super_ = mods.contains(TermModifiers::SUPER);
let ctrl = mods.contains(TermModifiers::CTRL);
let alt = mods.contains(TermModifiers::ALT);
let command = super_ || (ctrl && !cfg!(target_os = "macos"));
- let word_modifier = if cfg!(target_os = "macos") {
- alt && !super_ && !ctrl
- } else {
- ctrl && !super_ && !alt
- };
+ let word_modifier = edit.word;
if word_modifier
&& matches!(
@@ -4543,7 +4585,7 @@ impl crate::TermWindow {
.find(|layout| &layout.item_type == item_type)?;
let input = self.right_sidebar_input_for_item(item_type)?;
let font = layout.font.clone();
- let chars: Vec<char> = input.text.chars().collect();
+ let chars: Vec<char> = input.text().chars().collect();
let first = layout.first_char.min(chars.len());
let relative = (x as f32 - layout.text_x).clamp(0.0, layout.text_width.max(0.0));
let mut best_idx = first;
@@ -4860,7 +4902,8 @@ impl crate::TermWindow {
preview_metrics: RenderMetrics,
) -> Option<RightSidebarFilePreviewBodyMetrics> {
if self.right_sidebar_file_view != RightSidebarFileView::Preview
- || self.right_sidebar_file_selected.is_none()
+ || (self.right_sidebar_file_selected.is_none()
+ && self.right_sidebar_remote_files.selected.is_none())
{
return None;
}
@@ -5223,7 +5266,7 @@ impl crate::TermWindow {
fn filtered_snippet_count(&self) -> usize {
let needle = self
.right_sidebar_snippet_search
- .text
+ .text()
.trim()
.to_ascii_lowercase();
crate::snippets::list_snippets()
@@ -5262,7 +5305,9 @@ impl crate::TermWindow {
let icon_size = (ui_cell_height + self.ui_px(6)).clamp(self.ui_px(20), self.ui_px(24));
if self.right_sidebar_mode == RightSidebarMode::Chat {
- let _ = self.sync_right_sidebar_file_root_for_current_workspace();
+ if !matches!(self.active_remote_project_for_files(), Ok(Some(_))) {
+ let _ = self.sync_right_sidebar_file_root_for_current_workspace();
+ }
}
if let Some(preview_rect) = self.right_sidebar_file_preview_rect() {
@@ -6924,10 +6969,9 @@ impl crate::TermWindow {
let mut top = padding;
// Reuse the previous geometry allocation when this host holds the
// only reference (paint-local clones are dropped each frame).
- let mut geometry = Arc::try_unwrap(std::mem::take(
- &mut self.right_sidebar_note.line_geometry,
- ))
- .unwrap_or_default();
+ let mut geometry =
+ Arc::try_unwrap(std::mem::take(&mut self.right_sidebar_note.line_geometry))
+ .unwrap_or_default();
geometry.clear();
geometry.reserve(visual.lines.len());
for (line_index, line) in visual.lines.iter().enumerate() {
@@ -7044,7 +7088,8 @@ impl crate::TermWindow {
// frame and the capacities are stable.
let mut layouts = std::mem::take(&mut self.right_sidebar_note.line_layouts);
layouts.clear();
- let mut code_block_layouts = std::mem::take(&mut self.right_sidebar_note.code_block_layouts);
+ let mut code_block_layouts =
+ std::mem::take(&mut self.right_sidebar_note.code_block_layouts);
code_block_layouts.clear();
let mut table_layouts = std::mem::take(&mut self.right_sidebar_note_table_layouts);
table_layouts.clear();
@@ -8431,6 +8476,46 @@ impl crate::TermWindow {
content_bottom: usize,
icon_size: usize,
) -> anyhow::Result<()> {
+ if let Some(target) = self
+ .active_remote_project_for_files()
+ .map_err(anyhow::Error::msg)?
+ {
+ let changed = self.right_sidebar_remote_files.target.as_ref() != Some(&target);
+ if changed {
+ self.clear_right_sidebar_text_focus();
+ self.right_sidebar_remote_file_tree_scroll_offset = 0.0;
+ }
+ let effects = self
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::TargetChanged(Some(target)));
+ self.apply_right_sidebar_remote_files_effects(effects);
+ if changed && self.right_sidebar_remote_files.can_resume_current() {
+ let effects = self
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::ResumeRequested);
+ self.apply_right_sidebar_remote_files_effects(effects);
+ }
+ return self.paint_remote_files_sidebar(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ foreground,
+ muted_fg,
+ content_x,
+ content_top,
+ content_width,
+ content_bottom,
+ icon_size,
+ );
+ }
+
+ if self.right_sidebar_remote_files.target.is_some() {
+ let effects = self
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::TargetChanged(None));
+ self.apply_right_sidebar_remote_files_effects(effects);
+ }
self.paint_files_tree(
layers,
ui_font,
@@ -8446,38 +8531,8 @@ impl crate::TermWindow {
)
}
- fn active_local_project_for_files(&self) -> Result<RightSidebarFileRoot, String> {
- let mux = Mux::get();
- let active_workspace = self
- .current_mux_workspace()
- .unwrap_or_else(|| mux.active_workspace());
- let workspaces = mux.iter_workspaces();
- let view = workspace_threads::view_for_current_project(
- &self.active_space_id,
- &active_workspace,
- &workspaces,
- );
- let project = view
- .projects
- .iter()
- .find(|project| project.is_active)
- .or_else(|| view.projects.first())
- .ok_or_else(|| "No active project".to_string())?;
-
- if project.is_remote {
- return Err("Remote file browsing is not supported yet".to_string());
- }
-
- let path = workspace_threads::project_reveal_path(&project.id)
- .ok_or_else(|| "Project folder is unavailable".to_string())?;
- Ok(RightSidebarFileRoot {
- project_name: project.name.clone(),
- path,
- })
- }
-
#[allow(clippy::too_many_arguments)]
- fn paint_files_tree(
+ fn paint_remote_files_sidebar(
&mut self,
layers: &mut TripleLayerQuadAllocator,
ui_font: &Rc<LoadedFont>,
@@ -8491,164 +8546,1081 @@ impl crate::TermWindow {
content_bottom: usize,
icon_size: usize,
) -> anyhow::Result<()> {
- // Reserve room on the right for an icon-only Refresh button so it never
- // eats into the filename/search width.
- let refresh_size = (ui_metrics.cell_size.height as usize + self.ui_px(12))
- .clamp(self.ui_px(28), self.ui_px(38));
- let refresh_gap = self.ui_px(SIDEBAR_INSET);
- let filter_width = content_width.saturating_sub(refresh_size + refresh_gap);
- let refresh_x = content_x + content_width - refresh_size;
- let refresh_y =
- content_top + self.ui_px(FILE_FILTER_HEIGHT).saturating_sub(refresh_size) / 2;
-
- let filter_input = self.right_sidebar_file_filter.clone();
- self.paint_snippet_text_box(
- layers,
- 1,
- ui_font,
- ui_metrics,
- chrome,
- muted_fg,
- content_x,
- content_top,
- filter_width,
- self.ui_px(FILE_FILTER_HEIGHT),
- Some(SvgIcon::Search),
- "Filter files",
- &filter_input,
- self.right_sidebar_file_focus == Some(RightSidebarFileField::Filter),
- UIItemType::RightSidebarFileFilter,
- false,
- )?;
- self.paint_files_preview_header_icon_button(
- layers,
- chrome,
- foreground,
- muted_fg,
- refresh_x,
- refresh_y,
- refresh_size,
- SvgIcon::RotateCcw,
- UIItemType::RightSidebarFileRefresh,
- )?;
-
- let tree_top = content_top + self.ui_px(FILE_FILTER_HEIGHT) + self.ui_px(FILE_TREE_TOP_GAP);
- let root = match self.sync_right_sidebar_file_root_for_current_workspace() {
- Ok(root) => root,
- Err(message) => {
- return self.paint_files_message(
+ let phase = self.right_sidebar_remote_files.phase.clone();
+ match phase {
+ RemoteFilesPhase::Disconnected => {
+ self.paint_files_message(
layers,
ui_font,
ui_metrics,
chrome,
muted_fg,
content_x,
- tree_top,
+ content_top,
content_width,
content_bottom,
icon_size,
- &message,
- );
+ "Connect to browse this remote project",
+ )?;
+ self.paint_remote_files_connect_button(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ foreground,
+ content_x,
+ content_top + self.ui_px(RIGHT_SIDEBAR_EMPTY_HEIGHT + 12),
+ content_width,
+ "Connect to Remote Files",
+ )
}
- };
- if self
- .right_sidebar_file_expanded
- .insert(path_key(&root.path))
- {
- self.right_sidebar_file_expanded_version =
- self.right_sidebar_file_expanded_version.wrapping_add(1);
- }
-
- let applied_filter = self.right_sidebar_file_filter_for_tree();
- let index = match self.right_sidebar_file_index_status.clone() {
- RightSidebarFileIndexStatus::Ready => match self.right_sidebar_file_index.clone() {
- Some(index) => index,
- None => {
- return self.paint_files_message(
- layers,
- ui_font,
- ui_metrics,
- chrome,
- muted_fg,
- content_x,
- tree_top,
- content_width,
- content_bottom,
- icon_size,
- "Indexing files...",
- );
- }
- },
- RightSidebarFileIndexStatus::Failed(message) => {
- return self.paint_files_message(
+ RemoteFilesPhase::Connecting => self.paint_files_message(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ muted_fg,
+ content_x,
+ content_top,
+ content_width,
+ content_bottom,
+ icon_size,
+ "Connecting to Remote Files...",
+ ),
+ RemoteFilesPhase::Failed(message) => {
+ self.paint_files_message(
layers,
ui_font,
ui_metrics,
chrome,
muted_fg,
content_x,
- tree_top,
+ content_top,
content_width,
content_bottom,
icon_size,
&message,
- );
- }
- RightSidebarFileIndexStatus::Empty | RightSidebarFileIndexStatus::Indexing => {
- return self.paint_files_message(
+ )?;
+ self.paint_remote_files_connect_button(
layers,
ui_font,
ui_metrics,
chrome,
- muted_fg,
+ foreground,
content_x,
- tree_top,
+ content_top + self.ui_px(RIGHT_SIDEBAR_EMPTY_HEIGHT + 12),
content_width,
- content_bottom,
- icon_size,
- "Indexing files...",
- );
+ "Retry",
+ )
}
- };
-
- let query = applied_filter.trim().to_string();
- self.start_right_sidebar_file_search_if_needed(&query);
- let row_count = if query.is_empty() {
- self.refresh_right_sidebar_file_browse_rows(&index);
- self.right_sidebar_file_browse_rows.len()
- } else {
- self.right_sidebar_file_search_rows.len()
- };
-
- if row_count == 0 && self.right_sidebar_file_searching {
- return self.paint_files_message(
+ RemoteFilesPhase::Connected => self.paint_remote_files_tree(
layers,
ui_font,
ui_metrics,
chrome,
+ foreground,
muted_fg,
content_x,
- tree_top,
+ content_top,
content_width,
content_bottom,
- icon_size,
- "Searching files...",
- );
+ ),
}
+ }
- if row_count == 0 && !query.is_empty() {
- return self.paint_files_message(
- layers,
- ui_font,
- ui_metrics,
- chrome,
- muted_fg,
- content_x,
- tree_top,
- content_width,
- content_bottom,
- icon_size,
- "No matching files",
+ #[allow(clippy::too_many_arguments)]
+ fn paint_remote_files_connect_button(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator,
+ ui_font: &Rc<LoadedFont>,
+ ui_metrics: RenderMetrics,
+ chrome: UiPalette,
+ foreground: LinearRgba,
+ x: usize,
+ y: usize,
+ width: usize,
+ label: &str,
+ ) -> anyhow::Result<()> {
+ let height = self.ui_px(44);
+ let hovered = self.is_pointer_over_ui_rect(x, y, width, height);
+ self.fill_rounded_rectangle_with_border(
+ layers,
+ 1,
+ euclid::rect(x as f32, y as f32, width as f32, height as f32),
+ if hovered {
+ chrome.control_hover_bg
+ } else {
+ chrome.sidebar_button_bg
+ },
+ chrome.control_border,
+ self.ui_f32(SIDEBAR_ROW_RADIUS) + 4.0,
+ CAPSULE_BORDER_WIDTH,
+ )
+ .context("remote Files connect button")?;
+ self.ui_items.push(UIItem {
+ x,
+ y,
+ width,
+ height,
+ item_type: UIItemType::RightSidebarRemoteFileConnect,
+ });
+ let label_width = self
+ .sidebar_text_width(ui_font, label)
+ .unwrap_or(width as f32)
+ .ceil() as usize;
+ let text_x = x + width.saturating_sub(label_width) / 2;
+ self.paint_sidebar_text(
+ layers,
+ ui_font,
+ ui_metrics,
+ label,
+ text_x,
+ y + height.saturating_sub(ui_metrics.cell_size.height as usize) / 2,
+ width.saturating_sub(text_x.saturating_sub(x)),
+ foreground,
+ )
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn paint_remote_files_tree(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator,
+ ui_font: &Rc<LoadedFont>,
+ ui_metrics: RenderMetrics,
+ chrome: UiPalette,
+ foreground: LinearRgba,
+ muted_fg: LinearRgba,
+ content_x: usize,
+ content_top: usize,
+ content_width: usize,
+ content_bottom: usize,
+ ) -> anyhow::Result<()> {
+ let refresh_size = (ui_metrics.cell_size.height as usize + self.ui_px(12))
+ .clamp(self.ui_px(28), self.ui_px(38));
+ let refresh_x = content_x + content_width.saturating_sub(refresh_size);
+ let refresh_y =
+ content_top + self.ui_px(FILE_FILTER_HEIGHT).saturating_sub(refresh_size) / 2;
+ let label_width = content_width.saturating_sub(refresh_size + self.ui_px(SIDEBAR_INSET));
+ let label = self
+ .right_sidebar_remote_files
+ .target
+ .as_ref()
+ .map(|target| target.project_name.as_str())
+ .unwrap_or("Remote Files");
+ self.paint_sidebar_text(
+ layers,
+ ui_font,
+ ui_metrics,
+ label,
+ content_x,
+ content_top
+ + self
+ .ui_px(FILE_FILTER_HEIGHT)
+ .saturating_sub(ui_metrics.cell_size.height as usize)
+ / 2,
+ label_width,
+ foreground,
+ )?;
+ self.paint_files_preview_header_icon_button(
+ layers,
+ chrome,
+ foreground,
+ muted_fg,
+ refresh_x,
+ refresh_y,
+ refresh_size,
+ SvgIcon::RotateCcw,
+ UIItemType::RightSidebarRemoteFileRefresh,
+ )?;
+
+ let mut tree_top =
+ content_top + self.ui_px(FILE_FILTER_HEIGHT) + self.ui_px(FILE_TREE_TOP_GAP);
+ if let Some(message) = self.right_sidebar_remote_files.error_message.clone() {
+ self.paint_sidebar_text(
+ layers,
+ ui_font,
+ ui_metrics,
+ &message,
+ content_x,
+ tree_top,
+ content_width,
+ muted_fg,
+ )?;
+ tree_top += ui_metrics.cell_size.height as usize + self.ui_px(8);
+ }
+ let rows = self.right_sidebar_remote_files.rows();
+ if rows.is_empty() {
+ return self.paint_files_message(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ muted_fg,
+ content_x,
+ tree_top,
+ content_width,
+ content_bottom,
+ self.ui_px(22),
+ "Loading remote directory...",
+ );
+ }
+
+ let row_metrics = right_sidebar_file_row_metrics(ui_metrics);
+ let footer_height = if self.right_sidebar_remote_files.has_truncated_directory() {
+ row_metrics.row_height
+ } else {
+ 0
+ };
+ let viewport_bottom = content_bottom
+ .saturating_sub(self.ui_px(SIDEBAR_INSET))
+ .saturating_sub(footer_height);
+ let visible_height = viewport_bottom.saturating_sub(tree_top);
+ let total_height = rows.len().saturating_mul(row_metrics.row_height);
+ let max_scroll = total_height.saturating_sub(visible_height) as f32;
+ self.right_sidebar_remote_file_tree_scroll_offset = self
+ .right_sidebar_remote_file_tree_scroll_offset
+ .clamp(0.0, max_scroll);
+ let scroll = self.right_sidebar_remote_file_tree_scroll_offset;
+ let visible =
+ visible_file_row_range(rows.len(), scroll, visible_height, row_metrics.row_height);
+ let selected = self.right_sidebar_remote_files.selected.clone();
+ for (offset, row) in rows.get(visible.clone()).unwrap_or(&[]).iter().enumerate() {
+ let index = visible.start + offset;
+ let row_top = match file_row_placement(
+ index,
+ row_metrics.row_height,
+ tree_top as f32,
+ viewport_bottom as f32,
+ scroll,
+ ) {
+ FileRowPlacement::Above => continue,
+ FileRowPlacement::Below => break,
+ FileRowPlacement::Visible(row_top) => row_top,
+ };
+ self.paint_remote_file_tree_row(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ foreground,
+ muted_fg,
+ content_x,
+ row_top.floor().max(0.0) as usize,
+ content_width,
+ row,
+ selected.as_ref(),
+ tree_top,
+ viewport_bottom,
+ row_metrics,
+ )?;
+ }
+ if footer_height > 0 {
+ self.paint_sidebar_text(
+ layers,
+ ui_font,
+ ui_metrics,
+ "More entries are not shown",
+ content_x,
+ viewport_bottom,
+ content_width,
+ muted_fg,
+ )?;
+ }
+ Ok(())
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn paint_remote_file_tree_row(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator,
+ ui_font: &Rc<LoadedFont>,
+ ui_metrics: RenderMetrics,
+ chrome: UiPalette,
+ foreground: LinearRgba,
+ muted_fg: LinearRgba,
+ x: usize,
+ y: usize,
+ width: usize,
+ row: &RemoteFileRow,
+ selected: Option<&RemotePath>,
+ clip_top: usize,
+ clip_bottom: usize,
+ row_metrics: RightSidebarFileRowMetrics,
+ ) -> anyhow::Result<()> {
+ let row_bottom = y.saturating_add(row_metrics.row_height);
+ let visible_y = y.max(clip_top);
+ let visible_bottom = row_bottom.min(clip_bottom);
+ let visible_height = visible_bottom.saturating_sub(visible_y);
+ if visible_height == 0 {
+ return Ok(());
+ }
+ let hovered = self.is_pointer_over_ui_rect(x, visible_y, width, visible_height);
+ let is_selected = selected == Some(&row.entry.path);
+ if hovered || is_selected {
+ self.fill_rounded_rectangle(
+ layers,
+ 1,
+ euclid::rect(
+ x as f32,
+ visible_y as f32,
+ width as f32,
+ visible_height as f32,
+ ),
+ if is_selected {
+ chrome.selected_bg.mul_alpha(0.46)
+ } else {
+ chrome.sidebar_button_hover_bg
+ },
+ self.ui_f32(SIDEBAR_ROW_RADIUS),
+ )
+ .context("remote Files row hover")?;
+ }
+ self.ui_items.push(UIItem {
+ x,
+ y: visible_y,
+ width,
+ height: visible_height,
+ item_type: UIItemType::RightSidebarRemoteFileRow(row.entry.path.clone()),
+ });
+
+ let indent = row
+ .depth
+ .saturating_mul(row_metrics.indent_step)
+ .min(width.saturating_sub(24));
+ let chevron_x = x + self.ui_px(SIDEBAR_INSET) + indent;
+ let chevron_y = y + row_metrics
+ .row_height
+ .saturating_sub(row_metrics.chevron_size)
+ / 2;
+ if row.entry.is_directory() {
+ self.paint_sidebar_icon(
+ layers,
+ if row.expanded {
+ SvgIcon::ChevronDown
+ } else {
+ SvgIcon::ChevronRight
+ },
+ chevron_x,
+ chevron_y,
+ row_metrics.chevron_size,
+ muted_fg,
+ )?;
+ }
+ let icon_x = chevron_x + row_metrics.chevron_size + row_metrics.icon_gap;
+ let icon_y = y + row_metrics.row_height.saturating_sub(row_metrics.icon_size) / 2;
+ let icon = remote_file_icon(row);
+ match icon {
+ RightSidebarFileIcon::Material(icon) => {
+ self.paint_sidebar_material_icon(
+ layers,
+ icon,
+ icon_x,
+ icon_y,
+ row_metrics.icon_size,
+ )?;
+ }
+ RightSidebarFileIcon::Svg(icon) => {
+ self.paint_sidebar_icon(
+ layers,
+ icon,
+ icon_x,
+ icon_y,
+ row_metrics.icon_size,
+ if row.entry.is_directory() {
+ muted_fg
+ } else {
+ foreground
+ },
+ )?;
+ }
+ }
+ let text_x = icon_x + row_metrics.icon_size + row_metrics.icon_gap;
+ self.paint_sidebar_text(
+ layers,
+ ui_font,
+ ui_metrics,
+ &row.entry.name,
+ text_x,
+ y + row_metrics
+ .row_height
+ .saturating_sub(ui_metrics.cell_size.height as usize)
+ / 2,
+ x.saturating_add(width)
+ .saturating_sub(text_x + self.ui_px(SIDEBAR_INSET)),
+ if row.entry.is_directory() || is_selected {
+ foreground
+ } else {
+ muted_fg
+ },
+ )
+ }
+
+ fn active_remote_project_for_files(
+ &self,
+ ) -> Result<Option<workspace_threads::RemoteFilesTarget>, String> {
+ let mux = Mux::get();
+ let active_workspace = self
+ .current_mux_workspace()
+ .unwrap_or_else(|| mux.active_workspace());
+ let workspaces = mux.iter_workspaces();
+ let view = workspace_threads::view_for_current_project(
+ &self.active_space_id,
+ &active_workspace,
+ &workspaces,
+ );
+ let project = view
+ .projects
+ .iter()
+ .find(|project| project.is_active)
+ .or_else(|| view.projects.first())
+ .ok_or_else(|| "No active project".to_string())?;
+ if !project.is_remote {
+ return Ok(None);
+ }
+ if let Some(target) =
+ workspace_threads::remote_files_target(&self.active_space_id, &project.id)
+ {
+ return Ok(Some(target));
+ }
+ let Some(domain) = workspace_threads::client_domain_for_space(&self.active_space_id) else {
+ return Err("Remote Files source is unavailable".to_string());
+ };
+ Ok(Some(workspace_threads::RemoteFilesTarget {
+ project_id: project.id.clone(),
+ project_name: project.name.clone(),
+ source: workspace_threads::RemoteFilesSource::ClientDomain(domain),
+ requested_root: "~".to_string(),
+ }))
+ }
+
+ fn ssh_config_for_remote_files_target(
+ target: &workspace_threads::RemoteFilesTarget,
+ ) -> Result<config::SshDomain, String> {
+ match &target.source {
+ workspace_threads::RemoteFilesSource::SshHost(host_id) => {
+ let spec = crate::ssh_hosts::host_spec(host_id)
+ .ok_or_else(|| format!("SSH host {host_id} is unavailable"))?;
+ let mut domain = crate::ssh_hosts::build_ssh_domain(&spec);
+ domain.stored_password = spec
+ .password
+ .as_deref()
+ .map(crate::secret::reveal)
+ .filter(|password| !password.is_empty());
+ Ok(domain)
+ }
+ workspace_threads::RemoteFilesSource::ClientDomain(domain_name) => {
+ let domain = Mux::get()
+ .get_domain_by_name(domain_name)
+ .ok_or_else(|| format!("Mux domain {domain_name} is unavailable"))?;
+ let client = domain
+ .downcast_ref::<wezterm_client::domain::ClientDomain>()
+ .ok_or_else(|| {
+ "Remote Files supports only SSH-backed mux domains".to_string()
+ })?;
+ client.ssh_domain_config().ok_or_else(|| {
+ "Remote Files does not support Unix or TLS mux domains".to_string()
+ })
+ }
+ }
+ }
+
+ fn apply_right_sidebar_remote_files_effects(&mut self, effects: Vec<RemoteFilesEffect>) {
+ for effect in effects {
+ match effect {
+ RemoteFilesEffect::ReleaseLease => {
+ self.right_sidebar_remote_files_lease.take();
+ self.close_right_sidebar_file_preview();
+ }
+ RemoteFilesEffect::Connect {
+ generation,
+ target,
+ allow_connect,
+ } => {
+ let config = match Self::ssh_config_for_remote_files_target(&target) {
+ Ok(config) => config,
+ Err(message) => {
+ self.right_sidebar_remote_files.transition(
+ RemoteFilesEvent::ConnectionFailed {
+ generation,
+ message,
+ },
+ );
+ continue;
+ }
+ };
+ let Some(window) = self.window.as_ref().cloned() else {
+ self.right_sidebar_remote_files.transition(
+ RemoteFilesEvent::ConnectionFailed {
+ generation,
+ message: "Window is unavailable".to_string(),
+ },
+ );
+ continue;
+ };
+ let source_key = crate::termwindow::remote_files::RemoteFilesState::source_key(
+ &target.source,
+ );
+ let connection_key = remote_connection_key(&source_key, &config);
+ let requested_root = target.requested_root.clone();
+ promise::spawn::spawn(async move {
+ let manager = remote_connection_manager();
+ let result = match manager
+ .acquire(connection_key.clone(), config, allow_connect)
+ .await
+ {
+ Ok(lease) => {
+ let backend = lease.backend();
+ match backend.resolve_root(requested_root).await {
+ Ok(root) => match backend
+ .list_directory(
+ root.clone(),
+ crate::termwindow::remote_files::REMOTE_FILE_TREE_ROW_LIMIT,
+ )
+ .await
+ {
+ Ok(listing) => Ok((lease, root, listing)),
+ Err(err) => {
+ invalidate_remote_connection_if_dead(
+ &connection_key,
+ &err,
+ );
+ Err(RemoteAcquireError::Failed(err))
+ }
+ },
+ Err(err) => {
+ invalidate_remote_connection_if_dead(
+ &connection_key,
+ &err,
+ );
+ Err(RemoteAcquireError::Failed(err))
+ }
+ }
+ }
+ Err(err) => Err(err),
+ };
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ match result {
+ Ok((lease, root, listing)) => {
+ let current = term_window
+ .right_sidebar_remote_files
+ .current_source_key();
+ if current.as_deref() != Some(source_key.as_str())
+ || term_window.right_sidebar_remote_files.generation
+ != generation
+ {
+ drop(lease);
+ return;
+ }
+ term_window.right_sidebar_remote_files_lease = Some(lease);
+ let effects = term_window.right_sidebar_remote_files.transition(
+ RemoteFilesEvent::Connected {
+ generation,
+ root,
+ listing,
+ },
+ );
+ term_window
+ .apply_right_sidebar_remote_files_effects(effects);
+ }
+ Err(RemoteAcquireError::NotConnected) => {
+ term_window.right_sidebar_remote_files.transition(
+ RemoteFilesEvent::ResumeUnavailable { generation },
+ );
+ }
+ Err(RemoteAcquireError::Failed(message)) => {
+ term_window.right_sidebar_remote_files.transition(
+ RemoteFilesEvent::ConnectionFailed {
+ generation,
+ message,
+ },
+ );
+ }
+ }
+ term_window.invalidate_window();
+ })));
+ })
+ .detach();
+ }
+ RemoteFilesEffect::ListDirectory {
+ generation,
+ source_key,
+ path,
+ limit,
+ } => {
+ let Some(lease) = self.right_sidebar_remote_files_lease.as_ref() else {
+ self.right_sidebar_remote_files_lease.take();
+ self.close_right_sidebar_file_preview();
+ self.right_sidebar_remote_files.transition(
+ RemoteFilesEvent::ConnectionFailed {
+ generation,
+ message: "Remote Files connection is no longer available"
+ .to_string(),
+ },
+ );
+ continue;
+ };
+ let Some(operation_lease) = lease.operation_lease() else {
+ self.right_sidebar_remote_files_lease.take();
+ self.close_right_sidebar_file_preview();
+ self.right_sidebar_remote_files.transition(
+ RemoteFilesEvent::ConnectionFailed {
+ generation,
+ message: "Remote Files connection is no longer available"
+ .to_string(),
+ },
+ );
+ continue;
+ };
+ let backend = lease.backend();
+ let connection_key = lease.connection_key().to_string();
+ let Some(window) = self.window.as_ref().cloned() else {
+ continue;
+ };
+ promise::spawn::spawn(async move {
+ let result = backend.list_directory(path.clone(), limit).await;
+ drop(operation_lease);
+ let connection_died = result.as_ref().is_err_and(|message| {
+ invalidate_remote_connection_if_dead(&connection_key, message)
+ });
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ if term_window
+ .right_sidebar_remote_files
+ .current_source_key()
+ .as_deref()
+ != Some(source_key.as_str())
+ {
+ return;
+ }
+ let event = match result {
+ Ok(listing) => RemoteFilesEvent::DirectoryLoaded {
+ generation,
+ path,
+ listing,
+ },
+ Err(message) if connection_died => {
+ term_window.right_sidebar_remote_files_lease.take();
+ term_window.close_right_sidebar_file_preview();
+ RemoteFilesEvent::ConnectionFailed {
+ generation,
+ message,
+ }
+ }
+ Err(message) => RemoteFilesEvent::DirectoryFailed {
+ generation,
+ path,
+ message,
+ },
+ };
+ let effects = term_window.right_sidebar_remote_files.transition(event);
+ term_window.apply_right_sidebar_remote_files_effects(effects);
+ term_window.invalidate_window();
+ })));
+ })
+ .detach();
+ }
+ RemoteFilesEffect::LoadPreview {
+ generation,
+ source_key,
+ path,
+ } => {
+ self.spawn_right_sidebar_remote_file_preview(generation, source_key, path);
+ }
+ }
+ }
+ }
+
+ pub(crate) fn request_right_sidebar_remote_files_connect(&mut self, explicit: bool) {
+ let event = if explicit {
+ RemoteFilesEvent::ConnectRequested
+ } else {
+ RemoteFilesEvent::ResumeRequested
+ };
+ let effects = self.right_sidebar_remote_files.transition(event);
+ self.apply_right_sidebar_remote_files_effects(effects);
+ }
+
+ pub(crate) fn refresh_right_sidebar_remote_files(&mut self) {
+ self.close_right_sidebar_file_preview();
+ let effects = self
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::Refresh);
+ self.apply_right_sidebar_remote_files_effects(effects);
+ }
+
+ pub(crate) fn open_right_sidebar_remote_file(&mut self, path: RemotePath) {
+ match self.right_sidebar_remote_files.kind_for_path(&path) {
+ Some(RemoteFileKind::Directory) => {
+ let effects = self
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::ToggleDirectory(path));
+ self.apply_right_sidebar_remote_files_effects(effects);
+ }
+ Some(RemoteFileKind::File) => {
+ if !self.right_sidebar_file_preview_active() {
+ let max_tree_for_preview = self
+ .right_sidebar_pane_total_max_width()
+ .saturating_sub(self.ui_px(FILE_PREVIEW_PANE_MIN_WIDTH))
+ .max(self.ui_px(RIGHT_SIDEBAR_MIN_WIDTH));
+ self.right_sidebar_file_tree_width = self
+ .right_sidebar_width
+ .clamp(self.ui_px(RIGHT_SIDEBAR_MIN_WIDTH), max_tree_for_preview);
+ }
+ self.close_right_sidebar_file_preview();
+ self.right_sidebar_file_view = RightSidebarFileView::Preview;
+ self.right_sidebar_file_preview_message =
+ Some("Loading remote file preview...".to_string());
+ let effects = self
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::SelectFile(path));
+ self.apply_right_sidebar_remote_files_effects(effects);
+ }
+ Some(RemoteFileKind::Symlink) | Some(RemoteFileKind::Other) | None => {}
+ }
+ }
+
+ pub(crate) fn close_right_sidebar_remote_file_preview(&mut self) {
+ self.close_right_sidebar_file_preview();
+ self.right_sidebar_remote_files
+ .transition(RemoteFilesEvent::ClosePreview);
+ }
+
+ pub(crate) fn release_right_sidebar_remote_files_if_hidden(&mut self) {
+ if self.right_sidebar_file_view_active() {
+ return;
+ }
+ let effects = self
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::PanelHidden);
+ self.apply_right_sidebar_remote_files_effects(effects);
+ }
+
+ fn spawn_right_sidebar_remote_file_preview(
+ &mut self,
+ generation: u64,
+ source_key: String,
+ path: RemotePath,
+ ) {
+ let Some(lease) = self.right_sidebar_remote_files_lease.as_ref() else {
+ self.right_sidebar_remote_files_lease.take();
+ self.close_right_sidebar_file_preview();
+ self.right_sidebar_remote_files
+ .transition(RemoteFilesEvent::ConnectionFailed {
+ generation,
+ message: "Remote Files connection is no longer available".to_string(),
+ });
+ return;
+ };
+ let Some(operation_lease) = lease.operation_lease() else {
+ self.right_sidebar_remote_files_lease.take();
+ self.close_right_sidebar_file_preview();
+ self.right_sidebar_remote_files
+ .transition(RemoteFilesEvent::ConnectionFailed {
+ generation,
+ message: "Remote Files connection is no longer available".to_string(),
+ });
+ return;
+ };
+ let backend = lease.backend();
+ let connection_key = lease.connection_key().to_string();
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+ let is_image = is_preview_image_extension(path.extension());
+ let limit = if is_image {
+ FILE_PREVIEW_IMAGE_MAX_BYTES
+ } else {
+ FILE_PREVIEW_MAX_BYTES
+ };
+ let use_dark_syntax_theme = matches!(
+ crate::native_settings::effective_appearance(),
+ window::Appearance::Dark | window::Appearance::DarkHighContrast
+ );
+ promise::spawn::spawn(async move {
+ let bytes = backend.read_file(path.clone(), limit).await;
+ drop(operation_lease);
+ let connection_died = bytes.as_ref().is_err_and(|message| {
+ invalidate_remote_connection_if_dead(&connection_key, message)
+ });
+ let preview_path = path.clone();
+ let result = match bytes {
+ Ok(bytes) => promise::spawn::spawn_into_new_thread(move || {
+ Ok(remote_preview_from_bytes(
+ &preview_path,
+ bytes,
+ use_dark_syntax_theme,
+ ))
+ })
+ .await
+ .unwrap_or_else(|err| RightSidebarLoadedFilePreview {
+ lines: Vec::new(),
+ image: None,
+ message: Some(format!("Unable to prepare remote preview: {err}")),
+ truncated: false,
+ }),
+ Err(err) => RightSidebarLoadedFilePreview {
+ lines: Vec::new(),
+ image: None,
+ message: Some(err),
+ truncated: false,
+ },
+ };
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ if term_window
+ .right_sidebar_remote_files
+ .current_source_key()
+ .as_deref()
+ != Some(source_key.as_str())
+ || term_window.right_sidebar_remote_files.generation != generation
+ || term_window.right_sidebar_remote_files.selected.as_ref() != Some(&path)
+ {
+ return;
+ }
+ let error = result.message.clone();
+ if connection_died {
+ term_window.right_sidebar_remote_files_lease.take();
+ term_window.close_right_sidebar_file_preview();
+ term_window.right_sidebar_remote_files.transition(
+ RemoteFilesEvent::ConnectionFailed {
+ generation,
+ message: error
+ .clone()
+ .unwrap_or_else(|| "Remote Files connection was lost".to_string()),
+ },
+ );
+ term_window.invalidate_window();
+ return;
+ }
+ term_window.right_sidebar_file_preview_lines = result.lines;
+ term_window.right_sidebar_file_preview_max_columns = term_window
+ .right_sidebar_file_preview_lines
+ .iter()
+ .map(|line| line.char_count)
+ .max()
+ .unwrap_or(0);
+ term_window.right_sidebar_file_preview_image = result.image;
+ term_window.right_sidebar_file_preview_message = result.message;
+ term_window.right_sidebar_file_preview_truncated = result.truncated;
+ term_window.clear_right_sidebar_file_preview_slice_cache();
+ term_window.right_sidebar_remote_files.transition(
+ RemoteFilesEvent::PreviewFinished {
+ generation,
+ path,
+ error,
+ },
+ );
+ term_window.invalidate_window();
+ })));
+ })
+ .detach();
+ }
+
+ fn active_local_project_for_files(&self) -> Result<RightSidebarFileRoot, String> {
+ if workspace_threads::client_domain_for_space(&self.active_space_id).is_some() {
+ return Err("Remote file browsing is not supported yet".to_string());
+ }
+
+ let mux = Mux::get();
+ let active_workspace = self
+ .current_mux_workspace()
+ .unwrap_or_else(|| mux.active_workspace());
+ let workspaces = mux.iter_workspaces();
+ let view = workspace_threads::view_for_current_project(
+ &self.active_space_id,
+ &active_workspace,
+ &workspaces,
+ );
+ let project = view
+ .projects
+ .iter()
+ .find(|project| project.is_active)
+ .or_else(|| view.projects.first())
+ .ok_or_else(|| "No active project".to_string())?;
+
+ if project.is_remote {
+ return Err("Remote file browsing is not supported yet".to_string());
+ }
+
+ let path = workspace_threads::project_reveal_path(&project.id)
+ .ok_or_else(|| "Project folder is unavailable".to_string())?;
+ Ok(RightSidebarFileRoot {
+ project_name: project.name.clone(),
+ path,
+ })
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn paint_files_tree(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator,
+ ui_font: &Rc<LoadedFont>,
+ ui_metrics: RenderMetrics,
+ chrome: UiPalette,
+ foreground: LinearRgba,
+ muted_fg: LinearRgba,
+ content_x: usize,
+ content_top: usize,
+ content_width: usize,
+ content_bottom: usize,
+ icon_size: usize,
+ ) -> anyhow::Result<()> {
+ // Reserve room on the right for an icon-only Refresh button so it never
+ // eats into the filename/search width.
+ let refresh_size = (ui_metrics.cell_size.height as usize + self.ui_px(12))
+ .clamp(self.ui_px(28), self.ui_px(38));
+ let refresh_gap = self.ui_px(SIDEBAR_INSET);
+ let filter_width = content_width.saturating_sub(refresh_size + refresh_gap);
+ let refresh_x = content_x + content_width - refresh_size;
+ let refresh_y =
+ content_top + self.ui_px(FILE_FILTER_HEIGHT).saturating_sub(refresh_size) / 2;
+
+ let filter_input = self.right_sidebar_file_filter.clone();
+ self.paint_snippet_text_box(
+ layers,
+ 1,
+ ui_font,
+ ui_metrics,
+ chrome,
+ muted_fg,
+ content_x,
+ content_top,
+ filter_width,
+ self.ui_px(FILE_FILTER_HEIGHT),
+ Some(SvgIcon::Search),
+ "Filter files",
+ &filter_input,
+ self.right_sidebar_file_focus == Some(RightSidebarFileField::Filter),
+ UIItemType::RightSidebarFileFilter,
+ false,
+ )?;
+ self.paint_files_preview_header_icon_button(
+ layers,
+ chrome,
+ foreground,
+ muted_fg,
+ refresh_x,
+ refresh_y,
+ refresh_size,
+ SvgIcon::RotateCcw,
+ UIItemType::RightSidebarFileRefresh,
+ )?;
+
+ let tree_top = content_top + self.ui_px(FILE_FILTER_HEIGHT) + self.ui_px(FILE_TREE_TOP_GAP);
+ let root = match self.sync_right_sidebar_file_root_for_current_workspace() {
+ Ok(root) => root,
+ Err(message) => {
+ return self.paint_files_message(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ muted_fg,
+ content_x,
+ tree_top,
+ content_width,
+ content_bottom,
+ icon_size,
+ &message,
+ );
+ }
+ };
+ if self
+ .right_sidebar_file_expanded
+ .insert(path_key(&root.path))
+ {
+ self.right_sidebar_file_expanded_version =
+ self.right_sidebar_file_expanded_version.wrapping_add(1);
+ }
+
+ let applied_filter = self.right_sidebar_file_filter_for_tree();
+ let index = match self.right_sidebar_file_index_status.clone() {
+ RightSidebarFileIndexStatus::Ready => match self.right_sidebar_file_index.clone() {
+ Some(index) => index,
+ None => {
+ return self.paint_files_message(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ muted_fg,
+ content_x,
+ tree_top,
+ content_width,
+ content_bottom,
+ icon_size,
+ "Indexing files...",
+ );
+ }
+ },
+ RightSidebarFileIndexStatus::Failed(message) => {
+ return self.paint_files_message(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ muted_fg,
+ content_x,
+ tree_top,
+ content_width,
+ content_bottom,
+ icon_size,
+ &message,
+ );
+ }
+ RightSidebarFileIndexStatus::Empty | RightSidebarFileIndexStatus::Indexing => {
+ return self.paint_files_message(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ muted_fg,
+ content_x,
+ tree_top,
+ content_width,
+ content_bottom,
+ icon_size,
+ "Indexing files...",
+ );
+ }
+ };
+
+ let query = applied_filter.trim().to_string();
+ self.start_right_sidebar_file_search_if_needed(&query);
+ let row_count = if query.is_empty() {
+ self.refresh_right_sidebar_file_browse_rows(&index);
+ self.right_sidebar_file_browse_rows.len()
+ } else {
+ self.right_sidebar_file_search_rows.len()
+ };
+
+ if row_count == 0 && self.right_sidebar_file_searching {
+ return self.paint_files_message(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ muted_fg,
+ content_x,
+ tree_top,
+ content_width,
+ content_bottom,
+ icon_size,
+ "Searching files...",
+ );
+ }
+
+ if row_count == 0 && !query.is_empty() {
+ return self.paint_files_message(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ muted_fg,
+ content_x,
+ tree_top,
+ content_width,
+ content_bottom,
+ icon_size,
+ "No matching files",
);
}
@@ -8684,14 +9656,17 @@ impl crate::TermWindow {
};
for (offset, row) in rows.iter().enumerate() {
let idx = visible_rows.start + offset;
- let row_top = tree_top_f + (idx * row_metrics.row_height) as f32 - scroll_offset;
- let row_bottom = row_top + row_metrics.row_height as f32;
- if row_bottom <= tree_top_f {
- continue;
- }
- if row_top >= viewport_bottom_f {
- break;
- }
+ let row_top = match file_row_placement(
+ idx,
+ row_metrics.row_height,
+ tree_top_f,
+ viewport_bottom_f,
+ scroll_offset,
+ ) {
+ FileRowPlacement::Above => continue,
+ FileRowPlacement::Below => break,
+ FileRowPlacement::Visible(row_top) => row_top,
+ };
self.paint_file_tree_row(
layers,
ui_font,
@@ -9123,6 +10098,113 @@ impl crate::TermWindow {
)
}
+ #[allow(clippy::too_many_arguments)]
+ fn paint_remote_files_preview_header(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator,
+ ui_font: &Rc<LoadedFont>,
+ ui_metrics: RenderMetrics,
+ chrome: UiPalette,
+ foreground: LinearRgba,
+ muted_fg: LinearRgba,
+ content_x: usize,
+ content_top: usize,
+ content_width: usize,
+ path: &RemotePath,
+ ) -> anyhow::Result<()> {
+ let header_top = content_top + 4;
+ let button_size = 44.min(content_width);
+ self.paint_files_preview_header_icon_button(
+ layers,
+ chrome,
+ foreground,
+ muted_fg,
+ content_x,
+ header_top,
+ button_size,
+ SvgIcon::X,
+ UIItemType::RightSidebarRemoteFileBack,
+ )?;
+ let can_copy = self.right_sidebar_file_preview_image.is_none()
+ && !self.right_sidebar_file_preview_lines.is_empty();
+ let actions_x = content_x + content_width.saturating_sub(button_size);
+ if can_copy {
+ self.paint_files_preview_header_icon_button(
+ layers,
+ chrome,
+ foreground,
+ muted_fg,
+ actions_x,
+ header_top,
+ button_size,
+ SvgIcon::Copy,
+ UIItemType::RightSidebarRemoteFileCopyText,
+ )?;
+ }
+ let title_x = content_x + button_size + self.ui_px(SIDEBAR_INSET);
+ let title_right = if can_copy {
+ actions_x.saturating_sub(self.ui_px(SIDEBAR_INSET))
+ } else {
+ content_x + content_width
+ };
+ self.paint_sidebar_text(
+ layers,
+ ui_font,
+ ui_metrics,
+ path.file_name(),
+ title_x,
+ header_top + button_size.saturating_sub(ui_metrics.cell_size.height as usize) / 2,
+ title_right.saturating_sub(title_x),
+ foreground,
+ )
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn paint_current_files_preview_header(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator,
+ ui_font: &Rc<LoadedFont>,
+ ui_metrics: RenderMetrics,
+ chrome: UiPalette,
+ foreground: LinearRgba,
+ muted_fg: LinearRgba,
+ content_x: usize,
+ content_top: usize,
+ content_width: usize,
+ local_path: Option<&Path>,
+ remote_path: Option<&RemotePath>,
+ ) -> anyhow::Result<()> {
+ if let Some(path) = remote_path {
+ self.paint_remote_files_preview_header(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ foreground,
+ muted_fg,
+ content_x,
+ content_top,
+ content_width,
+ path,
+ )
+ } else if let Some(path) = local_path {
+ self.paint_files_preview_header(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ foreground,
+ muted_fg,
+ content_x,
+ content_top,
+ content_width,
+ path,
+ )
+ } else {
+ Ok(())
+ }
+ }
+
#[allow(clippy::too_many_arguments)]
fn paint_files_preview_header_open_with_button(
&mut self,
@@ -9258,15 +10340,17 @@ impl crate::TermWindow {
content_width: usize,
_content_bottom: usize,
) -> anyhow::Result<()> {
- let Some(path) = self.right_sidebar_file_selected.clone() else {
+ let local_path = self.right_sidebar_file_selected.clone();
+ let remote_path = self.right_sidebar_remote_files.selected.clone();
+ if local_path.is_none() && remote_path.is_none() {
return Ok(());
- };
+ }
let mut profile = FilePreviewPaintProfile::new();
let mut profile_scroll_offset = 0.0;
let mut profile_horizontal_offset = 0usize;
let Some(metrics) = self.right_sidebar_file_preview_body_metrics(ui_metrics) else {
- self.paint_files_preview_header(
+ self.paint_current_files_preview_header(
layers,
ui_font,
ui_metrics,
@@ -9276,7 +10360,8 @@ impl crate::TermWindow {
content_x,
content_top,
content_width,
- &path,
+ local_path.as_deref(),
+ remote_path.as_ref(),
)?;
return Ok(());
};
@@ -9441,7 +10526,7 @@ impl crate::TermWindow {
.min(body_bottom.saturating_sub(metrics.y)),
)?;
}
- self.paint_files_preview_header(
+ self.paint_current_files_preview_header(
layers,
ui_font,
ui_metrics,
@@ -9451,7 +10536,8 @@ impl crate::TermWindow {
content_x,
content_top,
content_width,
- &path,
+ local_path.as_deref(),
+ remote_path.as_ref(),
)?;
if show_scrollbars {
self.paint_right_sidebar_file_preview_scrollbar(layers, chrome)?;
@@ -9998,7 +11084,7 @@ impl crate::TermWindow {
let toolbar_gap = self.ui_px(SNIPPET_ROW_GAP);
let search_is_active = self.right_sidebar_snippet_focus
== Some(RightSidebarSnippetField::Search)
- || !self.right_sidebar_snippet_search.text.is_empty();
+ || !self.right_sidebar_snippet_search.text().is_empty();
let full_new_button_width = new_button_icon_size
+ self.ui_px(SIDEBAR_ICON_GAP)
+ new_button_label_width
@@ -10067,7 +11153,7 @@ impl crate::TermWindow {
+ self.ui_px(SNIPPET_LIST_TOP_GAP);
let needle = self
.right_sidebar_snippet_search
- .text
+ .text()
.trim()
.to_ascii_lowercase();
let snippets: Vec<_> = crate::snippets::list_snippets()
@@ -10622,15 +11708,15 @@ impl crate::TermWindow {
text_x += icon_size + self.ui_px(SIDEBAR_ICON_GAP);
}
- let text_color = if input.text.is_empty() && !focused {
+ let text_color = if input.text().is_empty() && !focused {
muted_fg.mul_alpha(0.72)
} else {
chrome.text
};
- let text = if input.text.is_empty() && !focused {
+ let text = if input.text().is_empty() && !focused {
placeholder
} else {
- input.text.as_str()
+ input.text()
};
if multiline {
let line_height = ui_metrics.cell_size.height as usize + 4;
@@ -10679,7 +11765,7 @@ impl crate::TermWindow {
let text_area_width = width.saturating_sub((text_x - x) + text_pad);
let baseline_y = y + (height.saturating_sub(ui_metrics.cell_size.height as usize)) / 2;
- if input.text.is_empty() && !focused {
+ if input.text().is_empty() && !focused {
self.paint_sidebar_text(
layers,
ui_font,
@@ -10691,7 +11777,7 @@ impl crate::TermWindow {
text_color,
)?;
} else {
- let chars: Vec<char> = input.text.chars().collect();
+ let chars: Vec<char> = input.text().chars().collect();
let cursor = input.cursor.min(chars.len());
let avail = text_area_width as f32;
let caret_margin = self.ui_f32(SNIPPET_CARET_WIDTH) + 2.0;
@@ -11253,7 +12339,11 @@ fn syntax_color(kind: HighlightKind, use_dark_theme: bool) -> LinearRgba {
}
fn preview_line_count(lines: &[RightSidebarFilePreviewLine]) -> usize {
- if lines.is_empty() { 1 } else { lines.len() }
+ if lines.is_empty() {
+ 1
+ } else {
+ lines.len()
+ }
}
fn decimal_digit_count(mut value: usize) -> usize {
@@ -11523,6 +12613,39 @@ fn open_with_candidate_rank(candidate: &wezterm_open_url::OpenWithCandidate) ->
(rank, candidate.label.to_lowercase())
}
+/// Where a tree row lands once the viewport is scrolled, or that it is outside
+/// the viewport entirely.
+#[derive(Debug, Clone, Copy, PartialEq)]
+enum FileRowPlacement {
+ /// Scrolled off the top; skip it and keep going.
+ Above,
+ /// Paint at this y. May sit above `tree_top` when the row is only partly
+ /// scrolled out — the row painters clip against `tree_top`/`viewport_bottom`
+ /// themselves, and they need the *true* origin to do it. Clamping the origin
+ /// instead keeps a full row height below `tree_top`, which overlaps the next
+ /// row by the scroll remainder and drags an oversized hit rect along.
+ Visible(f32),
+ /// Past the bottom; every later row is too, so the caller can stop.
+ Below,
+}
+
+fn file_row_placement(
+ index: usize,
+ row_height: usize,
+ tree_top: f32,
+ viewport_bottom: f32,
+ scroll: f32,
+) -> FileRowPlacement {
+ let row_top = tree_top + (index * row_height) as f32 - scroll;
+ if row_top + row_height as f32 <= tree_top {
+ FileRowPlacement::Above
+ } else if row_top >= viewport_bottom {
+ FileRowPlacement::Below
+ } else {
+ FileRowPlacement::Visible(row_top)
+ }
+}
+
fn visible_file_row_range(
row_count: usize,
scroll_offset: f32,
@@ -11588,6 +12711,102 @@ fn is_preview_image_path(path: &Path) -> bool {
)
}
+fn is_preview_image_extension(extension: Option<&str>) -> bool {
+ matches!(
+ extension.map(str::to_ascii_lowercase).as_deref(),
+ Some("png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "ico" | "tif" | "tiff")
+ )
+}
+
+fn remote_preview_from_bytes(
+ path: &RemotePath,
+ mut remote: RemoteFileBytes,
+ use_dark_syntax_theme: bool,
+) -> RightSidebarLoadedFilePreview {
+ if is_preview_image_extension(path.extension()) {
+ if remote.truncated {
+ return RightSidebarLoadedFilePreview {
+ lines: Vec::new(),
+ image: None,
+ message: Some(format!(
+ "image is larger than {} MiB",
+ FILE_PREVIEW_IMAGE_MAX_BYTES / 1024 / 1024
+ )),
+ truncated: true,
+ };
+ }
+ let encoded_bytes = remote.bytes.len();
+ let image_data = ImageDataType::EncodedFile(remote.bytes);
+ return match image_data.dimensions() {
+ Ok((width, height)) if image_pixels_within_preview_budget(width, height) => {
+ RightSidebarLoadedFilePreview {
+ lines: Vec::new(),
+ image: Some(RightSidebarFilePreviewImage {
+ data: Arc::new(ImageData::with_data(image_data)),
+ width,
+ height,
+ encoded_bytes,
+ }),
+ message: None,
+ truncated: false,
+ }
+ }
+ Ok((width, height)) => RightSidebarLoadedFilePreview {
+ lines: Vec::new(),
+ image: None,
+ message: Some(format!(
+ "image is too large to preview ({width}×{height}, over {} megapixels)",
+ FILE_PREVIEW_IMAGE_MAX_PIXELS / 1_000_000
+ )),
+ truncated: false,
+ },
+ Err(err) => RightSidebarLoadedFilePreview {
+ lines: Vec::new(),
+ image: None,
+ message: Some(format!("Unable to decode image dimensions: {err:#}")),
+ truncated: false,
+ },
+ };
+ }
+
+ if remote.truncated {
+ truncate_preview_bytes_to_utf8_boundary(&mut remote.bytes);
+ }
+ let (text, message) = if remote.bytes.contains(&0) {
+ (
+ String::new(),
+ Some("Preview unavailable for binary file".to_string()),
+ )
+ } else {
+ match String::from_utf8(remote.bytes) {
+ Ok(text) if text.is_empty() => (String::new(), Some("Empty file".to_string())),
+ Ok(text) => (text, None),
+ Err(_) => (
+ String::new(),
+ Some("Preview unavailable for non-UTF-8 text".to_string()),
+ ),
+ }
+ };
+ let lines = if message.is_none() {
+ // The highlighter only uses the basename/extension; never pass the
+ // remote path through local filesystem operations.
+ preview_lines_from_text_with_cancellation(
+ Path::new(path.file_name()),
+ &text,
+ use_dark_syntax_theme,
+ None,
+ )
+ } else {
+ Vec::new()
+ };
+ RightSidebarLoadedFilePreview {
+ lines,
+ image: None,
+ message,
+ truncated: remote.truncated,
+ }
+}
+
fn load_file_preview_image(path: &Path) -> anyhow::Result<RightSidebarFilePreviewImage> {
let metadata = fs::metadata(path).with_context(|| format!("stat {}", path.display()))?;
if metadata.len() > FILE_PREVIEW_IMAGE_MAX_BYTES as u64 {
@@ -11707,8 +12926,8 @@ impl RightSidebarFileCharBag {
/// `Arc<RightSidebarFileIndex>` instead of each scanning and holding its own
/// copy. Only weak refs live here, so an index is freed the moment the last
/// window drops its strong ref (e.g. via the idle-release path).
-fn shared_file_index_registry()
--> &'static Mutex<HashMap<(PathBuf, String), Weak<RightSidebarFileIndex>>> {
+fn shared_file_index_registry(
+) -> &'static Mutex<HashMap<(PathBuf, String), Weak<RightSidebarFileIndex>>> {
static REGISTRY: OnceLock<Mutex<HashMap<(PathBuf, String), Weak<RightSidebarFileIndex>>>> =
OnceLock::new();
REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
@@ -12099,6 +13318,40 @@ fn file_icon_for_row(row: &RightSidebarFileTreeRow) -> RightSidebarFileIcon {
}
}
+fn remote_file_icon(row: &RemoteFileRow) -> RightSidebarFileIcon {
+ if row.entry.is_directory() {
+ if let Some(icon) =
+ material_folder_icon_for_name(&row.entry.name, row.expanded, row.depth == 0)
+ {
+ return RightSidebarFileIcon::Material(icon);
+ }
+ return RightSidebarFileIcon::Svg(if row.expanded {
+ SvgIcon::FolderOpen
+ } else {
+ SvgIcon::Folder
+ });
+ }
+ if let Some(icon) = material_file_icon_for_name(&row.entry.name) {
+ return RightSidebarFileIcon::Material(icon);
+ }
+ let icon = match row
+ .entry
+ .path
+ .extension()
+ .map(str::to_ascii_lowercase)
+ .as_deref()
+ {
+ Some(
+ "rs" | "toml" | "lua" | "js" | "jsx" | "ts" | "tsx" | "json" | "css" | "html" | "sh"
+ | "py" | "rb" | "go" | "swift" | "kt" | "java" | "c" | "cc" | "cpp" | "h" | "hpp" | "m"
+ | "mm",
+ ) => SvgIcon::FileCode,
+ Some("md" | "txt" | "log" | "yaml" | "yml" | "xml") => SvgIcon::FileText,
+ _ => SvgIcon::File,
+ };
+ RightSidebarFileIcon::Svg(icon)
+}
+
fn snippet_preview(body: &str) -> String {
body.lines()
.find_map(|line| {
@@ -12317,21 +13570,21 @@ fn snippet_cursor_visible(now_ms: u128, blink_ms: u64) -> bool {
#[cfg(test)]
mod tests {
use super::{
- FileReleaseAction, NoteReleaseAction, file_release_action, note_release_action,
- FILE_PREVIEW_MAX_BYTES, NOTE_CODE_BLOCK_RADIUS, NOTE_CODE_HEADER_HEIGHT,
- NoteApproximateTextMetrics, NoteCodeHighlightEntry, NoteCodeHighlightState,
approximate_note_text_width, build_right_sidebar_file_index, clip_note_texture,
- full_line_colors_by_byte,
+ file_release_action, file_row_placement, full_line_colors_by_byte,
image_pixels_within_preview_budget, load_file_preview, load_file_preview_image,
naturalish_cmp, note_code_highlight_key, note_code_highlight_lines, note_code_row_height,
- note_image_display_size, note_open_pending_for_vault, open_with_candidate_allowed,
- path_key, preview_line_count, preview_lines_from_text, preview_plain_lines_from_text,
- preview_text_range, preview_visible_colored, preview_visible_line_range,
- right_sidebar_file_browse_rows_from_index, right_sidebar_file_row_metrics,
- right_sidebar_open_with_cache_key, scrollable_note_table_columns,
- search_right_sidebar_file_index, snippet_cursor_visible, snippet_run_buffer,
- sorted_open_with_candidates, virtual_note_line_range, visible_code_block_rounded_edges,
- visible_file_row_range, wrap_snippet_text_for_width,
+ note_image_display_size, note_open_pending_for_vault, note_release_action,
+ open_with_candidate_allowed, path_key, preview_line_count, preview_lines_from_text,
+ preview_plain_lines_from_text, preview_text_range, preview_visible_colored,
+ preview_visible_line_range, right_sidebar_file_browse_rows_from_index,
+ right_sidebar_file_row_metrics, right_sidebar_open_with_cache_key,
+ scrollable_note_table_columns, search_right_sidebar_file_index, snippet_cursor_visible,
+ snippet_run_buffer, sorted_open_with_candidates, virtual_note_line_range,
+ visible_code_block_rounded_edges, visible_file_row_range, wrap_snippet_text_for_width,
+ FileReleaseAction, FileRowPlacement, NoteApproximateTextMetrics, NoteCodeHighlightEntry,
+ NoteCodeHighlightState, NoteReleaseAction, FILE_PREVIEW_MAX_BYTES, NOTE_CODE_BLOCK_RADIUS,
+ NOTE_CODE_HEADER_HEIGHT,
};
use crate::markdown_editor::{NoteLineGeometry, ProjectedCodeBlock};
use crate::termwindow::{RightSidebarFilePreviewLine, RightSidebarFilePreviewSpan};
@@ -12339,11 +13592,11 @@ mod tests {
use std::collections::HashSet;
use std::fs;
use std::io::Cursor;
- use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
+ use std::sync::Arc;
use wezterm_font::units::PixelLength;
- use window::Size;
use window::color::LinearRgba;
+ use window::Size;
fn test_render_metrics(cell_height: isize, cell_width: isize) -> RenderMetrics {
RenderMetrics {
@@ -12535,21 +13788,17 @@ mod tests {
state.remember_block(python.source.start, Arc::clone(&entry));
assert!(state.cached(key, &python.text).is_some());
assert!(state.cached(key, "hash collision guard").is_none());
- assert!(
- state
- .previous_for_block(python.source.start, changed_key.language)
- .is_some()
- );
+ assert!(state
+ .previous_for_block(python.source.start, changed_key.language)
+ .is_some());
let generation = state
.schedule_block(python.source.start, changed_key)
.unwrap();
assert!(generation > 0);
- assert!(
- state
- .schedule_block(python.source.start, changed_key)
- .is_none()
- );
+ assert!(state
+ .schedule_block(python.source.start, changed_key)
+ .is_none());
}
#[test]
@@ -12801,6 +14050,66 @@ mod tests {
assert_eq!(preview_visible_line_range(0, 0, 2), 0..0);
}
+ #[test]
+ fn partly_scrolled_row_keeps_its_true_origin() {
+ // Scroll by a third of a row: the first row is still partly visible and
+ // must report an origin *above* tree_top so the painter can clip it.
+ // Clamping it to tree_top (the bug this pins) would draw a full-height
+ // row starting at tree_top, overlapping row 1 by the remainder and
+ // handing it an oversized hit rect.
+ let row_height = 30usize;
+ let tree_top = 100.0;
+ let viewport_bottom = 400.0;
+ let scroll = 10.0;
+
+ assert_eq!(
+ file_row_placement(0, row_height, tree_top, viewport_bottom, scroll),
+ FileRowPlacement::Visible(90.0)
+ );
+ // Rows never overlap: each sits exactly one row height below the last.
+ assert_eq!(
+ file_row_placement(1, row_height, tree_top, viewport_bottom, scroll),
+ FileRowPlacement::Visible(120.0)
+ );
+ }
+
+ #[test]
+ fn rows_outside_the_viewport_are_classified() {
+ let row_height = 30usize;
+ let tree_top = 100.0;
+ let viewport_bottom = 400.0;
+
+ // Scrolled a full row: row 0 is exactly flush with the top edge and
+ // contributes nothing.
+ assert_eq!(
+ file_row_placement(0, row_height, tree_top, viewport_bottom, 30.0),
+ FileRowPlacement::Above
+ );
+ // One pixel less and it is still (barely) on screen.
+ assert_eq!(
+ file_row_placement(0, row_height, tree_top, viewport_bottom, 29.0),
+ FileRowPlacement::Visible(71.0)
+ );
+ // A row starting exactly at the bottom edge is out, and so is anything
+ // after it — the caller stops there.
+ assert_eq!(
+ file_row_placement(10, row_height, tree_top, viewport_bottom, 0.0),
+ FileRowPlacement::Below
+ );
+ assert_eq!(
+ file_row_placement(9, row_height, tree_top, viewport_bottom, 0.0),
+ FileRowPlacement::Visible(370.0)
+ );
+ }
+
+ #[test]
+ fn unscrolled_first_row_starts_at_the_tree_top() {
+ assert_eq!(
+ file_row_placement(0, 30, 100.0, 400.0, 0.0),
+ FileRowPlacement::Visible(100.0)
+ );
+ }
+
#[test]
fn visible_file_row_range_only_returns_rows_near_viewport() {
let row_height = 44;
@@ -12845,7 +14154,7 @@ mod tests {
assert!(image_pixels_within_preview_budget(1920, 1080)); // 2 MP
assert!(image_pixels_within_preview_budget(4096, 2160)); // ~8.8 MP (4K)
assert!(image_pixels_within_preview_budget(4000, 4000)); // 16 MP (== budget)
- // Bombs are rejected, and the u64 product cannot overflow.
+ // Bombs are rejected, and the u64 product cannot overflow.
assert!(!image_pixels_within_preview_budget(8000, 8000)); // 64 MP
assert!(!image_pixels_within_preview_budget(100_000, 100_000));
assert!(!image_pixels_within_preview_budget(u32::MAX, u32::MAX));
diff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rs
index 095b5bf7..8804ec2d 100644
--- a/wezterm-gui/src/termwindow/ui/sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs
@@ -287,9 +287,7 @@ impl crate::TermWindow {
) -> workspace_threads::WorkspaceThreadsView {
let hidden = crate::native_settings::workspace_sidebar_hidden_statuses()
.iter()
- .filter_map(|key| {
- workspace_threads::WorkspaceThreadWorkStatus::from_settings_key(key)
- })
+ .filter_map(|key| workspace_threads::WorkspaceThreadWorkStatus::from_settings_key(key))
.collect::<Vec<_>>();
if !hidden.is_empty() {
workspace_threads::filter_threads_view_by_status(&mut view, &hidden);
@@ -599,13 +597,12 @@ impl crate::TermWindow {
.current_mux_workspace()
.unwrap_or_else(|| mux.active_workspace());
let workspaces = mux.iter_workspaces();
- let view = self.apply_workspace_thread_status_filter(
- workspace_threads::view_for_current_project(
+ let view =
+ self.apply_workspace_thread_status_filter(workspace_threads::view_for_current_project(
&self.active_space_id,
&active_workspace,
&workspaces,
- ),
- );
+ ));
let row_gap = self.ui_px(SIDEBAR_ROW_GAP);
let total_height = Self::workspace_sidebar_scroll_height(
&view,
@@ -648,13 +645,12 @@ impl crate::TermWindow {
.current_mux_workspace()
.unwrap_or_else(|| mux.active_workspace());
let workspaces = mux.iter_workspaces();
- let view = self.apply_workspace_thread_status_filter(
- workspace_threads::view_for_current_project(
+ let view =
+ self.apply_workspace_thread_status_filter(workspace_threads::view_for_current_project(
&self.active_space_id,
&active_workspace,
&workspaces,
- ),
- );
+ ));
let row_gap = self.ui_px(SIDEBAR_ROW_GAP);
let total_height = Self::workspace_sidebar_scroll_height(
&view,
@@ -868,13 +864,12 @@ impl crate::TermWindow {
.current_mux_workspace()
.unwrap_or_else(|| mux.active_workspace());
let workspaces = mux.iter_workspaces();
- let view = self.apply_workspace_thread_status_filter(
- workspace_threads::view_for_current_project(
+ let view =
+ self.apply_workspace_thread_status_filter(workspace_threads::view_for_current_project(
&self.active_space_id,
&active_workspace,
&workspaces,
- ),
- );
+ ));
let header_icon_size = icon_size.min(self.ui_px(32));
let button_size = (header_icon_size + self.ui_px(8)).clamp(self.ui_px(32), self.ui_px(40));
@@ -898,14 +893,13 @@ impl crate::TermWindow {
self.window_state,
)
};
- let top_fancy_row = if self.show_tab_bar
- && self.config.use_fancy_tab_bar
- && !self.config.tab_bar_at_bottom
- {
- self.tab_bar_pixel_height().ok().map(|h| h.ceil() as usize)
- } else {
- None
- };
+ let top_fancy_row =
+ if self.show_tab_bar && self.config.use_fancy_tab_bar && !self.config.tab_bar_at_bottom
+ {
+ self.tab_bar_pixel_height().ok().map(|h| h.ceil() as usize)
+ } else {
+ None
+ };
let sidebar_toggle_y = if sidebar_toolbar_uses_fullscreen_style {
header_y + self.ui_px(WINDOW_TAB_FULLSCREEN_SIDEBAR_BUTTON_Y_OFFSET)
} else if let Some(row_h) = top_fancy_row {
diff --git a/wezterm-gui/src/ui/draw.rs b/wezterm-gui/src/ui/draw.rs
index 58321cfb..2a924faf 100644
--- a/wezterm-gui/src/ui/draw.rs
+++ b/wezterm-gui/src/ui/draw.rs
@@ -48,6 +48,13 @@ impl<'a> DrawContext<'a> {
crate::ui::scale_ui_f32(value, self.dimensions.dpi)
}
+ /// Design-pixel -> physical-pixel ratio for this surface. Use it when a
+ /// helper needs the raw factor (e.g. to stay unit-testable); prefer
+ /// [`Self::px`] for one-off conversions.
+ pub(crate) fn scale(&self) -> f32 {
+ crate::ui::ui_scale_for_dpi(self.dimensions.dpi)
+ }
+
pub(crate) fn draw_rect(
&self,
layers: &mut TripleLayerQuadAllocator<'_>,
diff --git a/wezterm-gui/src/ui/events.rs b/wezterm-gui/src/ui/events.rs
index afd1945f..96ae8016 100644
--- a/wezterm-gui/src/ui/events.rs
+++ b/wezterm-gui/src/ui/events.rs
@@ -1,10 +1,16 @@
use crate::ui::{contains, ScrollState};
use window::{MouseEvent, MouseEventKind};
-pub(crate) fn wheel_delta_pixels(amount: i16) -> f32 {
- -(amount as f32) * 34.0
+/// Pixels moved per wheel notch. `scale` is the design-pixel ratio
+/// ([`DrawContext::scale`]): rows shrink with the UI, so the scroll step has to
+/// shrink with them or one notch jumps a different number of rows per display.
+pub(crate) fn wheel_delta_pixels(amount: i16, scale: f32) -> f32 {
+ -(amount as f32) * WHEEL_NOTCH_PIXELS * scale
}
+/// Distance a single wheel notch scrolls, in design pixels.
+const WHEEL_NOTCH_PIXELS: f32 = 34.0;
+
pub(crate) fn precise_wheel_delta_pixels(event: &MouseEvent) -> Option<f32> {
let delta = event.precise_scroll_delta?;
if delta.y.abs() >= delta.x.abs() && delta.y.abs() > f32::EPSILON {
@@ -18,6 +24,7 @@ pub(crate) fn apply_wheel_to_area(
event: &MouseEvent,
area: window::RectF,
scroll: &mut ScrollState,
+ scale: f32,
) -> bool {
if !contains(area, event.coords.x as f32, event.coords.y as f32) {
return false;
@@ -34,7 +41,7 @@ pub(crate) fn apply_wheel_to_area(
match event.kind {
MouseEventKind::VertWheel(amount) => {
let old_velocity = scroll.velocity;
- scroll.scroll_by_smooth(wheel_delta_pixels(amount));
+ scroll.scroll_by_smooth(wheel_delta_pixels(amount, scale));
(scroll.velocity - old_velocity).abs() > 0.5
}
_ => false,
diff --git a/wezterm-gui/src/ui/keys.rs b/wezterm-gui/src/ui/keys.rs
new file mode 100644
index 00000000..f32b69c7
--- /dev/null
+++ b/wezterm-gui/src/ui/keys.rs
@@ -0,0 +1,189 @@
+//! Platform-normalized text-editing modifiers.
+//!
+//! Every text surface in the app needs the same two questions answered: is this
+//! the "command" chord (clipboard, select-all, line-start/end) and is this the
+//! "word" chord (word-wise motion and deletion)? The answer differs per OS:
+//!
+//! | | command | word |
+//! |---|---|---|
+//! | macOS | ⌘ | ⌥ |
+//! | Windows / Linux | Ctrl | Ctrl |
+//!
+//! Deriving that inline is how the surfaces drifted apart — some ended up
+//! macOS-only, so Ctrl+A/C/V and Ctrl+arrow did nothing on Windows and Linux.
+//! Resolve it here once and share the result.
+
+/// Text-editing intent of a key event's modifiers, normalized across platforms.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct EditModifiers {
+ /// Clipboard / select-all / line-start-end chord (⌘ on macOS, Ctrl elsewhere).
+ pub command: bool,
+ /// Word-wise motion and deletion chord (⌥ on macOS, Ctrl elsewhere).
+ pub word: bool,
+ /// Selection should be extended rather than replaced.
+ pub shift: bool,
+ /// Whether a modifier that rules out plain text input was held. Separate
+ /// from the two roles above because "no chord I recognize" is not the same
+ /// as "no modifier at all".
+ blocked: bool,
+}
+
+/// Modifiers that mean "this key is a shortcut, not text". Mirrors the rule the
+/// terminal input path already uses for the inline tab renamer
+/// (`termwindow/keyevent.rs`), including LEADER and the positional variants —
+/// a chord this type does not recognize must still reach the application.
+///
+/// AltGr is deliberately absent: X11 reports it through the keymap (Mod5 /
+/// ISO_Level3_Shift) rather than as Ctrl+Alt, so composed characters arrive
+/// with no modifier bits set and type normally.
+pub(crate) const TEXT_MOD_BLOCKERS: window::Modifiers = window::Modifiers::ALT
+ .union(window::Modifiers::CTRL)
+ .union(window::Modifiers::SUPER)
+ .union(window::Modifiers::LEADER)
+ .union(window::Modifiers::LEFT_ALT)
+ .union(window::Modifiers::RIGHT_ALT)
+ .union(window::Modifiers::LEFT_CTRL)
+ .union(window::Modifiers::RIGHT_CTRL);
+
+impl EditModifiers {
+ pub(crate) fn from_flags(shift: bool, ctrl: bool, alt: bool, super_: bool) -> Self {
+ let macos = cfg!(target_os = "macos");
+ // On Windows/Linux both roles live on Ctrl; the caller disambiguates by
+ // key (arrows/Backspace are word-wise, letters are commands).
+ let command = if macos {
+ super_ && !alt && !ctrl
+ } else {
+ ctrl && !alt && !super_
+ };
+ let word = if macos {
+ alt && !super_ && !ctrl
+ } else {
+ ctrl && !super_ && !alt
+ };
+ Self {
+ command,
+ word,
+ shift,
+ blocked: ctrl || alt || super_,
+ }
+ }
+
+ /// The event carries no modifier that rules out text input, so it belongs
+ /// to the focused field: characters are inserted, arrows and Backspace move
+ /// or edit the caret.
+ ///
+ /// Anything looser would swallow application shortcuts. Ctrl+F on macOS and
+ /// Super+F on Windows/Linux form neither chord above, but they are still
+ /// shortcuts — the field must not eat the `f`.
+ pub(crate) fn plain(self) -> bool {
+ !self.blocked
+ }
+}
+
+/// `wezterm_term::KeyModifiers` is a re-export of this same type, so this one
+/// impl covers both the terminal-side and window-side key paths.
+impl From<window::Modifiers> for EditModifiers {
+ fn from(mods: window::Modifiers) -> Self {
+ use window::Modifiers as M;
+ let mut resolved = Self::from_flags(
+ mods.contains(M::SHIFT),
+ mods.contains(M::CTRL),
+ mods.contains(M::ALT),
+ mods.contains(M::SUPER),
+ );
+ // `from_flags` only sees the four canonical bits; LEADER and the
+ // positional variants must block text input too.
+ resolved.blocked |= mods.intersects(TEXT_MOD_BLOCKERS);
+ resolved
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::EditModifiers;
+
+ const MACOS: bool = cfg!(target_os = "macos");
+
+ fn m(shift: bool, ctrl: bool, alt: bool, super_: bool) -> EditModifiers {
+ EditModifiers::from_flags(shift, ctrl, alt, super_)
+ }
+
+ #[test]
+ fn command_chord_follows_platform() {
+ // ⌘ alone is the command chord on macOS only.
+ assert_eq!(m(false, false, false, true).command, MACOS);
+ // Ctrl alone is the command chord everywhere else.
+ assert_eq!(m(false, true, false, false).command, !MACOS);
+ }
+
+ #[test]
+ fn word_chord_follows_platform() {
+ // ⌥ alone is the word chord on macOS only.
+ assert_eq!(m(false, false, true, false).word, MACOS);
+ // Ctrl alone doubles as the word chord off macOS.
+ assert_eq!(m(false, true, false, false).word, !MACOS);
+ }
+
+ #[test]
+ fn mixed_chords_are_rejected() {
+ // A second modifier means the user is asking for something else; never
+ // claim the event (this is what keeps app-level chords working).
+ for (shift, ctrl, alt, super_) in [
+ (false, true, true, false),
+ (false, true, false, true),
+ (false, false, true, true),
+ (false, true, true, true),
+ ] {
+ let mods = m(shift, ctrl, alt, super_);
+ assert!(!mods.command, "command claimed {ctrl}/{alt}/{super_}");
+ assert!(!mods.word, "word claimed {ctrl}/{alt}/{super_}");
+ }
+ }
+
+ #[test]
+ fn shortcut_modifiers_never_reach_the_field() {
+ // The exact combinations that used to be swallowed: on its own platform
+ // each of these forms neither chord, but they are still shortcuts. The
+ // field must not eat the key — not the arrow, and not the character.
+ for (label, mods) in [
+ ("ctrl", m(false, true, false, false)),
+ ("alt", m(false, false, true, false)),
+ ("super", m(false, false, false, true)),
+ ("ctrl+alt", m(false, true, true, false)),
+ ] {
+ if mods.command || mods.word {
+ continue; // this one *is* a chord on this platform
+ }
+ assert!(!mods.plain(), "{label} must not be treated as plain input");
+ }
+ }
+
+ #[test]
+ fn plain_ignores_shift() {
+ // Shift is how selections are extended and capitals are typed; it never
+ // takes a key away from the field.
+ assert!(m(false, false, false, false).plain());
+ assert!(m(true, false, false, false).plain());
+ }
+
+ #[test]
+ fn leader_and_positional_modifiers_block_text() {
+ // `from_flags` only sees the four canonical bits, so the `Modifiers`
+ // conversion has to catch LEADER and the left/right variants as well.
+ use window::Modifiers as M;
+ for mods in [
+ M::LEADER,
+ M::LEFT_ALT,
+ M::RIGHT_ALT,
+ M::LEFT_CTRL,
+ M::RIGHT_CTRL,
+ ] {
+ assert!(
+ !EditModifiers::from(mods).plain(),
+ "{mods:?} must block text input"
+ );
+ }
+ assert!(EditModifiers::from(M::NONE).plain());
+ assert!(EditModifiers::from(M::SHIFT).plain());
+ }
+}
diff --git a/wezterm-gui/src/ui/mod.rs b/wezterm-gui/src/ui/mod.rs
index aa952130..8039db52 100644
--- a/wezterm-gui/src/ui/mod.rs
+++ b/wezterm-gui/src/ui/mod.rs
@@ -4,6 +4,7 @@ pub(crate) mod draw;
pub(crate) mod events;
pub(crate) mod geometry;
pub(crate) mod icons;
+pub(crate) mod keys;
pub(crate) mod primitives;
pub(crate) mod state;
pub(crate) mod tokens;
@@ -13,6 +14,7 @@ pub(crate) use draw::*;
pub(crate) use events::*;
pub(crate) use geometry::*;
pub(crate) use icons::*;
+pub(crate) use keys::*;
pub(crate) use primitives::*;
pub(crate) use state::*;
pub(crate) use tokens::*;
diff --git a/wezterm-gui/src/ui/primitives.rs b/wezterm-gui/src/ui/primitives.rs
index f7eebfd5..9b7dff64 100644
--- a/wezterm-gui/src/ui/primitives.rs
+++ b/wezterm-gui/src/ui/primitives.rs
@@ -60,12 +60,15 @@ pub(crate) struct ScrollbarSpec {
}
impl ScrollbarSpec {
+ /// Every measurement here comes from `tokens`, which is already scaled for
+ /// the target DPI (`UiTokens::for_dpi`). Do not reintroduce raw literals:
+ /// mixing them with the scaled width breaks non-1.0 displays.
pub(crate) fn from_area(area: window::RectF, tokens: UiTokens) -> Self {
Self {
- x: area.origin.x + area.size.width - tokens.scrollbar_width - 4.0,
- y: area.origin.y + 8.0,
+ x: area.origin.x + area.size.width - tokens.scrollbar_width - tokens.scrollbar_inset,
+ y: area.origin.y + tokens.scrollbar_margin_y,
width: tokens.scrollbar_width,
- height: (area.size.height - 16.0).max(0.0),
+ height: (area.size.height - tokens.scrollbar_margin_y * 2.0).max(0.0),
}
}
}
diff --git a/wezterm-gui/src/ui/state.rs b/wezterm-gui/src/ui/state.rs
index 04742c03..2cc6385b 100644
--- a/wezterm-gui/src/ui/state.rs
+++ b/wezterm-gui/src/ui/state.rs
@@ -1,6 +1,10 @@
use std::time::Instant;
use window::ScrollPhase;
+/// Shortest scrollbar thumb, in design pixels, used by the legacy
+/// [`ScrollState::thumb`] entry point. Scaled callers pass their own minimum.
+const DEFAULT_MIN_THUMB_EXTENT: f32 = 32.0;
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct WidgetId(pub u64);
@@ -67,9 +71,12 @@ impl<A: Copy + PartialEq> Default for InteractionState<A> {
}
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Default)]
pub(crate) struct TextInputState {
- pub text: String,
+ /// Private on purpose. Assigning this directly leaves `cursor` stale, which
+ /// silently breaks typing and Backspace in a prefilled field; go through
+ /// [`Self::set_text_end`] or the caret methods instead.
+ text: String,
/// Cached "whole text selected" flag. Kept in sync by every mutator so the
/// simple consumers (settings window, widgets) can keep reading it, while
/// the sidebar uses the richer caret/selection model below.
@@ -139,6 +146,10 @@ impl TextInputState {
self.text.is_empty()
}
+ pub(crate) fn text(&self) -> &str {
+ &self.text
+ }
+
pub(crate) fn select_all(&mut self) {
self.selected_all = !self.text.is_empty();
if self.selected_all {
@@ -502,12 +513,24 @@ impl ScrollState {
self.max_offset() > 0.5
}
+ /// Legacy entry point that assumes an unscaled minimum thumb length.
+ /// Prefer [`Self::thumb_with_min`] and pass `UiTokens::scrollbar_min_thumb`
+ /// so the thumb keeps its proportions on non-1.0 displays.
pub(crate) fn thumb(&self, track_start: f32, track_extent: f32) -> Option<(f32, f32)> {
+ self.thumb_with_min(track_start, track_extent, DEFAULT_MIN_THUMB_EXTENT)
+ }
+
+ pub(crate) fn thumb_with_min(
+ &self,
+ track_start: f32,
+ track_extent: f32,
+ min_extent: f32,
+ ) -> Option<(f32, f32)> {
if !self.has_overflow() || track_extent <= 0.0 || self.content_extent <= 0.0 {
return None;
}
let ratio = (self.viewport_extent / self.content_extent).clamp(0.08, 1.0);
- let thumb_extent = (track_extent * ratio).max(32.0).min(track_extent);
+ let thumb_extent = (track_extent * ratio).max(min_extent).min(track_extent);
let travel = (track_extent - thumb_extent).max(0.0);
let progress = if self.max_offset() <= 0.0 {
0.0
@@ -656,4 +679,28 @@ mod text_input_tests {
i.caret_set(99, false);
assert_eq!(i.cursor, 2);
}
+
+ #[test]
+ fn set_text_end_leaves_the_caret_after_the_text() {
+ // Prefilling a field by assigning `.text` used to leave the caret at 0,
+ // so typing inserted at the front and Backspace did nothing. Every
+ // prefill must go through here instead.
+ let mut input = TextInputState::new();
+ input.set_text_end("Fira Code".to_string());
+ assert_eq!(input.cursor, input.char_len());
+ assert_eq!(input.caret_selection_range(), None);
+ assert!(!input.selected_all);
+
+ input.caret_backspace();
+ assert_eq!(input.text, "Fira Cod");
+ }
+
+ #[test]
+ fn set_text_end_handles_multibyte_text() {
+ let mut input = TextInputState::new();
+ input.set_text_end("字体名称".to_string());
+ assert_eq!(input.cursor, 4);
+ input.caret_backspace();
+ assert_eq!(input.text, "字体名");
+ }
}
diff --git a/wezterm-gui/src/ui/tokens.rs b/wezterm-gui/src/ui/tokens.rs
index bf1cac05..d6b8b98d 100644
--- a/wezterm-gui/src/ui/tokens.rs
+++ b/wezterm-gui/src/ui/tokens.rs
@@ -93,6 +93,12 @@ pub(crate) struct UiTokens {
pub icon_size: f32,
pub resize_handle_width: f32,
pub scrollbar_width: f32,
+ /// Gap between the scrollbar and the right edge of its area.
+ pub scrollbar_inset: f32,
+ /// Gap above and below the scrollbar track inside its area.
+ pub scrollbar_margin_y: f32,
+ /// Shortest the scrollbar thumb is allowed to get.
+ pub scrollbar_min_thumb: f32,
}
impl Default for UiTokens {
@@ -110,6 +116,9 @@ impl Default for UiTokens {
icon_size: 26.0,
resize_handle_width: 24.0,
scrollbar_width: 5.0,
+ scrollbar_inset: 4.0,
+ scrollbar_margin_y: 8.0,
+ scrollbar_min_thumb: 32.0,
}
}
}
@@ -135,6 +144,9 @@ impl UiTokens {
icon_size: base.icon_size * scale,
resize_handle_width: base.resize_handle_width * scale,
scrollbar_width: base.scrollbar_width * scale,
+ scrollbar_inset: base.scrollbar_inset * scale,
+ scrollbar_margin_y: base.scrollbar_margin_y * scale,
+ scrollbar_min_thumb: base.scrollbar_min_thumb * scale,
}
}
}
diff --git a/wezterm-gui/src/ui/widgets.rs b/wezterm-gui/src/ui/widgets.rs
index c35b57b0..402dd6ab 100644
--- a/wezterm-gui/src/ui/widgets.rs
+++ b/wezterm-gui/src/ui/widgets.rs
@@ -15,12 +15,45 @@ use wezterm_font::LoadedFont;
use window::color::LinearRgba;
use window::RectF;
+/// Geometry below is authored in *design pixels* (the 2x macOS backing grid)
+/// and must be converted with [`DrawContext::px`] at the point of use, exactly
+/// like the callers size their rects. Mixing a scaled rect with an unscaled
+/// inset silently breaks every display whose scale is not 1.0 — see
+/// `ui::tokens::ui_scale_for_dpi`.
+///
+/// Horizontal inset for a button label; the available text width is the button
+/// width minus this on *both* sides. Callers size buttons as
+/// `measure_text_width(label) + px(36)`, which leaves 8 design px of slack.
+const BUTTON_TEXT_PAD: f32 = 14.0;
+const BUTTON_RADIUS: f32 = 8.0;
+const ICON_BUTTON_RADIUS: f32 = 8.0;
+/// Icon side length is derived from the (already DPI-aware) cell height, so
+/// only the padding and the clamp bounds are design pixels.
+const ICON_CELL_PADDING: f32 = 4.0;
+const ICON_MIN_SIZE: f32 = 20.0;
+const ICON_MAX_SIZE: f32 = 30.0;
+/// Selection highlight bleeds this far outside the text box's text area.
+const INPUT_SELECTION_BLEED_X: f32 = 4.0;
+/// Vertical inset of the selection highlight / caret inside the text box.
+const INPUT_SELECTION_INSET_Y: f32 = 5.0;
+const INPUT_SELECTION_RADIUS_INSET: f32 = 5.0;
+const INPUT_SELECTION_MIN_RADIUS: f32 = 3.0;
+const CARET_WIDTH: f32 = 3.0;
+/// Gap between the toggle track edge and its knob.
+const TOGGLE_KNOB_INSET: f32 = 2.0;
+
/// 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)
}
+/// Width available for a button's label inside `button_width`. Split out so the
+/// pairing with [`BUTTON_TEXT_PAD`] can be unit-tested without a GPU context.
+pub(crate) fn button_label_width(button_width: f32, scale: f32) -> f32 {
+ button_width - BUTTON_TEXT_PAD * 2.0 * scale
+}
+
/// 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>(
@@ -42,16 +75,16 @@ pub(crate) fn draw_button<A: Copy + PartialEq>(
spec.rect.size.height,
background,
border,
- 8.0,
+ ctx.px(BUTTON_RADIUS),
)?;
ctx.draw_text(
layers,
font,
- spec.rect.origin.x + 14.0,
+ spec.rect.origin.x + ctx.px(BUTTON_TEXT_PAD),
control_text_y(ctx, spec.rect.origin.y, spec.rect.size.height),
spec.label,
palette.text,
- spec.rect.size.width - 28.0,
+ button_label_width(spec.rect.size.width, ctx.scale()),
)?;
Ok(())
}
@@ -82,9 +115,12 @@ pub(crate) fn draw_icon_button<A: Copy + PartialEq>(
LinearRgba::TRANSPARENT
};
if bg.3 > 0.0 {
- ctx.draw_rounded_rect(layers, 0, x, y, size, size, bg, 8.0)?;
+ ctx.draw_rounded_rect(layers, 0, x, y, size, size, bg, ctx.px(ICON_BUTTON_RADIUS))?;
}
- let icon_size = (ctx.metrics.cell_size.height as f32 + 4.0).clamp(20.0, 30.0);
+ // cell_size already tracks the window DPI, so only the padding and the
+ // clamp bounds need converting from design pixels.
+ let icon_size = (ctx.metrics.cell_size.height as f32 + ctx.px(ICON_CELL_PADDING))
+ .clamp(ctx.px(ICON_MIN_SIZE), ctx.px(ICON_MAX_SIZE));
ctx.draw_svg_icon(
layers,
icon,
@@ -99,8 +135,74 @@ pub(crate) fn draw_icon_button<A: Copy + PartialEq>(
)
}
+/// Caret and selection to render inside a text field, in char indices into the
+/// field's text. `None` at the call site keeps the legacy behaviour: the caret
+/// pins to the end of the text and only whole-text selection can be shown.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub(crate) struct InputCaret {
+ pub cursor: usize,
+ /// Ordered `(start, end)` char range; empty ranges are treated as no
+ /// selection.
+ pub selection: Option<(usize, usize)>,
+}
+
+/// Width of `text[..char_idx]` as it will actually be drawn. Shares
+/// [`DrawContext::measure_text_width`] with the renderer so caret placement can
+/// never drift from the glyphs.
+pub(crate) fn text_width_to_char(
+ ctx: &DrawContext,
+ font: &Rc<LoadedFont>,
+ text: &str,
+ char_idx: usize,
+) -> f32 {
+ let byte_idx = text
+ .char_indices()
+ .nth(char_idx)
+ .map(|(idx, _)| idx)
+ .unwrap_or(text.len());
+ ctx.measure_text_width(font, &text[..byte_idx])
+}
+
+/// Char index nearest to `dx` (an offset from the start of the text). Rounds to
+/// the closer boundary so clicking the right half of a glyph lands after it,
+/// which is what every native text field does.
+pub(crate) fn char_index_for_x(
+ ctx: &DrawContext,
+ font: &Rc<LoadedFont>,
+ text: &str,
+ dx: f32,
+) -> usize {
+ if text.is_empty() || dx <= 0.0 {
+ return 0;
+ }
+ let char_len = text.chars().count();
+ // Binary search for the last boundary that still starts before `dx`, then
+ // pick whichever of the two neighbouring boundaries is closer.
+ let (mut low, mut high) = (0usize, char_len);
+ while low < high {
+ let mid = (low + high + 1) / 2;
+ if text_width_to_char(ctx, font, text, mid) <= dx {
+ low = mid;
+ } else {
+ high = mid - 1;
+ }
+ }
+ if low >= char_len {
+ return char_len;
+ }
+ let before = text_width_to_char(ctx, font, text, low);
+ let after = text_width_to_char(ctx, font, text, low + 1);
+ if dx - before > (after - before) / 2.0 {
+ low + 1
+ } else {
+ low
+ }
+}
+
/// A single-line text field with placeholder, focus ring and caret. `text_pad`
-/// is the horizontal inset for the text (left/right).
+/// is the horizontal inset for the text (left/right). Pass `caret` to render a
+/// real caret position and partial selection; see [`InputCaret`].
+#[allow(clippy::too_many_arguments)]
pub(crate) fn draw_text_input<A: Copy + PartialEq>(
ctx: &DrawContext,
layers: &mut TripleLayerQuadAllocator<'_>,
@@ -112,6 +214,7 @@ pub(crate) fn draw_text_input<A: Copy + PartialEq>(
text_pad: f32,
cursor_on: bool,
spec: TextInputSpec<'_, A>,
+ caret: Option<InputCaret>,
) -> anyhow::Result<()> {
widgets.push(spec.rect, WidgetKind::TextInput, spec.action);
let border = if spec.focused {
@@ -143,43 +246,63 @@ pub(crate) fn draw_text_input<A: Copy + PartialEq>(
} 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),
- )?;
+ let text_left = spec.rect.origin.x + text_pad;
+ let text_area = (spec.rect.size.width - text_pad * 2.0).max(0.0);
+ let bleed_x = ctx.px(INPUT_SELECTION_BLEED_X);
+ let inset_y = ctx.px(INPUT_SELECTION_INSET_Y);
+ let highlight_y = spec.rect.origin.y + inset_y;
+ let highlight_h = (spec.rect.size.height - inset_y * 2.0).max(0.0);
+ let highlight_radius = (tokens.control_radius - ctx.px(INPUT_SELECTION_RADIUS_INSET))
+ .max(ctx.px(INPUT_SELECTION_MIN_RADIUS));
+
+ // Explicit range wins; `selected_all` is the legacy whole-text fallback.
+ let selection = caret
+ .and_then(|caret| caret.selection)
+ .filter(|(start, end)| start != end)
+ .or_else(|| {
+ (spec.selected_all && !spec.text.is_empty()).then(|| (0, spec.text.chars().count()))
+ });
+
+ if spec.focused && !spec.text.is_empty() {
+ if let Some((start, end)) = selection {
+ let start_x = text_width_to_char(ctx, font, spec.text, start).min(text_area);
+ let end_x = text_width_to_char(ctx, font, spec.text, end).min(text_area);
+ ctx.draw_rounded_rect(
+ layers,
+ 1,
+ text_left + start_x - bleed_x,
+ highlight_y,
+ (end_x - start_x) + bleed_x * 2.0,
+ highlight_h,
+ palette.selected_bg.mul_alpha(0.56),
+ highlight_radius,
+ )?;
+ }
}
ctx.draw_text(
layers,
font,
- spec.rect.origin.x + text_pad,
+ text_left,
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),
+ text_area,
)?;
- 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));
+ if spec.focused && selection.is_none() && cursor_on {
+ // Without an explicit caret the field can only pin to the end of the
+ // text, which is the pre-caret behaviour.
+ let caret_dx = match caret {
+ Some(caret) => text_width_to_char(ctx, font, spec.text, caret.cursor),
+ None => ctx.measure_text_width(font, spec.text),
+ };
+ let caret_width = ctx.px(CARET_WIDTH);
ctx.draw_rect(
layers,
1,
- caret_x - 1.0,
- spec.rect.origin.y + 5.0,
- 3.0,
- spec.rect.size.height - 10.0,
+ text_left + caret_dx.min(text_area) - caret_width / 3.0,
+ highlight_y,
+ caret_width,
+ highlight_h,
palette.selected_bg,
)?;
}
@@ -213,17 +336,18 @@ pub(crate) fn draw_toggle<A: Copy + PartialEq>(
track,
h / 2.0,
)?;
- let knob = (h - 4.0).max(2.0);
+ let inset = ctx.px(TOGGLE_KNOB_INSET);
+ let knob = (h - inset * 2.0).max(inset);
let knob_x = if on {
- rect.origin.x + rect.size.width - knob - 2.0
+ rect.origin.x + rect.size.width - knob - inset
} else {
- rect.origin.x + 2.0
+ rect.origin.x + inset
};
ctx.draw_rounded_rect(
layers,
1,
knob_x,
- rect.origin.y + 2.0,
+ rect.origin.y + inset,
knob,
knob,
LinearRgba::with_components(1.0, 1.0, 1.0, 1.0),
@@ -243,7 +367,9 @@ pub(crate) fn draw_scrollbar(
scroll: ScrollState,
) -> anyhow::Result<()> {
let spec = ScrollbarSpec::from_area(area, tokens);
- if let Some((thumb_y, thumb_h)) = scroll.thumb(spec.y, spec.height) {
+ if let Some((thumb_y, thumb_h)) =
+ scroll.thumb_with_min(spec.y, spec.height, tokens.scrollbar_min_thumb)
+ {
ctx.draw_rounded_rect(
layers,
0,
@@ -257,3 +383,38 @@ pub(crate) fn draw_scrollbar(
}
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::{button_label_width, BUTTON_TEXT_PAD};
+
+ /// Callers size buttons as `measure_text_width(label) + px(36)`. The label
+ /// must still fit after the widget subtracts its own insets, at *every*
+ /// scale — mixing a scaled width with unscaled insets is what truncated
+ /// "Save & Open" into "Save & O..." on 96dpi displays.
+ #[test]
+ fn label_always_fits_the_button_the_caller_sized() {
+ const CALLER_PAD: f32 = 36.0;
+ for scale in [0.25, 0.5, 0.75, 1.0, 2.0] {
+ for measured in [0.0, 12.5, 61.0, 168.0] {
+ let button_width = measured + CALLER_PAD * scale;
+ let available = button_label_width(button_width, scale);
+ assert!(
+ available >= measured,
+ "scale {scale}: {available} < {measured}"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn insets_are_symmetric() {
+ // 8 design px of slack at scale 1.0, matching the settings window's
+ // own 44/36 pairing.
+ assert_eq!(
+ button_label_width(100.0, 1.0),
+ 100.0 - BUTTON_TEXT_PAD * 2.0
+ );
+ assert_eq!(button_label_width(100.0, 0.5), 100.0 - BUTTON_TEXT_PAD);
+ }
+}
diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rs
index 611f239a..27cf13a3 100644
--- a/wezterm-gui/src/workspace_threads.rs
+++ b/wezterm-gui/src/workspace_threads.rs
@@ -891,7 +891,8 @@ pub fn view_for_current_project(
return store.view_for_project(space_id, &project_id, live_workspaces);
}
- current_project_for_workspace(space_id, active_workspace).view(live_workspaces)
+ let is_remote = store.is_client_domain_space(space_id);
+ current_project_for_workspace(space_id, active_workspace).view(live_workspaces, is_remote)
}
pub fn sync_current_project(space_id: &str, active_workspace: &str) -> bool {
@@ -1030,7 +1031,7 @@ pub fn project_is_remote(project_id: &str) -> bool {
.projects
.iter()
.find(|project| project.id == project_id)
- .is_some_and(is_remote_project)
+ .is_some_and(|project| is_remote_project(project, &store.spaces))
}
pub fn refresh_thread_work_for_pane(pane_id: PaneId) -> bool {
@@ -1509,6 +1510,67 @@ pub fn project_reveal_path(project_id: &str) -> Option<PathBuf> {
store.project_reveal_path(project_id)
}
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum RemoteFilesSource {
+ SshHost(String),
+ ClientDomain(String),
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct RemoteFilesTarget {
+ pub project_id: String,
+ pub project_name: String,
+ pub source: RemoteFilesSource,
+ /// Remote spelling as stored by the workspace model. This is deliberately
+ /// a String rather than PathBuf: joining is performed by the slash-only
+ /// RemotePath type in the SFTP layer.
+ pub requested_root: String,
+}
+
+/// Resolve the remote file source and root for the active project without
+/// consulting the local filesystem.
+pub fn remote_files_target(space_id: &str, project_id: &str) -> Option<RemoteFilesTarget> {
+ let store = THREAD_STORE.lock();
+ store.remote_files_target(space_id, project_id)
+}
+
+impl WorkspaceThreadStore {
+ fn remote_files_target(&self, space_id: &str, project_id: &str) -> Option<RemoteFilesTarget> {
+ let project = self
+ .projects
+ .iter()
+ .find(|project| project.space_id == space_id && project.id == project_id)?;
+ if !is_remote_project(project, &self.spaces) {
+ return None;
+ }
+
+ let source = if let Some(domain) = self
+ .spaces
+ .iter()
+ .find(|space| space.id == space_id)
+ .and_then(|space| space.client_domain.clone())
+ {
+ RemoteFilesSource::ClientDomain(domain)
+ } else {
+ RemoteFilesSource::SshHost(remote_host_id_for_project_id(&project.id).to_string())
+ };
+ let stored = project.path.to_string_lossy();
+ let requested_root = if stored.starts_with("wezterm-mux://") || stored.starts_with("ssh://")
+ {
+ "~".to_string()
+ } else {
+ stored.into_owned()
+ };
+
+ Some(RemoteFilesTarget {
+ project_id: project.id.clone(),
+ project_name: project.name.clone(),
+ source,
+ requested_root,
+ })
+ }
+}
+
pub fn workspace_pane_font_scales(
workspace: &str,
window_id: MuxWindowId,
@@ -1668,7 +1730,7 @@ fn thread_views_for_project(
}
impl Project {
- fn view(&self, live_workspaces: &[String]) -> WorkspaceThreadsView {
+ fn view(&self, live_workspaces: &[String], is_remote: bool) -> WorkspaceThreadsView {
WorkspaceThreadsView {
pinned_threads: vec![],
projects: vec![ProjectView {
@@ -1677,7 +1739,7 @@ impl Project {
is_active: true,
threads_collapsed: self.threads_collapsed,
threads: thread_views_for_project(self, Some(&self.id), live_workspaces),
- is_remote: is_remote_project(self),
+ is_remote,
distro: None,
}],
}
@@ -1962,7 +2024,7 @@ impl WorkspaceThreadStore {
.iter()
.filter(|project| project.space_id == space_id)
.map(|project| {
- let is_remote = is_remote_project(project);
+ let is_remote = is_remote_project(project, &self.spaces);
ProjectView {
id: project.id.clone(),
name: project.name.clone(),
@@ -1997,7 +2059,7 @@ impl WorkspaceThreadStore {
.projects
.iter()
.find(|project| project.id == project_id)?;
- if is_remote_project(project) || !project.path.is_dir() {
+ if is_remote_project(project, &self.spaces) || !project.path.is_dir() {
return None;
}
Some(project.path.clone())
@@ -2125,8 +2187,9 @@ impl WorkspaceThreadStore {
fn repair_cross_space_local_workspace_bindings(&mut self) -> bool {
let mut changed = false;
+ let spaces = &self.spaces;
for project in &mut self.projects {
- if is_remote_project(project) {
+ if is_remote_project(project, spaces) {
continue;
}
for session in &mut project.threads {
@@ -2390,6 +2453,9 @@ impl WorkspaceThreadStore {
fn restorable_thread_id_for_project(&self, project_index: usize) -> Option<WorkspaceThreadId> {
let project = self.projects.get(project_index)?;
+ if self.is_client_domain_space(&project.space_id) {
+ return None;
+ }
project
.active_thread_id
.as_ref()
@@ -2494,7 +2560,7 @@ impl WorkspaceThreadStore {
project_name: project.name.clone(),
thread_name: session.name.clone(),
workspace_name: workspace_name.clone(),
- is_remote: is_remote_project(project),
+ is_remote: is_remote_project(project, &self.spaces),
is_live: live_workspaces.iter().any(|live| live == &workspace_name),
})
}
@@ -2521,7 +2587,7 @@ impl WorkspaceThreadStore {
// Never write a local layout for mux-domain threads; the remote mux
// server owns the layout truth (second layer under the window-origin
// tag guard in snapshot_active_space_thread_layout_with_font_scales).
- if is_mux_domain_project_id(&project_id) {
+ if self.is_client_domain_space(space_id) || is_mux_domain_project_id(&project_id) {
return false;
}
let Some(project) = self
@@ -2895,7 +2961,7 @@ impl WorkspaceThreadStore {
return EndWorkspaceThreadResult::Noop;
};
- if !is_remote_project(&self.projects[project_index]) {
+ if !is_remote_project(&self.projects[project_index], &self.spaces) {
return EndWorkspaceThreadResult::Noop;
}
@@ -2935,7 +3001,7 @@ impl WorkspaceThreadStore {
return (None, false);
};
- if !is_remote_project(&self.projects[project_index]) {
+ if !is_remote_project(&self.projects[project_index], &self.spaces) {
return (None, false);
}
@@ -3726,10 +3792,13 @@ fn scan_workspace_work_status(workspace: &str) -> WorkspaceThreadWorkStatus {
}
}
-fn is_remote_project(project: &Project) -> bool {
+fn is_remote_project(project: &Project, spaces: &[Space]) -> bool {
project.id.starts_with("ssh-")
|| project.id.starts_with("system-ssh-")
|| project.path.to_string_lossy().starts_with("ssh://")
+ || spaces
+ .iter()
+ .any(|space| space.id == project.space_id && space.client_domain.is_some())
}
fn thread_has_restorable_workspace(thread: &WorkspaceThread) -> bool {
@@ -4738,6 +4807,71 @@ mod tests {
assert_eq!(store.thread_space_id(&thread_id), Some(space_id));
}
+ #[test]
+ fn mux_domain_path_project_is_remote_even_when_path_exists_locally() {
+ let space_id = default_space_id();
+ let dir = tempdir().unwrap();
+ let mut store = test_store();
+ store.spaces[0].client_domain = Some("remote-mux".to_string());
+
+ let materialized_workspace = "thinkterm:other-project:thread-other".to_string();
+ let thread = WorkspaceThread::new(
+ "project-path".to_string(),
+ "main".to_string(),
+ Some(materialized_workspace.clone()),
+ );
+ let thread_id = thread.id.clone();
+ let mut project = test_project(
+ "project-path",
+ "Remote path",
+ dir.path().to_path_buf(),
+ vec![thread],
+ );
+ project.active_thread_id = Some(thread_id.clone());
+ store.projects.push(project);
+ store.set_active_project_for_space(&space_id, "project-path".to_string());
+
+ assert_eq!(
+ store
+ .remote_files_target(&space_id, "project-path")
+ .expect("remote Files target"),
+ RemoteFilesTarget {
+ project_id: "project-path".to_string(),
+ project_name: "Remote path".to_string(),
+ source: RemoteFilesSource::ClientDomain("remote-mux".to_string()),
+ requested_root: dir.path().to_string_lossy().into_owned(),
+ }
+ );
+ let view = store.view_for_project(&space_id, "project-path", &[]);
+ assert!(view.projects[0].is_remote);
+ assert!(store.project_reveal_path("project-path").is_none());
+ assert!(!store.snapshot_active_space_thread_layout(
+ &space_id,
+ &materialized_workspace,
+ WorkspaceThreadLayoutSnapshot {
+ active_tab: 0,
+ tabs: vec![serde_json::json!({"kind": "must-not-be-saved"})],
+ terminal_specs: vec![],
+ },
+ ));
+ assert!(store.projects[0].threads[0].layout.is_none());
+
+ let state = store
+ .thread_connection_state(&thread_id, &[])
+ .expect("mux-domain thread state");
+ assert!(state.is_remote);
+ assert_eq!(state.space_id, space_id);
+ assert_eq!(store.thread_to_restore_for_space(&space_id), (None, false));
+
+ assert!(!store.repair_cross_space_local_workspace_bindings());
+ assert_eq!(
+ store.projects[0].threads[0]
+ .materialized_workspace_name
+ .as_deref(),
+ Some(materialized_workspace.as_str())
+ );
+ }
+
#[test]
fn activation_plan_for_thread_does_not_select_or_materialize() {
let space_id = default_space_id();
@@ -5605,6 +5739,36 @@ mod tests {
);
}
+ #[test]
+ fn end_workspace_thread_removes_mux_domain_path_project() {
+ let space_id = default_space_id();
+ let mut store = test_store();
+ store.spaces[0].client_domain = Some("remote-mux".to_string());
+
+ let thread =
+ WorkspaceThread::new("project-path".to_string(), "Session 1".to_string(), None);
+ let thread_id = thread.id.clone();
+ let mut project = test_project(
+ "project-path",
+ "Remote path",
+ PathBuf::from("/remote/project"),
+ vec![thread],
+ );
+ project.active_thread_id = Some(thread_id.clone());
+ store.projects.push(project);
+ store.set_active_project_for_space(&space_id, "project-path".to_string());
+
+ let result = store.end_workspace_thread_record(&thread_id);
+ let EndWorkspaceThreadResult::RemovedProject(removed) = result else {
+ panic!("expected mux-domain project removal");
+ };
+ assert!(removed.was_active);
+ assert!(store
+ .projects
+ .iter()
+ .all(|project| project.id != "project-path"));
+ }
+
#[test]
fn end_workspace_thread_noops_for_last_local_thread() {
let space_id = default_space_id();
@@ -5726,6 +5890,38 @@ mod tests {
);
}
+ #[test]
+ fn disconnect_mux_domain_path_thread_uses_remote_flow() {
+ let space_id = default_space_id();
+ let mut store = test_store();
+ store.spaces[0].client_domain = Some("remote-mux".to_string());
+
+ let thread =
+ WorkspaceThread::new("project-path".to_string(), "Session 1".to_string(), None);
+ let thread_id = thread.id.clone();
+ let workspace = workspace_name_for_thread("project-path", &thread_id);
+ let mut project = test_project(
+ "project-path",
+ "Remote path",
+ PathBuf::from("/remote/project"),
+ vec![thread],
+ );
+ project.active_thread_id = Some(thread_id.clone());
+ store.projects.push(project);
+ store.set_active_project_for_space(&space_id, "project-path".to_string());
+
+ let (disconnected, changed) =
+ store.disconnect_workspace_thread_record(&thread_id, &[workspace.clone()]);
+ let disconnected = disconnected.expect("disconnected mux-domain thread");
+ assert!(changed);
+ assert!(disconnected.was_active);
+ assert_eq!(disconnected.workspace_name, workspace);
+ assert_ne!(
+ store.active_project_id_for_space(&space_id).as_deref(),
+ Some("project-path")
+ );
+ }
+
#[test]
fn project_reveal_path_requires_existing_local_directory() {
let mut store = test_store();