A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
Files panel: drag/drop, rename, open-with, rescan
RoversXbb56dff91621
diff --git a/Cargo.lock b/Cargo.lockindex d4b95d7c..81654ec9 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6339,6 +6339,24 @@ dependencies = ["once_cell",]+[[package]]+name = "trash"+version = "5.2.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7602e0c7d66ec2d92a8c917219fbc7894039efa2063b9064260110828a356f46"+dependencies = [+ "chrono",+ "libc",+ "log",+ "objc2",+ "objc2-foundation",+ "once_cell",+ "percent-encoding",+ "scopeguard",+ "urlencoding",+ "windows 0.56.0",+]+[[package]]name = "try-lock"version = "0.2.5"@@ -6467,6 +6485,12 @@ dependencies = ["wezterm-dynamic",]+[[package]]+name = "urlencoding"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"+[[package]]name = "usvg"version = "0.45.1"@@ -7122,6 +7146,7 @@ dependencies = ["textwrap","thiserror 1.0.69","tiny-skia",+ "trash","umask","unicode-normalization","unicode-segmentation",@@ -7227,6 +7252,7 @@ dependencies = ["core-foundation-sys","libc","winapi",+ "winreg",][[package]]@@ -7650,6 +7676,16 @@ dependencies = ["windows_x86_64_msvc 0.33.0",]+[[package]]+name = "windows"+version = "0.56.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1de69df01bdf1ead2f4ac895dc77c9351aefff65b2f3db429a343f9cbf05e132"+dependencies = [+ "windows-core 0.56.0",+ "windows-targets 0.52.6",+]+[[package]]name = "windows"version = "0.58.0"@@ -7660,6 +7696,18 @@ dependencies = ["windows-targets 0.52.6",]+[[package]]+name = "windows-core"+version = "0.56.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4698e52ed2d08f8658ab0c39512a7c00ee5fe2688c65f8c0a4f06750d729f2a6"+dependencies = [+ "windows-implement 0.56.0",+ "windows-interface 0.56.0",+ "windows-result 0.1.2",+ "windows-targets 0.52.6",+]+[[package]]name = "windows-core"version = "0.58.0"@@ -7686,6 +7734,17 @@ dependencies = ["windows-strings 0.5.1",]+[[package]]+name = "windows-implement"+version = "0.56.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6fc35f58ecd95a9b71c4f2329b911016e6bec66b3f2e6a4aad86bd2e99e2f9b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.110",+]+[[package]]name = "windows-implement"version = "0.58.0"@@ -7708,6 +7767,17 @@ dependencies = ["syn 2.0.110",]+[[package]]+name = "windows-interface"+version = "0.56.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08990546bf4edef8f431fa6326e032865f27138718c587dc21bc0265bbcb57cc"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.110",+]+[[package]]name = "windows-interface"version = "0.58.0"@@ -7753,6 +7823,15 @@ dependencies = ["windows-strings 0.4.2",]+[[package]]+name = "windows-result"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8"+dependencies = [+ "windows-targets 0.52.6",+]+[[package]]name = "windows-result"version = "0.2.0"diff --git a/Cargo.toml b/Cargo.tomlindex 693905e4..44870cff 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -28,7 +28,7 @@ opt-level = 3# debug = 2[profile.dev]-debug = 1+debug = 0# https://jakedeichert.com/blog/reducing-rust-incremental-compilation-times-on-macos-by-70-percent/# Disabled because it breaks builds on Windows#split-debuginfo = "unpacked"@@ -237,6 +237,7 @@ utf8parse = "0.2"uuid = "1.13"varbincode = "0.1"vtparse = { version="0.7", path="vtparse", default-features=false }+trash = "5"walkdir = "2"wayland-backend = "0.3.5"wayland-client = "0.31"diff --git a/config/src/keyassignment.rs b/config/src/keyassignment.rsindex 9f0d26e3..1464ac10 100644--- a/config/src/keyassignment.rs+++ b/config/src/keyassignment.rs@@ -583,7 +583,11 @@ pub enum KeyAssignment {label: String,},OpenFileWithSystemDefault(String),+ PickOpenFileWithApp(String),RevealFileInFolder(String),+ RenameSidebarFile(String),+ TrashSidebarFile(String),+ CopyFilePathToClipboard(String),PromptRenameWorkspaceThread(String),PromptRenameSpace(String),CreateSpace,diff --git a/mux/src/tab.rs b/mux/src/tab.rsindex 6065e879..70200cee 100644--- a/mux/src/tab.rs+++ b/mux/src/tab.rs@@ -1604,11 +1604,25 @@ impl TabInner {node.first.rows = pane_size.rows;node.second.rows = pane_size.rows;+ // Clamp the preserved first branch to what actually fits;+ // collapse/expand can shrink a branch below its child's+ // remembered size, and an unclamped first here makes this+ // node wider than its parent (overlapping pane geometry).+ node.first.cols = node+ .first+ .cols+ .min(pane_size.cols.saturating_sub(2))+ .max(1);node.second.cols = pane_size.cols.saturating_sub(1 + node.first.cols);} else {node.first.cols = pane_size.cols;node.second.cols = pane_size.cols;+ node.first.rows = node+ .first+ .rows+ .min(pane_size.rows.saturating_sub(2))+ .max(1);node.second.rows = pane_size.rows.saturating_sub(1 + node.first.rows);}node.first.pixel_width = node.first.cols * cell_width;diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.tomlindex 65d5880d..f84fa36a 100644--- a/wezterm-gui/Cargo.toml+++ b/wezterm-gui/Cargo.toml@@ -94,6 +94,7 @@ termwiz.workspace = truetextwrap.workspace = truethiserror.workspace = truetiny-skia.workspace = true+trash.workspace = trueumask.workspace = trueunicode-normalization.workspace = trueunicode-segmentation.workspace = truediff --git a/wezterm-gui/src/commands.rs b/wezterm-gui/src/commands.rsindex 792a9b94..c8a3fa93 100644--- a/wezterm-gui/src/commands.rs+++ b/wezterm-gui/src/commands.rs@@ -880,6 +880,14 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Commmenubar: &[],icon: Some("md_open_in_new"),},+ PickOpenFileWithApp(_) => CommandDef {+ brief: "Open File With Other Application".into(),+ doc: "Prompts for an application to open a file with".into(),+ keys: vec![],+ args: &[ArgType::ActiveWindow],+ menubar: &[],+ icon: Some("md_open_in_new"),+ },RevealFileInFolder(_) => CommandDef {brief: "Reveal File in Folder".into(),doc: "Reveals a file in the system file manager".into(),@@ -888,6 +896,30 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Commmenubar: &[],icon: Some("md_folder_open"),},+ RenameSidebarFile(_) => CommandDef {+ brief: "Rename File".into(),+ doc: "Renames a file from the sidebar file list".into(),+ keys: vec![],+ args: &[ArgType::ActiveWindow],+ menubar: &[],+ icon: Some("md_edit"),+ },+ TrashSidebarFile(_) => CommandDef {+ brief: "Move File to Trash".into(),+ doc: "Moves a file from the sidebar file list to the system trash".into(),+ keys: vec![],+ args: &[ArgType::ActiveWindow],+ menubar: &[],+ icon: Some("md_delete"),+ },+ CopyFilePathToClipboard(_) => CommandDef {+ brief: "Copy File Path".into(),+ doc: "Copies a file path to the clipboard".into(),+ keys: vec![],+ args: &[ArgType::ActiveWindow],+ menubar: &[],+ icon: Some("md_content_copy"),+ },PromptRenameWorkspaceThread(_) => CommandDef {brief: "Rename Thread".into(),doc: "Prompts for a new name for the ThinkTerm thread".into(),diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rsindex 6fee413f..1d794da8 100644--- a/wezterm-gui/src/native_settings.rs+++ b/wezterm-gui/src/native_settings.rs@@ -196,6 +196,7 @@ pub(crate) struct NativeChromeSettings {pub(crate) right_sidebar_width: Option<usize>,pub(crate) right_sidebar_file_preview_width: Option<usize>,pub(crate) right_sidebar_open_with_app: Option<NativeOpenWithApp>,+ pub(crate) right_sidebar_custom_open_with_apps: Vec<NativeOpenWithApp>,pub(crate) tab_font_size: Option<f64>,pub(crate) pane_header_font_size: Option<f64>,}@@ -485,6 +486,25 @@ pub(crate) fn save_right_sidebar_open_with_app(app: NativeOpenWithApp) -> anyhowsave(&settings)}+pub(crate) fn right_sidebar_custom_open_with_apps() -> Vec<NativeOpenWithApp> {+ load().chrome.right_sidebar_custom_open_with_apps+}++const MAX_CUSTOM_OPEN_WITH_APPS: usize = 20;++pub(crate) fn add_right_sidebar_custom_open_with_app(+ app: NativeOpenWithApp,+) -> anyhow::Result<()> {+ let mut settings = load();+ let apps = &mut settings.chrome.right_sidebar_custom_open_with_apps;+ apps.retain(|existing| existing.id != app.id);+ apps.push(app);+ while apps.len() > MAX_CUSTOM_OPEN_WITH_APPS {+ apps.remove(0);+ }+ save(&settings)+}+pub(crate) fn mark_onboarding_seen(settings: &mut ThinkTermNativeSettings) {settings.onboarding.seen_version = ONBOARDING_VERSION;}diff --git a/wezterm-gui/src/termwindow/keyevent.rs b/wezterm-gui/src/termwindow/keyevent.rsindex b98a9a06..d3ef6a37 100644--- a/wezterm-gui/src/termwindow/keyevent.rs+++ b/wezterm-gui/src/termwindow/keyevent.rs@@ -897,6 +897,19 @@ impl super::TermWindow {}pub fn key_event_impl(&mut self, window_key: KeyEvent, context: &dyn WindowOps) {+ // Esc aborts an in-flight file-row drag without reaching the pane+ if window_key.key_is_down+ && matches!(window_key.key, KeyCode::Char('\u{1b}'))+ && self+ .right_sidebar_file_drag+ .as_ref()+ .is_some_and(|state| state.active)+ {+ self.right_sidebar_file_drag = None;+ self.dragging = None;+ context.invalidate();+ return;+ }if self.handle_inline_tab_rename_key(&window_key, context) {return;}diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex ef929f8f..b76410fe 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -59,7 +59,7 @@ use smol::Timer;use std::cell::{RefCell, RefMut};use std::collections::{HashMap, HashSet, LinkedList, VecDeque};use std::ops::Add;-use std::path::PathBuf;+use std::path::{Path, PathBuf};use std::rc::Rc;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};@@ -296,6 +296,7 @@ pub enum UIItemType {RightSidebarFilePreviewHorizontalScrollThumb,RightSidebarFilePreviewText,RightSidebarFileFilter,+ RightSidebarFileRefresh,RightSidebarFileRow(PathBuf),RightSidebarFileBack,RightSidebarFileOpen,@@ -339,6 +340,20 @@ pub enum RightSidebarFileView {Preview,}+/// Remembered Files-panel view state for one (root, project), so switching+/// workspaces / idle-release / re-scan can restore where the user was. Holds+/// only paths + scroll + the effective filter (a few KB) — never the index.+#[derive(Clone, Debug)]+pub(crate) struct RightSidebarFileViewState {+ pub view: RightSidebarFileView,+ pub selected: Option<PathBuf>,+ pub expanded: HashSet<String>,+ pub tree_scroll: f32,+ pub preview_scroll: f32,+ pub preview_horizontal: usize,+ pub filter: String,+}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum RightSidebarFileField {Filter,@@ -472,6 +487,14 @@ pub(crate) enum TabWheelSurface {PaneStack(PaneStackId),}+#[derive(Clone, Debug)]+struct FileDragState {+ path: PathBuf,+ start: ::window::Point,+ current: ::window::Point,+ active: bool,+}+#[derive(Clone, Debug)]enum InlineTabRenameTarget {WindowTab(TabId),@@ -479,6 +502,8 @@ enum InlineTabRenameTarget {Space(String),Project(String),WorkspaceThread(String),+ /// A file row in the right sidebar Files panel; commits via fs::rename.+ File(PathBuf),}#[derive(Clone, Debug)]@@ -935,6 +960,10 @@ pub struct TermWindow {context_menu: Option<ui::context_menu::ContextMenuState>,context_menu_suppressed_release: Option<MousePress>,dragging: Option<(UIItem, MouseEvent)>,+ // In-flight drag of a Files-panel row toward the terminal; becomes+ // active once the pointer moves past a small threshold so plain clicks+ // still open the file.+ right_sidebar_file_drag: Option<FileDragState>,/// Content views (e.g. SSH hosts) shown as synthetic tabs.content_views: Vec<ContentViewTab>,active_content_view_id: Option<ContentViewId>,@@ -1013,6 +1042,20 @@ pub struct TermWindow {right_sidebar_file_tree_scroll_offset: f32,right_sidebar_file_preview_scroll_offset: f32,right_sidebar_file_preview_horizontal_offset: usize,+ // When restoring a remembered preview, the async load result resets the+ // scroll to 0; this carries the offsets to re-apply once the lines arrive.+ right_sidebar_file_preview_restore_scroll: Option<(f32, usize)>,+ // Per-(root, project) remembered Files-panel view state (expanded folders,+ // selected/preview, scroll, filter) so switching workspaces / idle-release /+ // 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)>,+ // 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+ // button spinner); the old tree stays visible meanwhile.+ right_sidebar_file_refreshing: bool,right_sidebar_open_with_generation: u64,right_sidebar_open_with_cache: HashMap<String, RightSidebarOpenWithCacheEntry>,right_sidebar_open_with_app: Option<crate::native_settings::NativeOpenWithApp>,@@ -1205,6 +1248,12 @@ impl TermWindow {for state in self.pane_state.borrow_mut().values_mut() {state.mouse_terminal_coords.take();}++ // Losing window focus commits a pending inline rename (same as+ // clicking away) and abandons any in-flight file drag.+ self.finish_inline_tab_rename(true);+ self.right_sidebar_file_drag = None;+ self.dragging = None;}// Reset the cursor blink phase@@ -1219,6 +1268,12 @@ impl TermWindow {self.update_title();self.emit_window_event("window-focus-changed", None);++ // On regaining focus, refresh the Files tree + (re)start its periodic+ // re-scan; on blur the cycle lapses (its next tick gates on focus).+ if focused {+ self.kick_right_sidebar_file_rescan_cycle();+ }}fn created(&mut self, ctx: RenderContext) -> anyhow::Result<()> {@@ -1499,6 +1554,7 @@ impl TermWindow {context_menu: None,context_menu_suppressed_release: None,dragging: None,+ right_sidebar_file_drag: None,content_views: vec![],active_content_view_id: None,content_view_response_tab_id: None,@@ -1564,6 +1620,11 @@ impl TermWindow {right_sidebar_file_tree_scroll_offset: 0.0,right_sidebar_file_preview_scroll_offset: 0.0,right_sidebar_file_preview_horizontal_offset: 0,+ 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_file_rescan_token: 0,+ right_sidebar_file_refreshing: false,right_sidebar_open_with_generation: 0,right_sidebar_open_with_cache: HashMap::new(),right_sidebar_open_with_app: crate::native_settings::right_sidebar_open_with_app(),@@ -3894,6 +3955,41 @@ impl TermWindow {}}+ /// Whether the given pressed UI item is the surface currently hosting the+ /// inline rename editor; presses there must not auto-commit the rename.+ fn ui_item_hosts_inline_rename(&self, item: Option<&UIItemType>) -> bool {+ let Some(rename) = self.inline_tab_rename.as_ref() else {+ return false;+ };+ let Some(item) = item else {+ return false;+ };+ match (&rename.target, item) {+ (+ InlineTabRenameTarget::WindowTab(tab_id),+ UIItemType::TabBar(TabBarItem::Tab { tab_idx, .. }),+ ) => {+ Mux::get()+ .get_window(self.mux_window_id)+ .and_then(|window| window.get_by_idx(*tab_idx).map(|tab| tab.tab_id()))+ == Some(*tab_id)+ }+ (InlineTabRenameTarget::PaneTab(pane_id), UIItemType::PaneNav { pane_id: p, .. }) => {+ p == pane_id+ }+ (InlineTabRenameTarget::Space(_), UIItemType::SpaceMenu) => true,+ (InlineTabRenameTarget::Project(id), UIItemType::Project(other)) => id == other,+ (InlineTabRenameTarget::WorkspaceThread(id), UIItemType::WorkspaceThread(other)) => {+ id == other+ }+ (+ InlineTabRenameTarget::File(path),+ UIItemType::RightSidebarFileRow(other),+ ) => path == other,+ _ => false,+ }+ }+fn finish_inline_tab_rename(&mut self, commit: bool) {let rename = match self.inline_tab_rename.take() {Some(rename) => rename,@@ -3924,12 +4020,71 @@ impl TermWindow {InlineTabRenameTarget::WorkspaceThread(thread_id) => {crate::workspace_threads::rename_thread(&thread_id, title);}+ InlineTabRenameTarget::File(path) => {+ self.commit_sidebar_file_rename(path, &title);+ }}}self.update_title_impl();}+ pub(crate) fn start_sidebar_file_rename(&mut self, path: PathBuf) {+ self.finish_inline_tab_rename(true);+ let Some(name) = path.file_name().map(|n| n.to_string_lossy().to_string()) else {+ return;+ };+ self.inline_tab_rename = Some(InlineTabRename::new(+ InlineTabRenameTarget::File(path),+ name,+ ));+ if let Some(window) = self.window.as_ref() {+ window.invalidate();+ }+ }++ fn commit_sidebar_file_rename(&mut self, old_path: PathBuf, new_name: &str) {+ if new_name.is_empty() || new_name.contains(std::path::is_separator) {+ return;+ }+ if old_path.file_name().map(|n| n.to_string_lossy()) == Some(new_name.into()) {+ return;+ }+ let Some(parent) = old_path.parent() else {+ return;+ };+ let new_path = parent.join(new_name);+ if new_path.exists() {+ log::warn!(+ "not renaming {} to {new_name}: target already exists",+ old_path.display()+ );+ return;+ }+ if let Err(err) = std::fs::rename(&old_path, &new_path) {+ log::error!("failed to rename {}: {err:#}", old_path.display());+ return;+ }+ if self.right_sidebar_file_selected.as_ref() == Some(&old_path) {+ self.right_sidebar_file_selected = Some(new_path);+ }+ self.force_right_sidebar_file_rescan();+ }++ pub(crate) fn is_renaming_sidebar_file(&self, path: &Path) -> bool {+ self.inline_tab_rename.as_ref().is_some_and(+ |rename| matches!(&rename.target, InlineTabRenameTarget::File(p) if p == path),+ )+ }++ pub(crate) fn sidebar_file_row_title(&self, path: &Path, name: &str) -> String {+ self.inline_tab_rename+ .as_ref()+ .filter(|rename| matches!(&rename.target, InlineTabRenameTarget::File(p) if p == path))+ .map(|rename| rename.display_text())+ .unwrap_or_else(|| name.to_string())+ }+fn inline_window_tab_rename_title(&self, tab_id: TabId) -> Option<String> {self.inline_tab_rename.as_ref()@@ -3945,7 +4100,8 @@ impl TermWindow {InlineTabRenameTarget::PaneTab(_)| InlineTabRenameTarget::Space(_)| InlineTabRenameTarget::Project(_)- | InlineTabRenameTarget::WorkspaceThread(_) => None,+ | InlineTabRenameTarget::WorkspaceThread(_)+ | InlineTabRenameTarget::File(_) => None,})}@@ -4530,9 +4686,37 @@ impl TermWindow {OpenFileWithSystemDefault(path) => {wezterm_open_url::open_url(path);}+ PickOpenFileWithApp(path) => {+ let file_path = path.clone();+ let Some(window) = self.window.as_ref().cloned() else {+ return Ok(PerformAssignmentResult::Handled);+ };+ let notify_window = window.clone();+ window.pick_app_async(Box::new(move |app_path| {+ if let Some(app_path) = app_path {+ notify_window.notify(TermWindowNotif::Apply(Box::new(+ move |term_window| {+ term_window.finish_pick_open_with_app(&file_path, &app_path);+ },+ )));+ }+ }));+ }RevealFileInFolder(path) => {wezterm_open_url::reveal_path(std::path::Path::new(path));}+ RenameSidebarFile(path) => {+ self.start_sidebar_file_rename(PathBuf::from(path));+ }+ TrashSidebarFile(path) => {+ self.trash_sidebar_file(Path::new(path));+ }+ CopyFilePathToClipboard(path) => {+ self.copy_to_clipboard(+ config::keyassignment::ClipboardCopyDestination::Clipboard,+ path.clone(),+ );+ }PromptRenameWorkspaceThread(thread_id) => {self.prompt_rename_workspace_thread(thread_id.clone())}diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex 91a0a7b2..823507a6 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -677,6 +677,7 @@ impl super::TermWindow {| UIItemType::RightSidebarFilePreviewHorizontalScrollThumb| UIItemType::RightSidebarFilePreviewText| UIItemType::RightSidebarFileFilter+ | UIItemType::RightSidebarFileRefresh| UIItemType::RightSidebarFileRow(_)| UIItemType::RightSidebarFileBack| UIItemType::RightSidebarFileOpen@@ -739,6 +740,7 @@ impl super::TermWindow {| UIItemType::RightSidebarFilePreviewHorizontalScrollThumb| UIItemType::RightSidebarFilePreviewText| UIItemType::RightSidebarFileFilter+ | UIItemType::RightSidebarFileRefresh| UIItemType::RightSidebarFileRow(_)| UIItemType::RightSidebarFileBack| UIItemType::RightSidebarFileOpen@@ -962,6 +964,30 @@ impl super::TermWindow {);context.invalidate();}+ if completed_drag+ .as_ref()+ .is_some_and(|(item, _)| {+ matches!(item.item_type, UIItemType::RightSidebarFileRow(_))+ })+ {+ if let Some(state) = self.right_sidebar_file_drag.take() {+ if state.active {+ self.drop_right_sidebar_file_drag(state, &event, x, y);+ context.invalidate();+ } else {+ // Never crossed the drag threshold: this was a+ // plain click, so open the file (moved here+ // from the press handler). Opening a preview+ // widens the sidebar, so reflow like the old+ // press path did or the preview overlaps the+ // terminal.+ let previous_width = self.right_sidebar_width();+ self.open_right_sidebar_file_path(state.path);+ self.invalidate_or_reflow_right_sidebar(previous_width, context);+ }+ }+ return;+ }if completed_drag.is_some() {// Completed a dragreturn;@@ -1052,6 +1078,17 @@ impl super::TermWindow {None};+ // A press anywhere other than the row being renamed commits a pending+ // inline rename (Enter semantics); otherwise the editor stays armed+ // and keeps swallowing keyboard input after the user clicked away.+ if matches!(event.kind, WMEK::Press(_))+ && self.inline_tab_rename.is_some()+ && !self.ui_item_hosts_inline_rename(ui_item.as_ref().map(|item| &item.item_type))+ {+ self.finish_inline_tab_rename(true);+ context.invalidate();+ }+if let Some(item) = ui_item.clone() {if capture_mouse {self.current_mouse_capture = Some(MouseCapture::UI);@@ -1424,12 +1461,88 @@ impl super::TermWindow {}UIItemType::ContextMenuBackdrop | UIItemType::ContextMenuItem(_) => {}UIItemType::PaneNav { .. } => {}+ UIItemType::RightSidebarFileRow(_) => {+ self.drag_right_sidebar_file_row(item, start_event, event, context);+ }_ => {log::error!("drag not implemented for {:?}", item);}}}+ fn drag_right_sidebar_file_row(+ &mut self,+ item: UIItem,+ start_event: MouseEvent,+ event: MouseEvent,+ context: &dyn WindowOps,+ ) {+ if let Some(state) = self.right_sidebar_file_drag.as_mut() {+ if !state.active {+ let dx = event.coords.x - state.start.x;+ let dy = event.coords.y - state.start.y;+ // ~5px of travel turns the pending click into a drag+ if dx * dx + dy * dy >= 25 {+ state.active = true;+ }+ }+ state.current = event.coords;+ if state.active {+ context.set_cursor(Some(MouseCursor::Hand));+ context.invalidate();+ }+ }+ // drag_ui_item takes `dragging` on every move; keep the drag armed+ self.dragging.replace((item, start_event));+ }++ fn drop_right_sidebar_file_drag(+ &mut self,+ state: super::FileDragState,+ event: &MouseEvent,+ column: usize,+ row: i64,+ ) {+ // Only a drop over bare terminal ground counts: any UI chrome under+ // the pointer (sidebars, tab bar, splits) or an active content view+ // cancels silently.+ if self.resolve_ui_item(event).is_some() || self.content_view_foreground() {+ return;+ }+ let px = event.coords.x as f32;+ let py = event.coords.y as f32;+ let area = self.content_view_area();+ if px < area.min_x() || px >= area.max_x() || py < area.min_y() || py >= area.max_y() {+ return;+ }++ // Paste into the pane under the drop point (splits!), falling back+ // to the active pane. Focus is deliberately left unchanged.+ let mut target = None;+ for pos in self.get_panes_to_render() {+ if row >= pos.top as i64+ && row <= (pos.top + pos.height) as i64+ && column >= pos.left+ && column <= pos.left + pos.width+ {+ target = Some(pos.pane);+ break;+ }+ }+ let Some(pane) = target.or_else(|| self.get_active_pane_or_overlay()) else {+ return;+ };++ let mut text = self+ .config+ .quote_dropped_files+ .escape(&state.path.to_string_lossy());+ text.push(' ');+ if let Err(err) = pane.send_paste(&text) {+ log::error!("failed to paste dropped file path: {err:#}");+ }+ }+fn drag_workspace_sidebar_resize(&mut self,item: UIItem,@@ -1627,6 +1740,7 @@ impl super::TermWindow {self.mouse_event_right_sidebar_snippet(item.clone(), event, context);}UIItemType::RightSidebarFileFilter+ | UIItemType::RightSidebarFileRefresh| UIItemType::RightSidebarFileRow(_)| UIItemType::RightSidebarFileBack| UIItemType::RightSidebarFileOpen@@ -1801,6 +1915,7 @@ impl super::TermWindow {self.mouse_event_right_sidebar_snippet(item.clone(), event, context);}UIItemType::RightSidebarFileFilter+ | UIItemType::RightSidebarFileRefresh| UIItemType::RightSidebarFileRow(_)| UIItemType::RightSidebarFileBack| UIItemType::RightSidebarFileOpen@@ -2082,8 +2197,11 @@ impl super::TermWindow {let previous_width = self.right_sidebar_width();self.right_sidebar_mode = mode;// Leaving the file view (e.g. switching to Snippets/Tasks) makes the- // file index idle; schedule it for release if nothing reopens it.- if !self.right_sidebar_file_view_active() {+ // file index idle; schedule it for release. Entering it refreshes ++ // (re)starts the periodic re-scan.+ if self.right_sidebar_file_view_active() {+ self.kick_right_sidebar_file_rescan_cycle();+ } else {self.schedule_right_sidebar_file_memory_release();}self.invalidate_or_reflow_right_sidebar(previous_width, context);@@ -2212,14 +2330,31 @@ impl super::TermWindow {self.dragging.replace((item, event));}}+ (UIItemType::RightSidebarFileRefresh, WMEK::Press(MousePress::Left)) => {+ self.clear_right_sidebar_text_focus();+ self.force_right_sidebar_file_rescan();+ }(UIItemType::RightSidebarFileRow(path), WMEK::Press(MousePress::Left)) => {+ if self.is_renaming_sidebar_file(&path) {+ // Clicking the row that hosts the inline rename editor+ // must not arm a drag or re-open the file.+ return;+ }self.clear_right_sidebar_text_focus();- self.open_right_sidebar_file_path(path);+ // Don't open yet: arm a potential drag toward the terminal.+ // If the pointer never crosses the threshold, the release+ // handler treats it as a click and opens the file.+ self.right_sidebar_file_drag = Some(super::FileDragState {+ path,+ start: event.coords,+ current: event.coords,+ active: false,+ });+ self.dragging.replace((item.clone(), event));}(UIItemType::RightSidebarFileRow(path), WMEK::Press(MousePress::Right)) => {self.clear_right_sidebar_text_focus();- self.right_sidebar_file_selected = Some(path);- self.show_right_sidebar_file_open_with_menu(context, event.coords);+ self.show_right_sidebar_file_context_menu(context, event.coords, path);}(UIItemType::RightSidebarFileBack, WMEK::Press(MousePress::Left)) => {self.clear_right_sidebar_text_focus();diff --git a/wezterm-gui/src/termwindow/render/paint.rs b/wezterm-gui/src/termwindow/render/paint.rsindex 9832429e..0c65e2fd 100644--- a/wezterm-gui/src/termwindow/render/paint.rs+++ b/wezterm-gui/src/termwindow/render/paint.rs@@ -362,6 +362,92 @@ impl crate::TermWindow {Ok(())}+ /// Floating label that follows the cursor while a Files-panel row is+ /// being dragged toward the terminal. Painted after everything else so+ /// it stays on top; deliberately registers no UIItem (hit-transparent).+ fn paint_file_drag_ghost(&mut self) -> anyhow::Result<()> {+ let Some(state) = self.right_sidebar_file_drag.as_ref() else {+ return Ok(());+ };+ if !state.active {+ return Ok(());+ }+ let label = state+ .path+ .file_name()+ .map(|name| name.to_string_lossy().into_owned())+ .unwrap_or_else(|| state.path.to_string_lossy().into_owned());+ if label.is_empty() {+ return Ok(());+ }+ let anchor = state.current;++ let settings = crate::native_settings::load();+ let font_size = crate::native_settings::home_font_size(&settings);+ let ui_font = self+ .fonts+ .title_font_with_size(font_size)+ .context("file drag ghost font")?;+ let metrics = crate::utilsprites::RenderMetrics::with_font_metrics(&ui_font.metrics());+ let line_height = metrics.cell_size.height as f32;++ let (bg, fg) = match crate::native_settings::effective_appearance() {+ window::Appearance::Light | window::Appearance::LightHighContrast => (+ LinearRgba::with_srgba(245, 245, 248, 235),+ LinearRgba::with_srgba(40, 40, 48, 255),+ ),+ window::Appearance::Dark | window::Appearance::DarkHighContrast => (+ LinearRgba::with_srgba(58, 58, 66, 235),+ LinearRgba::with_srgba(235, 235, 240, 255),+ ),+ };++ let gl_state = self.render_state.as_ref().unwrap();+ let layer = gl_state+ .layer_for_zindex(0)+ .context("file drag ghost layer")?;+ let mut layers = layer.quad_allocator();++ let ctx = DrawContext::new(gl_state, self.dimensions, &metrics);+ let max_width = (self.dimensions.pixel_width as f32 * 0.4).max(80.0);+ let display_text = ctx.text_with_ellipsis(&ui_font, &label, max_width);+ let text_width = ctx+ .measure_text_width(&ui_font, &display_text)+ .min(max_width);++ let pad_x = 8.0;+ let pad_y = 4.0;+ let pill_w = text_width + pad_x * 2.0;+ let pill_h = line_height + pad_y * 2.0;+ let x = (anchor.x as f32 + 12.0)+ .min(self.dimensions.pixel_width as f32 - pill_w)+ .max(0.0);+ let y = (anchor.y as f32 + 12.0)+ .min(self.dimensions.pixel_height as f32 - pill_h)+ .max(0.0);++ self.filled_rectangle(+ &mut layers,+ 0,+ euclid::rect(x, y, pill_w, pill_h),+ bg,+ )+ .context("file drag ghost background")?;+ ctx.draw_text_on_layer(+ &mut layers,+ 2,+ &ui_font,+ x + pad_x,+ y + pad_y,+ &display_text,+ fg,+ max_width,+ )+ .context("file drag ghost label")?;++ Ok(())+ }+pub fn paint_pass(&mut self) -> anyhow::Result<()> {{let gl_state = self.render_state.as_ref().unwrap();@@ -526,6 +612,8 @@ impl crate::TermWindow {drop(layers);self.paint_modal().context("paint_modal")?;self.paint_context_menu().context("paint_context_menu")?;+ self.paint_file_drag_ghost()+ .context("paint_file_drag_ghost")?;Ok(())}diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rsindex a9c6f498..15fa18d4 100644--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs@@ -13,7 +13,7 @@ use crate::termwindow::{RightSidebarFilePreviewLine, RightSidebarFilePreviewSelection,RightSidebarFilePreviewSelectionPoint, RightSidebarFilePreviewSliceCacheKey,RightSidebarFilePreviewSliceCacheValue, RightSidebarFilePreviewSpan, RightSidebarFileTreeRow,- RightSidebarFileView, RightSidebarInputLayout, RightSidebarMode,+ RightSidebarFileView, RightSidebarFileViewState, RightSidebarInputLayout, RightSidebarMode,RightSidebarOpenWithCacheEntry, RightSidebarSnippetField, RightSidebarSnippetView,TermWindowNotif, UIItem, UIItemType, UiShapeCacheLookup,};@@ -106,6 +106,10 @@ const FILE_INDEX_ENTRY_LIMIT: usize = 100_000;// How long the file panel must stay closed/idle before its in-memory index and// buffers are released. Reopening within this window keeps everything resident.const FILE_INDEX_IDLE_RELEASE_SECS: u64 = 30;+// How often the Files panel re-scans the tree while it's visible + focused.+const FILE_INDEX_RESCAN_SECS: u64 = 90;+// Max number of (root, project) view-state snapshots kept in memory.+const FILE_VIEW_STATE_CACHE_CAP: usize = 32;const FILE_FILTER_DEBOUNCE_MS: u64 = 350;#[derive(Debug, Clone, Copy)]@@ -453,11 +457,14 @@ impl crate::TermWindow {self.right_sidebar_collapsed = !self.right_sidebar_collapsed;if self.right_sidebar_collapsed {self.schedule_right_sidebar_file_memory_release();+ } else {+ self.kick_right_sidebar_file_rescan_cycle();}}pub fn expand_right_sidebar(&mut self) {self.right_sidebar_collapsed = false;+ self.kick_right_sidebar_file_rescan_cycle();}/// The file panel (and its in-memory index) is only relevant while the right@@ -501,6 +508,10 @@ impl crate::TermWindow {return;}+ // Remember the view (paths/scroll/filter, a few KB) BEFORE the teardown+ // wipes selected/preview, so reopening this root restores where we were.+ self.save_right_sidebar_file_view_state();+if let Some(cancel) = self.right_sidebar_file_index_cancel.take() {cancel.store(true, AtomicOrdering::Relaxed);}@@ -517,6 +528,79 @@ impl crate::TermWindow {self.invalidate_window();}+ fn right_sidebar_file_view_state_key(&self) -> Option<(PathBuf, String)> {+ self.right_sidebar_file_index_root+ .clone()+ .map(|root| (root, self.right_sidebar_file_index_project_name.clone()))+ }++ /// Snapshot the active (root, project)'s Files view (paths/scroll/effective+ /// filter) so it survives idle-release / workspace switch / re-scan. KB-scale,+ /// LRU-bounded; never holds the index.+ fn save_right_sidebar_file_view_state(&mut self) {+ let Some(key) = self.right_sidebar_file_view_state_key() else {+ return;+ };+ let state = RightSidebarFileViewState {+ view: self.right_sidebar_file_view.clone(),+ selected: self.right_sidebar_file_selected.clone(),+ expanded: self.right_sidebar_file_expanded.clone(),+ tree_scroll: self.right_sidebar_file_tree_scroll_offset,+ preview_scroll: self.right_sidebar_file_preview_scroll_offset,+ preview_horizontal: self.right_sidebar_file_preview_horizontal_offset,+ filter: self.right_sidebar_file_applied_filter.clone(),+ };+ if !self.right_sidebar_file_view_state_by_root.contains_key(&key) {+ self.right_sidebar_file_view_state_order.push_back(key.clone());+ }+ self.right_sidebar_file_view_state_by_root.insert(key, state);+ while self.right_sidebar_file_view_state_order.len() > FILE_VIEW_STATE_CACHE_CAP {+ if let Some(old) = self.right_sidebar_file_view_state_order.pop_front() {+ self.right_sidebar_file_view_state_by_root.remove(&old);+ }+ }+ }++ /// Restore the remembered view for `key`, or apply defaults (tree view, only+ /// the project root expanded, no filter). Re-loads the preview asynchronously+ /// when one was open (the lines were dropped on release), preserving scroll.+ fn restore_right_sidebar_file_view_state(&mut self, key: &(PathBuf, String)) {+ self.right_sidebar_file_expanded_version =+ self.right_sidebar_file_expanded_version.wrapping_add(1);++ let Some(state) = self.right_sidebar_file_view_state_by_root.get(key).cloned() else {+ self.right_sidebar_file_view = RightSidebarFileView::Tree;+ self.right_sidebar_file_selected = None;+ self.right_sidebar_file_expanded.clear();+ self.right_sidebar_file_expanded.insert(path_key(&key.0));+ self.right_sidebar_file_tree_scroll_offset = 0.0;+ self.right_sidebar_file_filter.set_text_end(String::new());+ self.right_sidebar_file_applied_filter.clear();+ self.right_sidebar_file_filter_debounce_until = None;+ return;+ };++ self.right_sidebar_file_expanded = state.expanded;+ self.right_sidebar_file_tree_scroll_offset = state.tree_scroll;+ // Filter: set all three coupled fields so the first frame is consistent.+ self.right_sidebar_file_filter.set_text_end(state.filter.clone());+ self.right_sidebar_file_applied_filter = state.filter;+ self.right_sidebar_file_filter_debounce_until = None;++ match (state.view, state.selected) {+ (RightSidebarFileView::Preview, Some(path)) if path.is_file() => {+ self.open_right_sidebar_file_path_inner(+ path,+ Some((state.preview_scroll, state.preview_horizontal)),+ );+ }+ _ => {+ self.right_sidebar_file_view = RightSidebarFileView::Tree;+ self.right_sidebar_file_selected = None;+ }+ }+ }+pub(crate) fn right_sidebar_toggle_icon(&self) -> SvgIcon {if self.right_sidebar_collapsed {SvgIcon::PanelRightOpen@@ -703,6 +787,18 @@ impl crate::TermWindow {}pub(crate) fn open_right_sidebar_file_path(&mut self, path: PathBuf) {+ self.open_right_sidebar_file_path_inner(path, None);+ }++ /// `restore_scroll` re-applies a remembered preview scroll once the async+ /// load completes (consumed in `apply_right_sidebar_file_preview_result`);+ /// `None` (a normal click) resets to the top.+ fn open_right_sidebar_file_path_inner(+ &mut self,+ path: PathBuf,+ restore_scroll: Option<(f32, usize)>,+ ) {+ self.right_sidebar_file_preview_restore_scroll = restore_scroll;self.right_sidebar_file_focus = None;if path.is_dir() {let key = path_key(&path);@@ -771,6 +867,27 @@ impl crate::TermWindow {.detach();}+ pub(crate) fn trash_sidebar_file(&mut self, path: &Path) {+ if let Err(err) = trash::delete(path) {+ log::error!("failed to move {} to trash: {err:#}", path.display());+ return;+ }+ if self.right_sidebar_file_selected.as_deref() == Some(path) {+ // Closing the preview narrows the sidebar, so the terminal must+ // reflow or it keeps rendering under the old, wider sidebar.+ let previous_width = self.right_sidebar_width();+ self.close_right_sidebar_file_preview();+ if let Some(window) = self.window.as_ref().cloned() {+ if self.right_sidebar_width() != previous_width {+ let dimensions = self.dimensions;+ self.apply_dimensions(&dimensions, None, &window);+ }+ window.invalidate();+ }+ }+ self.force_right_sidebar_file_rescan();+ }+pub(crate) fn close_right_sidebar_file_preview(&mut self) {self.right_sidebar_file_view = RightSidebarFileView::Tree;self.right_sidebar_file_selected = None;@@ -899,8 +1016,14 @@ impl crate::TermWindow {self.right_sidebar_file_preview_message = result.message;self.right_sidebar_file_preview_truncated = result.truncated;self.right_sidebar_file_preview_selection = None;- self.right_sidebar_file_preview_scroll_offset = 0.0;- self.right_sidebar_file_preview_horizontal_offset = 0;+ // When restoring a remembered preview, re-apply the saved scroll once the+ // lines arrive (clamped on paint); otherwise reset to the top.+ let (scroll, horizontal) = self+ .right_sidebar_file_preview_restore_scroll+ .take()+ .unwrap_or((0.0, 0));+ self.right_sidebar_file_preview_scroll_offset = scroll;+ self.right_sidebar_file_preview_horizontal_offset = horizontal;self.invalidate_window();}@@ -936,6 +1059,54 @@ impl crate::TermWindow {self.show_term_context_menu(context, anchor, items);}+ pub(crate) fn show_right_sidebar_file_context_menu(+ &mut self,+ context: &dyn WindowOps,+ anchor: window::Point,+ path: PathBuf,+ ) {+ // Deliberately not touching right_sidebar_file_selected: that field+ // tracks the open preview, and every action here carries its own path.+ let items = self.right_sidebar_file_context_menu_items(&path);+ self.show_term_context_menu(context, anchor, items);+ }++ /// File-operations menu for right-clicking a Files row. Open With lives+ /// in the preview toolbar only, so this menu stays about the file itself.+ fn right_sidebar_file_context_menu_items(&self, path: &Path) -> Vec<ContextMenuItem> {+ let path_string = path.to_string_lossy().to_string();+ let mut items = Vec::new();+ if !path.is_dir() {+ items.push(ContextMenuItem::item_with_icon(+ "Open",+ "arrow.up.forward.app",+ KeyAssignment::OpenFileWithSystemDefault(path_string.clone()),+ ));+ }+ items.push(ContextMenuItem::item_with_icon(+ "Reveal in Folder",+ "folder",+ KeyAssignment::RevealFileInFolder(path_string.clone()),+ ));+ items.push(ContextMenuItem::item_with_icon(+ "Copy Path",+ "doc.on.doc",+ KeyAssignment::CopyFilePathToClipboard(path_string.clone()),+ ));+ items.push(ContextMenuItem::Separator);+ items.push(ContextMenuItem::item_with_icon(+ "Rename...",+ "pencil",+ KeyAssignment::RenameSidebarFile(path_string.clone()),+ ));+ items.push(ContextMenuItem::item_with_icon(+ "Move to Trash",+ "trash",+ KeyAssignment::TrashSidebarFile(path_string),+ ));+ items+ }+fn start_right_sidebar_open_with_load_if_needed(&mut self, key: &str, path: &Path) {if self.right_sidebar_open_with_cache@@ -1010,27 +1181,91 @@ impl crate::TermWindow {let current_id = self.current_right_sidebar_open_with_app(key).map(|app| app.id);- let Some(RightSidebarOpenWithCacheEntry::Ready(candidates)) =- self.right_sidebar_open_with_cache.get(key)- else {- return Vec::new();+ // Even with no platform candidates (Loading/Failed) the menu still+ // offers the user's custom apps and the "Other…" picker.+ let mut candidates = match self.right_sidebar_open_with_cache.get(key) {+ Some(RightSidebarOpenWithCacheEntry::Ready(candidates)) => candidates.clone(),+ _ => Vec::new(),};- sorted_open_with_candidates(candidates.clone(), current_id.as_deref())- .into_iter()- .filter(|candidate| current_id.as_deref() != Some(candidate.id.as_str()))- .map(|candidate| {- ContextMenuItem::item_with_icon(- format!("Open With {}", candidate.label),- "app",- KeyAssignment::OpenFileWith {- path: path_string.clone(),- app: candidate.id,- label: candidate.label,- },- )- })- .collect()+ let custom_apps = crate::native_settings::right_sidebar_custom_open_with_apps();+ let custom_ids: std::collections::HashSet<String> =+ custom_apps.iter().map(|app| app.id.clone()).collect();+ for app in custom_apps {+ if candidates.iter().any(|candidate| candidate.id == app.id) {+ // Platform entry wins so is_default stays accurate+ continue;+ }+ // Drop custom entries whose app was uninstalled; `desktop:` ids+ // (Linux) aren't paths, so they skip the existence check.+ if !app.id.starts_with("desktop:") && !Path::new(&app.id).exists() {+ continue;+ }+ candidates.push(wezterm_open_url::OpenWithCandidate {+ id: app.id,+ label: app.label,+ icon_path: None,+ is_default: false,+ });+ }++ let saved_id = self+ .right_sidebar_open_with_app+ .as_ref()+ .map(|app| app.id.clone());+ candidates+ .retain(|candidate| open_with_candidate_allowed(candidate, &custom_ids, saved_id.as_deref()));++ let mut items: Vec<ContextMenuItem> =+ sorted_open_with_candidates(candidates, current_id.as_deref())+ .into_iter()+ .filter(|candidate| current_id.as_deref() != Some(candidate.id.as_str()))+ .map(|candidate| {+ ContextMenuItem::item_with_icon(+ format!("Open With {}", candidate.label),+ "app",+ KeyAssignment::OpenFileWith {+ path: path_string.clone(),+ app: candidate.id,+ label: candidate.label,+ },+ )+ })+ .collect();++ if !items.is_empty() {+ items.push(ContextMenuItem::Separator);+ }+ items.push(ContextMenuItem::item_with_icon(+ "Open With Other…",+ "app",+ KeyAssignment::PickOpenFileWithApp(path_string),+ ));+ items+ }++ /// Completion of the "Open With Other…" app picker: persist the picked+ /// app as a custom entry + current preference, then open the file.+ pub(crate) fn finish_pick_open_with_app(&mut self, file_path: &str, app_path: &Path) {+ let (id, label) = wezterm_open_url::app_candidate_for_picked_path(app_path);+ if id.is_empty() {+ return;+ }+ let app = crate::native_settings::NativeOpenWithApp {+ id: id.clone(),+ label,+ };+ if let Err(err) =+ crate::native_settings::add_right_sidebar_custom_open_with_app(app.clone())+ {+ log::error!("failed to save custom Open With app: {err:#}");+ }+ self.right_sidebar_open_with_app = Some(app.clone());+ if let Err(err) = crate::native_settings::save_right_sidebar_open_with_app(app) {+ log::error!("failed to save Open With app selection: {err:#}");+ }+ wezterm_open_url::open_path_with_candidate(Path::new(file_path), &id);+ self.invalidate_window();}fn current_right_sidebar_open_with_app(@@ -1302,21 +1537,86 @@ impl crate::TermWindow {return;}+ let new_key = (root.path.clone(), root.project_name.clone());+if !same_root {let previous_width = self.right_sidebar_width();+ // Remember the outgoing root's view, then restore the incoming one+ // (replaces the old blanket clear of expanded + preview).+ self.save_right_sidebar_file_view_state();self.close_right_sidebar_file_preview();self.right_sidebar_file_browse_rows.clear();self.right_sidebar_file_browse_cache_key = None;- self.right_sidebar_file_expanded.clear();- 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);+ self.right_sidebar_file_index_root = Some(root.path.clone());+ self.right_sidebar_file_index_project_name = root.project_name.clone();+ self.restore_right_sidebar_file_view_state(&new_key);if self.right_sidebar_width() != previous_width {self.schedule_right_sidebar_reflow();}+ } else {+ // Same root, status Empty/Failed (e.g. after idle-release): restore+ // the view the release tore down before rebuilding.+ self.restore_right_sidebar_file_view_state(&new_key);}+ self.spawn_right_sidebar_file_index_build(+ root.path.clone(),+ root.project_name.clone(),+ false,+ false,+ );+ }++ fn clear_right_sidebar_file_root_for_unavailable_project(&mut self) {+ if self.right_sidebar_file_index_root.is_some() {+ self.save_right_sidebar_file_view_state();+ }+ let previous_width = self.right_sidebar_width();+ if let Some(cancel) = self.right_sidebar_file_index_cancel.take() {+ cancel.store(true, AtomicOrdering::Relaxed);+ }+ if let Some(cancel) = self.right_sidebar_file_search_cancel.take() {+ cancel.store(true, AtomicOrdering::Relaxed);+ }+ self.close_right_sidebar_file_preview();+ self.clear_right_sidebar_file_search();+ self.right_sidebar_file_index_root = None;+ self.right_sidebar_file_index_project_name.clear();+ self.right_sidebar_file_index_status = RightSidebarFileIndexStatus::Empty;+ self.right_sidebar_file_index = None;+ self.right_sidebar_file_browse_rows.clear();+ self.right_sidebar_file_browse_cache_key = None;+ self.right_sidebar_file_refreshing = false;+ if self.right_sidebar_width() != previous_width {+ self.schedule_right_sidebar_reflow();+ }+ }++ fn sync_right_sidebar_file_root_for_current_workspace(+ &mut self,+ ) -> Result<RightSidebarFileRoot, String> {+ let root = match self.active_local_project_for_files() {+ Ok(root) => root,+ Err(err) => {+ self.clear_right_sidebar_file_root_for_unavailable_project();+ return Err(err);+ }+ };+ self.start_right_sidebar_file_index_if_needed(&root);+ Ok(root)+ }++ /// Build (or refresh) the file index on a background thread. `fresh` bypasses+ /// the shared-registry reuse (forces a real disk scan); `keep_showing` leaves+ /// the current tree + status on screen and only swaps the new `Arc` in on+ /// apply (no "Indexing files…" flicker during a refresh).+ fn spawn_right_sidebar_file_index_build(+ &mut self,+ root_path: PathBuf,+ project_name: String,+ fresh: bool,+ keep_showing: bool,+ ) {let Some(window) = self.window.as_ref().cloned() else {self.right_sidebar_file_index_status =RightSidebarFileIndexStatus::Failed("Window is unavailable".to_string());@@ -1326,38 +1626,52 @@ impl crate::TermWindow {if let Some(cancel) = self.right_sidebar_file_index_cancel.take() {cancel.store(true, AtomicOrdering::Relaxed);}- if let Some(cancel) = self.right_sidebar_file_search_cancel.take() {- cancel.store(true, AtomicOrdering::Relaxed);- }let index_cancel = Arc::new(AtomicBool::new(false));self.right_sidebar_file_index_cancel = Some(index_cancel.clone());self.right_sidebar_file_index_generation =self.right_sidebar_file_index_generation.wrapping_add(1);let generation = self.right_sidebar_file_index_generation;- let root_path = root.path.clone();- let project_name = root.project_name.clone();self.right_sidebar_file_index_root = Some(root_path.clone());self.right_sidebar_file_index_project_name = project_name.clone();- self.right_sidebar_file_index_status = RightSidebarFileIndexStatus::Indexing;- self.right_sidebar_file_index = None;- self.right_sidebar_file_search_generation =- self.right_sidebar_file_search_generation.wrapping_add(1);- self.right_sidebar_file_search_query.clear();- self.right_sidebar_file_search_rows.clear();- self.right_sidebar_file_searching = false;- self.right_sidebar_file_tree_scroll_offset = 0.0;++ if keep_showing {+ // Refresh: keep the current tree + Ready visible; `apply` swaps the+ // new index in when it arrives. View state is left untouched.+ self.right_sidebar_file_refreshing = true;+ } else {+ self.right_sidebar_file_refreshing = false;+ self.right_sidebar_file_index_status = RightSidebarFileIndexStatus::Indexing;+ self.right_sidebar_file_index = None;+ if let Some(cancel) = self.right_sidebar_file_search_cancel.take() {+ cancel.store(true, AtomicOrdering::Relaxed);+ }+ self.right_sidebar_file_search_generation =+ self.right_sidebar_file_search_generation.wrapping_add(1);+ self.right_sidebar_file_search_query.clear();+ self.right_sidebar_file_search_rows.clear();+ self.right_sidebar_file_searching = false;+ // tree scroll is owned by restore_right_sidebar_file_view_state.+ }let index_root_path = root_path.clone();let index_project_name = project_name.clone();let worker_cancel = index_cancel.clone();promise::spawn::spawn(async move {let result = promise::spawn::spawn_into_new_thread(move || {- Ok(build_or_reuse_shared_file_index(- &index_root_path,- &index_project_name,- &worker_cancel,- ))+ Ok(if fresh {+ build_fresh_shared_file_index(+ &index_root_path,+ &index_project_name,+ &worker_cancel,+ )+ } else {+ build_or_reuse_shared_file_index(+ &index_root_path,+ &index_project_name,+ &worker_cancel,+ )+ })}).await.unwrap_or_else(|err| Err(format!("Unable to index files: {err}")));@@ -1373,6 +1687,84 @@ impl crate::TermWindow {.detach();}+ /// Force a real (registry-bypassing) re-scan of the current root while+ /// 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 !self.right_sidebar_file_view_active() || self.right_sidebar_file_refreshing {+ return;+ }+ if self+ .sync_right_sidebar_file_root_for_current_workspace()+ .is_err()+ {+ return;+ }+ if !matches!(+ self.right_sidebar_file_index_status,+ RightSidebarFileIndexStatus::Ready+ ) {+ return;+ }+ let Some((root, project)) = self.right_sidebar_file_view_state_key() else {+ return;+ };+ self.spawn_right_sidebar_file_index_build(root, project, true, true);+ }++ /// Refresh now (if a tree is already loaded) and (re)start the 90s periodic+ /// 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 !(self.right_sidebar_file_view_active() && self.focused.is_some()) {+ return;+ }+ if self+ .sync_right_sidebar_file_root_for_current_workspace()+ .is_err()+ {+ return;+ }+ if matches!(+ self.right_sidebar_file_index_status,+ RightSidebarFileIndexStatus::Ready+ ) {+ self.force_right_sidebar_file_rescan();+ }+ self.schedule_right_sidebar_file_rescan();+ }++ /// 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) {+ let Some(window) = self.window.as_ref().cloned() else {+ return;+ };+ self.right_sidebar_file_rescan_token =+ self.right_sidebar_file_rescan_token.wrapping_add(1);+ let token = self.right_sidebar_file_rescan_token;+ let target = Instant::now() + Duration::from_secs(FILE_INDEX_RESCAN_SECS);+ promise::spawn::spawn(async move {+ smol::Timer::at(target).await;+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.run_right_sidebar_file_periodic_rescan(token);+ })));+ })+ .detach();+ }++ fn run_right_sidebar_file_periodic_rescan(&mut self, token: u64) {+ // Superseded, panel hidden, or window blurred → let the cycle lapse.+ if token != self.right_sidebar_file_rescan_token+ || !self.right_sidebar_file_view_active()+ || self.focused.is_none()+ {+ return;+ }+ self.force_right_sidebar_file_rescan();+ self.schedule_right_sidebar_file_rescan();+ }+fn apply_right_sidebar_file_index_result(&mut self,generation: u64,@@ -1387,11 +1779,20 @@ impl crate::TermWindow {return;}self.right_sidebar_file_index_cancel = None;+ let was_refreshing = self.right_sidebar_file_refreshing;+ self.right_sidebar_file_refreshing = false;match result {Ok(index) => {self.right_sidebar_file_index_status = RightSidebarFileIndexStatus::Ready;self.right_sidebar_file_index = Some(index);+ if was_refreshing {+ self.right_sidebar_file_browse_rows.clear();+ self.right_sidebar_file_browse_cache_key = None;+ if !self.right_sidebar_file_applied_filter.trim().is_empty() {+ self.clear_right_sidebar_file_search();+ }+ }}Err(err) => {self.right_sidebar_file_index_status = RightSidebarFileIndexStatus::Failed(err);@@ -2421,6 +2822,10 @@ impl crate::TermWindow {let ui_cell_height = ui_metrics.cell_size.height as usize;let icon_size = (ui_cell_height + 6).clamp(20, 24);+ if self.right_sidebar_mode == RightSidebarMode::Chat {+ let _ = self.sync_right_sidebar_file_root_for_current_workspace();+ }+if let Some(preview_rect) = self.right_sidebar_file_preview_rect() {let file_font_size = self.right_sidebar_file_preview_font_size();let file_font = self@@ -3066,6 +3471,14 @@ 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 + 12).clamp(28, 38);+ let refresh_gap = 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 + FILE_FILTER_HEIGHT.saturating_sub(refresh_size) / 2;+let filter_input = self.right_sidebar_file_filter.clone();self.paint_snippet_text_box(layers,@@ -3076,7 +3489,7 @@ impl crate::TermWindow {muted_fg,content_x,content_top,- content_width,+ filter_width,FILE_FILTER_HEIGHT,Some(SvgIcon::Search),"Filter files",@@ -3085,9 +3498,20 @@ impl crate::TermWindow {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 + FILE_FILTER_HEIGHT + FILE_TREE_TOP_GAP;- let root = match self.active_local_project_for_files() {+ let root = match self.sync_right_sidebar_file_root_for_current_workspace() {Ok(root) => root,Err(message) => {return self.paint_files_message(@@ -3112,7 +3536,6 @@ impl crate::TermWindow {self.right_sidebar_file_expanded_version =self.right_sidebar_file_expanded_version.wrapping_add(1);}- self.start_right_sidebar_file_index_if_needed(&root);let applied_filter = self.right_sidebar_file_filter_for_tree();let index = match self.right_sidebar_file_index_status.clone() {@@ -3508,11 +3931,12 @@ impl crate::TermWindow {}}let text_x = file_icon_x + row_icon_size + row_metrics.icon_gap;+ let row_title = self.sidebar_file_row_title(&row.path, &row.name);self.paint_sidebar_text(layers,ui_font,ui_metrics,- &row.name,+ &row_title,text_x,y + (row_metrics.row_height@@ -5724,6 +6148,86 @@ fn right_sidebar_open_with_cache_key(path: &Path) -> String {.unwrap_or_else(|| format!("path:{}", path.to_string_lossy()))}+const OPEN_WITH_DEV_TOOL_NEEDLES: &[&str] = &[+ "zed",+ "visual studio code",+ "vscode",+ "code",+ "cursor",+ "xcode",+ "android studio",+ "sublime",+ "webstorm",+ "intellij",+ "pycharm",+ "goland",+ "rustrover",+ "vim",+ "neovim",+ "emacs",+];++const OPEN_WITH_PRODUCTIVITY_NEEDLES: &[&str] = &[+ "excel",+ "numbers",+ "pages",+ "keynote",+ "word",+ "powerpoint",+ "preview",+ "textedit",+ "typora",+ "obsidian",+ "libreoffice",+ "onlyoffice",+ "okular",+ "evince",+];++/// Match allowlist needles against the app NAME only: matching the id/path+/// lets junk through (e.g. Instruments.app matches "xcode" merely because it+/// lives inside Xcode.app).+fn open_with_candidate_text(candidate: &wezterm_open_url::OpenWithCandidate) -> String {+ candidate.label.to_lowercase()+}++/// Candidates living in hidden directories (~/.cache tool runtimes and the+/// like) or nested inside another bundle (Xcode's Instruments, calibre's+/// viewer) are implementation details, not apps the user chose to install.+fn open_with_candidate_in_junk_location(candidate: &wezterm_open_url::OpenWithCandidate) -> bool {+ let id = &candidate.id;+ if !id.starts_with('/') {+ // Not an absolute path (e.g. Linux `desktop:` ids): no location info+ return false;+ }+ id.contains(".app/") || id.split('/').any(|component| component.starts_with('.'))+}++/// The Open With menu is curated: the system default, well-known editors /+/// office apps, the saved preference and the user's own additions. Every+/// other registered handler is noise and stays hidden.+fn open_with_candidate_allowed(+ candidate: &wezterm_open_url::OpenWithCandidate,+ custom_ids: &std::collections::HashSet<String>,+ saved_id: Option<&str>,+) -> bool {+ // Explicit user choices bypass the location heuristics+ if custom_ids.contains(&candidate.id) || saved_id == Some(candidate.id.as_str()) {+ return true;+ }+ if open_with_candidate_in_junk_location(candidate) {+ return false;+ }+ if candidate.is_default {+ return true;+ }+ let text = open_with_candidate_text(candidate);+ OPEN_WITH_DEV_TOOL_NEEDLES+ .iter()+ .chain(OPEN_WITH_PRODUCTIVITY_NEEDLES.iter())+ .any(|needle| text.contains(needle))+}+fn sorted_open_with_candidates(mut candidates: Vec<wezterm_open_url::OpenWithCandidate>,preferred_candidate_id: Option<&str>,@@ -5736,38 +6240,26 @@ fn sorted_open_with_candidates(.then_with(|| open_with_candidate_rank(a).cmp(&open_with_candidate_rank(b))).then_with(|| a.id.cmp(&b.id))});- candidates.truncate(20);+ candidates.truncate(10);candidates}fn open_with_candidate_rank(candidate: &wezterm_open_url::OpenWithCandidate) -> (u8, String) {- let text = format!("{} {}", candidate.label, candidate.id).to_lowercase();- let is_developer_tool = [- "zed",- "visual studio code",- "vscode",- "code",- "cursor",- "xcode",- "android studio",- "sublime",- "webstorm",- "intellij",- "pycharm",- "goland",- "rustrover",- "vim",- "neovim",- "emacs",- ]- .iter()- .any(|needle| text.contains(needle));- let rank = if is_developer_tool {+ let text = open_with_candidate_text(candidate);+ let rank = if OPEN_WITH_DEV_TOOL_NEEDLES+ .iter()+ .any(|needle| text.contains(needle))+ {0} else if candidate.is_default {1- } else {+ } else if OPEN_WITH_PRODUCTIVITY_NEEDLES+ .iter()+ .any(|needle| text.contains(needle))+ {2+ } else {+ 3};(rank, candidate.label.to_lowercase())}@@ -5993,6 +6485,29 @@ fn build_or_reuse_shared_file_index(Ok(index)}+/// Always scan disk (never returns a cached `Arc`) and publish the fresh index to+/// the shared registry. Used by the manual/periodic/focus **refresh** so it can't+/// "succeed" by handing back a stale index another window still holds.+fn build_fresh_shared_file_index(+ root: &Path,+ project_name: &str,+ cancel: &AtomicBool,+) -> Result<Arc<RightSidebarFileIndex>, String> {+ let index = Arc::new(build_right_sidebar_file_index_with_cancel(+ root,+ project_name,+ cancel,+ )?);+ if let Ok(mut registry) = shared_file_index_registry().lock() {+ registry.insert(+ (root.to_path_buf(), project_name.to_string()),+ Arc::downgrade(&index),+ );+ registry.retain(|_, weak| weak.strong_count() > 0);+ }+ Ok(index)+}+#[cfg(test)]fn build_right_sidebar_file_index(root: &Path,@@ -6546,7 +7061,8 @@ mod tests {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, search_right_sidebar_file_index, snippet_cursor_visible,+ open_with_candidate_allowed, right_sidebar_open_with_cache_key,+ search_right_sidebar_file_index, snippet_cursor_visible,snippet_run_buffer, sorted_open_with_candidates, visible_file_row_range,wrap_snippet_text_for_width, FILE_PREVIEW_HIGHLIGHT_CHAR_LIMIT, FILE_PREVIEW_MAX_BYTES,};@@ -6877,6 +7393,68 @@ mod tests {assert_eq!(labels, vec!["Zed", "VS Code", "TextEdit"]);}+ #[test]+ fn open_with_filter_hides_junk_candidates() {+ // Real-world LaunchServices output observed for a .md file+ fn cand(id: &str, label: &str, is_default: bool) -> wezterm_open_url::OpenWithCandidate {+ wezterm_open_url::OpenWithCandidate {+ id: id.to_string(),+ label: label.to_string(),+ icon_path: None,+ is_default,+ }+ }+ let candidates = vec![+ cand("/Applications/Typora.app", "Typora", true),+ cand("/Applications/MinerU.app", "MinerU", false),+ cand("/Applications/Xcode.app", "Xcode", false),+ cand("/Applications/calibre.app", "calibre", false),+ cand("/Applications/Cursor.app", "Cursor", false),+ cand("/Applications/Zed.app", "Zed", false),+ cand("/Applications/Visual Studio Code.app", "Visual Studio Code", false),+ cand(+ "/Applications/calibre.app/Contents/ebook-viewer.app",+ "ebook-viewer",+ false,+ ),+ cand("/System/Applications/TextEdit.app", "TextEdit", false),+ cand("/Applications/Microsoft Word.app", "Microsoft Word", false),+ cand(+ "/Users/u/.cache/codex-runtimes/native/libreoffice/LibreOfficeDev.app",+ "LibreOfficeDev",+ false,+ ),+ cand(+ "/Applications/Xcode.app/Contents/Applications/Instruments.app",+ "Instruments",+ false,+ ),+ cand("/Applications/Google Chrome.app", "Google Chrome", false),+ cand("/System/Applications/Notes.app", "Notes", false),+ cand("/Applications/010 Editor.app", "010 Editor", false),+ ];++ let custom_ids = HashSet::new();+ let kept: Vec<&str> = candidates+ .iter()+ .filter(|candidate| open_with_candidate_allowed(candidate, &custom_ids, None))+ .map(|candidate| candidate.label.as_str())+ .collect();++ assert_eq!(+ kept,+ vec![+ "Typora",+ "Xcode",+ "Cursor",+ "Zed",+ "Visual Studio Code",+ "TextEdit",+ "Microsoft Word",+ ]+ );+ }+#[test]fn preview_lines_from_text_highlights_known_file_types() {let path = std::path::Path::new("main.rs");diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rsindex 52a26dd7..0fdd5801 100644--- a/wezterm-gui/src/workspace_threads.rs+++ b/wezterm-gui/src/workspace_threads.rs@@ -235,6 +235,10 @@ lazy_static::lazy_static! {static ref WINDOW_SPACES: Mutex<HashMap<u64, SpaceId>> = Mutex::new(HashMap::new());static ref MATERIALIZING_LAYOUT_WORKSPACES: Mutex<HashMap<String, usize>> =Mutex::new(HashMap::new());+ static ref WORK_RUNNING_LAST_SEEN: Mutex<HashMap<String, std::time::Instant>> =+ Mutex::new(HashMap::new());+ static ref WORK_STATUS_RECHECK_PENDING: Mutex<std::collections::HashSet<String>> =+ Mutex::new(std::collections::HashSet::new());}static THREAD_STORE_PERSIST_SCHEDULED: AtomicBool = AtomicBool::new(false);@@ -834,8 +838,67 @@ pub fn refresh_thread_work_for_pane(pane_id: PaneId) -> bool {refresh_thread_work_for_workspace(&workspace)}+/// The Running signal derives from pane titles / progress escapes that can+/// flicker off for a few frames while the user types, which used to strobe+/// the sidebar spinner (and spuriously latch work_finished_unseen). Hold+/// Running through short Idle observations; a deferred re-check settles the+/// state to Idle once the grace period truly elapses.+const WORK_RUNNING_FALL_DEBOUNCE: Duration = Duration::from_millis(800);++fn debounce_work_status(+ workspace: &str,+ observed: WorkspaceThreadWorkStatus,+) -> WorkspaceThreadWorkStatus {+ let mut last_seen = WORK_RUNNING_LAST_SEEN.lock();+ match observed {+ WorkspaceThreadWorkStatus::Running => {+ last_seen.insert(workspace.to_string(), std::time::Instant::now());+ observed+ }+ WorkspaceThreadWorkStatus::Idle => {+ let Some(last) = last_seen.get(workspace) else {+ return observed;+ };+ let elapsed = last.elapsed();+ if elapsed < WORK_RUNNING_FALL_DEBOUNCE {+ schedule_work_status_recheck(+ workspace.to_string(),+ WORK_RUNNING_FALL_DEBOUNCE - elapsed,+ );+ WorkspaceThreadWorkStatus::Running+ } else {+ last_seen.remove(workspace);+ observed+ }+ }+ WorkspaceThreadWorkStatus::NeedsAttention | WorkspaceThreadWorkStatus::FinishedUnseen => {+ last_seen.remove(workspace);+ observed+ }+ }+}++fn schedule_work_status_recheck(workspace: String, delay: Duration) {+ if !WORK_STATUS_RECHECK_PENDING.lock().insert(workspace.clone()) {+ return;+ }+ std::thread::spawn(move || {+ std::thread::sleep(delay);+ WORK_STATUS_RECHECK_PENDING.lock().remove(&workspace);+ promise::spawn::spawn_into_main_thread(async move {+ if refresh_thread_work_for_workspace(&workspace) {+ if let Some(front_end) = crate::frontend::try_front_end() {+ front_end.invalidate_all_windows();+ }+ }+ })+ .detach();+ });+}+pub fn refresh_thread_work_for_workspace(workspace: &str) -> bool {let observed = scan_workspace_work_status(workspace);+ let observed = debounce_work_status(workspace, observed);let mut store = THREAD_STORE.lock();let Some(change) = store.observe_thread_work_for_workspace(workspace, observed) else {return false;diff --git a/wezterm-open-url/Cargo.toml b/wezterm-open-url/Cargo.tomlindex b77ac821..9a1675ae 100644--- a/wezterm-open-url/Cargo.toml+++ b/wezterm-open-url/Cargo.toml@@ -9,6 +9,9 @@ publish = false[dependencies]winapi = {workspace=true, features=["shellapi"]}+[target.'cfg(windows)'.dependencies]+winreg.workspace = true+[target.'cfg(target_os = "macos")'.dependencies]core-foundation.workspace = truecore-foundation-sys = "0.8"diff --git a/wezterm-open-url/src/lib.rs b/wezterm-open-url/src/lib.rsindex c555f195..97cd16a5 100644--- a/wezterm-open-url/src/lib.rs+++ b/wezterm-open-url/src/lib.rs@@ -20,6 +20,31 @@ pub fn open_with_candidates(path: &Path) -> Vec<OpenWithCandidate> {platform_open_with_candidates(path)}+/// Normalize a path chosen in the OS app picker into an open-with candidate+/// (id, label). Linux `.desktop` entries become `desktop:{id}` with the+/// label taken from their `Name=`; everything else (mac .app bundles,+/// executables) uses the path as id and the file stem as label.+pub fn app_candidate_for_picked_path(path: &Path) -> (String, String) {+ #[cfg(all(not(windows), not(target_os = "macos")))]+ if path+ .extension()+ .is_some_and(|extension| extension == "desktop")+ {+ let id = path+ .file_stem()+ .map(|stem| stem.to_string_lossy().into_owned())+ .unwrap_or_default();+ let label = desktop_name(path).unwrap_or_else(|| id.clone());+ return (format!("desktop:{id}"), label);+ }++ let label = path+ .file_stem()+ .map(|stem| stem.to_string_lossy().into_owned())+ .unwrap_or_else(|| path.to_string_lossy().into_owned());+ (path.to_string_lossy().into_owned(), label)+}+#[cfg(target_os = "macos")]fn platform_open_with_candidates(path: &Path) -> Vec<OpenWithCandidate> {macos_open_with_candidates(path)@@ -31,8 +56,148 @@ fn platform_open_with_candidates(path: &Path) -> Vec<OpenWithCandidate> {}#[cfg(windows)]-fn platform_open_with_candidates(_path: &Path) -> Vec<OpenWithCandidate> {- Vec::new()+fn platform_open_with_candidates(path: &Path) -> Vec<OpenWithCandidate> {+ windows_open_with_candidates(path)+}++/// Discover candidate applications for a file on Windows: the association+/// default (AssocQueryString) plus Explorer's per-user OpenWithList MRU and+/// the OpenWithProgids registered for the extension.+#[cfg(windows)]+fn windows_open_with_candidates(path: &Path) -> Vec<OpenWithCandidate> {+ use std::collections::HashSet;+ use winreg::enums::{HKEY_CLASSES_ROOT, HKEY_CURRENT_USER};+ use winreg::RegKey;++ let Some(ext) = path.extension() else {+ return Vec::new();+ };+ let ext = format!(".{}", ext.to_string_lossy().to_lowercase());++ let mut out: Vec<OpenWithCandidate> = Vec::new();+ let mut seen: HashSet<String> = HashSet::new();++ fn push_candidate(+ out: &mut Vec<OpenWithCandidate>,+ seen: &mut HashSet<String>,+ id: String,+ is_default: bool,+ ) {+ let key = id.to_lowercase();+ if id.is_empty() || seen.contains(&key) {+ return;+ }+ seen.insert(key);+ let label = Path::new(&id)+ .file_stem()+ .map(|stem| stem.to_string_lossy().into_owned())+ .unwrap_or_else(|| id.clone());+ out.push(OpenWithCandidate {+ id,+ label,+ icon_path: None,+ is_default,+ });+ }++ let hkcu = RegKey::predef(HKEY_CURRENT_USER);+ let hkcr = RegKey::predef(HKEY_CLASSES_ROOT);+ let file_exts = format!(+ r"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{ext}"+ );++ if let Some(exe) = windows_default_executable(&hkcu, &hkcr, &file_exts, &ext) {+ push_candidate(&mut out, &mut seen, exe, true);+ }++ // Explorer's MRU of "Open with" choices; values are exe names that+ // ShellExecuteW resolves via PATH / App Paths.+ if let Ok(key) = hkcu.open_subkey(format!(r"{file_exts}\OpenWithList")) {+ for (name, value) in key.enum_values().flatten() {+ if name.eq_ignore_ascii_case("MRUList") {+ continue;+ }+ if let Ok(exe) = <String as winreg::types::FromRegValue>::from_reg_value(&value) {+ if exe.to_lowercase().ends_with(".exe") {+ push_candidate(&mut out, &mut seen, exe, false);+ }+ }+ }+ }++ // ProgIds registered for the extension (per-user and machine-wide),+ // plus the extension's default progid.+ let mut progids: Vec<String> = Vec::new();+ if let Ok(key) = hkcu.open_subkey(format!(r"{file_exts}\OpenWithProgids")) {+ progids.extend(key.enum_values().flatten().map(|(name, _)| name));+ }+ if let Ok(key) = hkcr.open_subkey(format!(r"{ext}\OpenWithProgids")) {+ progids.extend(key.enum_values().flatten().map(|(name, _)| name));+ }+ if let Ok(key) = hkcr.open_subkey(&ext) {+ if let Ok(progid) = key.get_value::<String, _>("") {+ progids.push(progid);+ }+ }+ for progid in progids {+ if let Some(exe) = windows_progid_executable(&hkcr, &progid) {+ push_candidate(&mut out, &mut seen, exe, false);+ }+ }++ out.truncate(20);+ out+}++/// Resolve a progid to the executable of its `shell\open\command`.+#[cfg(windows)]+fn windows_progid_executable(hkcr: &winreg::RegKey, progid: &str) -> Option<String> {+ if progid.is_empty() {+ return None;+ }+ let key = hkcr+ .open_subkey(format!(r"{progid}\shell\open\command"))+ .ok()?;+ let command: String = key.get_value("").ok()?;+ windows_command_line_executable(&command)+}++/// Extract the executable path from a registry `shell\open\command` value.+#[cfg(windows)]+fn windows_command_line_executable(command: &str) -> Option<String> {+ let command = command.trim();+ let exe = if let Some(rest) = command.strip_prefix('"') {+ rest.split('"').next()?+ } else {+ command.split_whitespace().next()?+ };+ let exe = exe.trim();+ if exe.is_empty() || !exe.to_lowercase().ends_with(".exe") {+ return None;+ }+ Some(exe.to_string())+}++/// The user's default handler for an extension: Explorer's UserChoice progid+/// first (what modern Windows actually honours), falling back to the+/// extension's classic default progid under HKCR.+#[cfg(windows)]+fn windows_default_executable(+ hkcu: &winreg::RegKey,+ hkcr: &winreg::RegKey,+ file_exts: &str,+ ext: &str,+) -> Option<String> {+ if let Ok(key) = hkcu.open_subkey(format!(r"{file_exts}\UserChoice")) {+ if let Ok(progid) = key.get_value::<String, _>("ProgId") {+ if let Some(exe) = windows_progid_executable(hkcr, &progid) {+ return Some(exe);+ }+ }+ }+ let key = hkcr.open_subkey(ext).ok()?;+ let progid: String = key.get_value("").ok()?;+ windows_progid_executable(hkcr, &progid)}#[cfg(not(windows))]diff --git a/wezterm-ssh/src/sessioninner.rs b/wezterm-ssh/src/sessioninner.rsindex f84b8518..b4c520a5 100644--- a/wezterm-ssh/src/sessioninner.rs+++ b/wezterm-ssh/src/sessioninner.rs@@ -473,8 +473,9 @@ impl SessionInner {let max_sleep_delay = Duration::from_secs(2);let immediate_wakeup = Duration::from_millis(10);let busy_loop_throttle = Duration::from_millis(50);- let busy_loop_disconnect_after = Duration::from_secs(30);- let mut busy_loop_started = None;+ let busy_loop_warn_every = Duration::from_secs(30);+ let mut busy_loop_started: Option<Instant> = None;+ let mut busy_loop_last_warn: Option<Instant> = None;loop {self.do_keepalive(sess)?;@@ -588,11 +589,26 @@ impl SessionInner {if made_progress || !saw_revents || poll_elapsed >= immediate_wakeup {busy_loop_started = None;+ busy_loop_last_warn = None;} else {+ // Repeated immediate wakeups with no IO progress. The+ // throttle below already caps this at ~20 iterations/sec,+ // which is enough to keep CPU usage negligible; don't kill+ // the session over it (protocol-only traffic such as+ // keepalives can legitimately look like this), just make+ // the condition visible in the logs.let started = *busy_loop_started.get_or_insert_with(Instant::now);- if started.elapsed() >= busy_loop_disconnect_after {- anyhow::bail!(- "SSH session made no IO progress after repeated immediate wakeups; closing it to avoid a busy loop"+ let should_warn = match busy_loop_last_warn {+ None => started.elapsed() >= busy_loop_warn_every,+ Some(last) => last.elapsed() >= busy_loop_warn_every,+ };+ if should_warn {+ busy_loop_last_warn = Some(Instant::now());+ log::warn!(+ "SSH session has made no IO progress despite repeated \+ immediate poll wakeups for {:.0?}; throttling the \+ session loop to avoid a busy loop",+ started.elapsed());}std::thread::sleep(busy_loop_throttle);diff --git a/window/Cargo.toml b/window/Cargo.tomlindex 773ddc78..d33a2a0e 100644--- a/window/Cargo.toml+++ b/window/Cargo.toml@@ -61,6 +61,7 @@ winapi = { workspace=true, features = ["shellscalingapi","shobjidl","shobjidl_core",+ "shtypes","synchapi","sysinfoapi","winerror",diff --git a/window/src/lib.rs b/window/src/lib.rsindex 871ee3ad..cdc574f2 100644--- a/window/src/lib.rs+++ b/window/src/lib.rs@@ -349,6 +349,12 @@ pub trait WindowOps {callback(None);}+ /// Show a native picker for choosing an application (macOS: .app bundle,+ /// Windows: .exe, Linux: .desktop entry or executable).+ fn pick_app_async(&self, callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>) {+ callback(None);+ }+/// Invalidate the window so that the entire client area will/// be repainted shortlyfn invalidate(&self);diff --git a/window/src/os/macos/connection.rs b/window/src/os/macos/connection.rsindex dd51ae50..32c3a462 100644--- a/window/src/os/macos/connection.rs+++ b/window/src/os/macos/connection.rs@@ -39,6 +39,22 @@ impl Connection {let delegate = create_app_delegate();let () = msg_send![ns_app, setDelegate: delegate];+ // Opt out of App Nap: it coalesces our timers when macOS decides+ // the app looks idle (heavy output but no input), which stalls+ // the paint throttle / animation wakeups until the next user+ // event. NSActivityUserInitiatedAllowingIdleSystemSleep keeps us+ // scheduled normally without blocking system sleep. The activity+ // token must stay alive for the process lifetime, so retain it.+ const NS_ACTIVITY_USER_INITIATED_ALLOWING_IDLE_SYSTEM_SLEEP: u64 = 0x00EFFFFF;+ let process_info: id = msg_send![class!(NSProcessInfo), processInfo];+ let reason = nsstring("ThinkTerm renders terminal output continuously");+ let activity: id = msg_send![+ process_info,+ beginActivityWithOptions: NS_ACTIVITY_USER_INITIATED_ALLOWING_IDLE_SYSTEM_SLEEP+ reason: *reason+ ];+ let _: id = msg_send![activity, retain];+let conn = Self {ns_app,windows: RefCell::new(HashMap::new()),diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rsindex a34bc766..890c3305 100644--- a/window/src/os/macos/window.rs+++ b/window/src/os/macos/window.rs@@ -48,7 +48,7 @@ use raw_window_handle::{HasWindowHandle, RawDisplayHandle, RawWindowHandle, WindowHandle,};use std::any::Any;-use std::cell::RefCell;+use std::cell::{Cell, RefCell};use std::ffi::{c_void, CStr};use std::path::{Path, PathBuf};use std::ptr::NonNull;@@ -603,8 +603,6 @@ impl Window {window: None,titlebar_sidebar_button_visible: false,screen_changed: false,- paint_throttled: false,- invalidated: true,gl_context_pair: None,text_cursor_position: Rect::new(Point::new(0, 0), Size::new(0, 0)),tracking_rect_tag: 0,@@ -954,6 +952,58 @@ impl WindowOps for Window {}}+ fn pick_app_async(&self, callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>) {+ unsafe {+ let _pool = NSAutoreleasePool::new(nil);+ let panel: id = msg_send![class!(NSOpenPanel), openPanel];+ let panel = StrongPtr::retain(panel);+ let () = msg_send![*panel, setCanChooseFiles: YES];+ let () = msg_send![*panel, setCanChooseDirectories: NO];+ let () = msg_send![*panel, setAllowsMultipleSelection: NO];+ let () = msg_send![*panel, setResolvesAliases: YES];+ let app_type = nsstring("app");+ let types: id = msg_send![class!(NSArray), arrayWithObject: *app_type];+ let () = msg_send![*panel, setAllowedFileTypes: types];+ let applications_dir = nsstring("/Applications");+ let dir_url: id =+ msg_send![class!(NSURL), fileURLWithPath: *applications_dir isDirectory: YES];+ let () = msg_send![*panel, setDirectoryURL: dir_url];+ let title = nsstring("Choose Application");+ let prompt = nsstring("Choose");+ let () = msg_send![*panel, setTitle: *title];+ let () = msg_send![*panel, setPrompt: *prompt];++ const NS_MODAL_RESPONSE_OK: NSInteger = 1;+ let callback = Arc::new(Mutex::new(Some(callback)));+ let callback_for_block = callback.clone();+ let panel_for_block = panel.clone();+ let block = RcBlock::new(move |result: NSInteger| {+ let selected_path = if result != NS_MODAL_RESPONSE_OK {+ None+ } else {+ let url: id = msg_send![*panel_for_block, URL];+ if url == nil {+ None+ } else {+ let path: id = msg_send![url, path];+ if path == nil {+ None+ } else {+ Some(PathBuf::from(nsstring_to_str(path)))+ }+ }+ };++ if let Ok(mut callback) = callback_for_block.lock() {+ if let Some(callback) = callback.take() {+ callback(selected_path);+ }+ }+ });+ let () = msg_send![*panel, beginWithCompletionHandler: &*block];+ }+ }+fn invalidate(&self) {Connection::with_window_inner(self.id, |inner| {inner.invalidate();@@ -1539,7 +1589,7 @@ impl WindowInner {unsafe {let () = msg_send![*self.view, setNeedsDisplay: YES];if let Some(window_view) = WindowView::get_this(&**self.view) {- window_view.inner.borrow_mut().invalidated = true;+ window_view.invalidated.set(true);}}}@@ -1970,9 +2020,7 @@ struct Inner {window: Option<WeakPtr>,titlebar_sidebar_button_visible: bool,screen_changed: bool,- paint_throttled: bool,window_id: usize,- invalidated: bool,gl_context_pair: Option<GlContextPair>,text_cursor_position: Rect,tracking_rect_tag: NSInteger,@@ -2300,6 +2348,12 @@ fn code_to_cursor(code: i64) -> Option<MouseCursor> {struct WindowView {inner: Rc<RefCell<Inner>>,+ // Repaint scheduling flags live outside the RefCell: they are touched+ // from paths that can run while `inner` is borrowed (reentrant drawRect,+ // the frame throttle timer, invalidate()), and losing an update here is+ // what makes the window stop refreshing until the next user interaction.+ paint_throttled: Cell<bool>,+ invalidated: Cell<bool>,}pub fn superclass(this: &Object) -> &'static Class {@@ -2749,6 +2803,32 @@ impl WindowView {}}+ extern "C" fn did_change_occlusion_state(view: &mut Object, _sel: Sel, _id: id) {+ // AppKit suppresses drawRect for occluded windows (covered, or on+ // another Space). If a frame was requested while we were hidden, the+ // needsDisplay it set may have been consumed without a draw; re-arm+ // when we become visible again so the window doesn't stay stale+ // until the next input event.+ const NS_WINDOW_OCCLUSION_STATE_VISIBLE: NSUInteger = 1 << 1;+ let view_ptr: id = view as *mut Object;+ if let Some(this) = Self::get_this(view) {+ let visible = unsafe {+ let window: id = msg_send![view_ptr, window];+ if window.is_null() {+ false+ } else {+ let state: NSUInteger = msg_send![window, occlusionState];+ (state & NS_WINDOW_OCCLUSION_STATE_VISIBLE) != 0+ }+ };+ if visible && this.invalidated.get() {+ unsafe {+ let () = msg_send![view_ptr, setNeedsDisplay: YES];+ }+ }+ }+ }+// Switch the coordinate system to have 0,0 in the top leftextern "C" fn is_flipped(_this: &Object, _sel: Sel) -> BOOL {YES@@ -3656,7 +3736,20 @@ impl WindowView {extern "C" fn draw_rect(view: &mut Object, sel: Sel, _dirty_rect: NSRect) {if let Some(this) = Self::get_this(view) {let Ok(mut inner) = this.inner.try_borrow_mut() else {- log::trace!("skipping draw while window is busy");+ // We're being asked to draw reentrantly while some other+ // handler holds the window state. AppKit has already cleared+ // needsDisplay for this pass, so if we simply return here the+ // frame is lost and the window stays stale until the next+ // interaction sets needsDisplay again. Re-arm it for the next+ // runloop turn instead.+ log::trace!("skipping draw while window is busy; re-arming");+ this.invalidated.set(true);+ let view_ptr: id = view as *mut Object;+ unsafe {+ let () = msg_send![view_ptr, performSelector: sel!(thinktermRearmNeedsDisplay)+ withObject: nil+ afterDelay: 0.0];+ }return;};@@ -3672,8 +3765,8 @@ impl WindowView {return;}- if inner.paint_throttled {- inner.invalidated = true;+ if this.paint_throttled.get() {+ this.invalidated.set(true);} else {let now = Instant::now();if let Some(last) = inner.last_repaint_time.replace(now) {@@ -3685,8 +3778,8 @@ impl WindowView {}}inner.events.dispatch(WindowEvent::NeedRepaint);- inner.invalidated = false;- inner.paint_throttled = true;+ this.invalidated.set(false);+ this.paint_throttled.set(true);let window_id = inner.window_id;let max_fps = target_frame_fps(inner.config.max_fps);@@ -3697,15 +3790,11 @@ impl WindowView {async_io::Timer::after(std::time::Duration::from_secs_f64(1.0 / max_fps)).await;Connection::with_window_inner(window_id, move |inner| {if let Some(window_view) = WindowView::get_this(unsafe { &**inner.view }) {- if let Ok(mut state) = window_view.inner.try_borrow_mut() {- state.paint_throttled = false;- if state.invalidated {- unsafe {- let () = msg_send![*inner.view, setNeedsDisplay: YES];- }+ window_view.paint_throttled.set(false);+ if window_view.invalidated.get() {+ unsafe {+ let () = msg_send![*inner.view, setNeedsDisplay: YES];}- } else {- log::trace!("skipping paint throttle update while window is busy");}}Ok(())@@ -3716,6 +3805,12 @@ impl WindowView {}}+ extern "C" fn rearm_needs_display(this: &mut Object, _sel: Sel) {+ unsafe {+ let () = msg_send![this, setNeedsDisplay: YES];+ }+ }+extern "C" fn dragging_entered(this: &mut Object, _: Sel, sender: id) -> BOOL {if let Some(this) = Self::get_this(this) {let mut inner = this.inner.borrow_mut();@@ -3788,6 +3883,8 @@ impl WindowView {let view = Box::into_raw(Box::new(Self {inner: Rc::clone(&inner),+ paint_throttled: Cell::new(false),+ invalidated: Cell::new(true),}));unsafe {@@ -3829,6 +3926,10 @@ impl WindowView {sel!(thinktermToggleWorkspaceSidebar:),Self::thinkterm_toggle_workspace_sidebar as extern "C" fn(&mut Object, Sel, id),);+ cls.add_method(+ sel!(thinktermRearmNeedsDisplay),+ Self::rearm_needs_display as extern "C" fn(&mut Object, Sel),+ );cls.add_method(sel!(windowWillClose:),Self::window_will_close as extern "C" fn(&mut Object, Sel, id),@@ -3915,6 +4016,10 @@ impl WindowView {sel!(windowDidResignKey:),Self::did_resign_key as extern "C" fn(&mut Object, Sel, id),);+ cls.add_method(+ sel!(windowDidChangeOcclusionState:),+ Self::did_change_occlusion_state as extern "C" fn(&mut Object, Sel, id),+ );cls.add_method(sel!(mouseMoved:),diff --git a/window/src/os/windows/window.rs b/window/src/os/windows/window.rsindex 93a97ecd..02eb62b2 100644--- a/window/src/os/windows/window.rs+++ b/window/src/os/windows/window.rs@@ -46,9 +46,11 @@ use winapi::um::objbase::{COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE};use winapi::um::shellapi::{DragAcceptFiles, DragFinish, DragQueryFileW, HDROP};use winapi::um::shellscalingapi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI};use winapi::um::shobjidl::{- IFileOpenDialog, FOS_FORCEFILESYSTEM, FOS_NOCHANGEDIR, FOS_PATHMUSTEXIST, FOS_PICKFOLDERS,+ IFileOpenDialog, FOS_FILEMUSTEXIST, FOS_FORCEFILESYSTEM, FOS_NOCHANGEDIR, FOS_PATHMUSTEXIST,+ FOS_PICKFOLDERS,};use winapi::um::shobjidl_core::{CLSID_FileOpenDialog, IShellItem, SIGDN_FILESYSPATH};+use winapi::um::shtypes::COMDLG_FILTERSPEC;use winapi::um::sysinfoapi::{GetTickCount, GetVersionExW};use winapi::um::uxtheme::{CloseThemeData, GetThemeFont, GetThemeSysFont, OpenThemeData, SetWindowTheme,@@ -260,6 +262,101 @@ unsafe fn pick_folder_dialog(hwnd: HWND) -> anyhow::Result<Option<PathBuf>> {result}+unsafe fn pick_app_dialog(hwnd: HWND) -> anyhow::Result<Option<PathBuf>> {+ let coinit = CoInitializeEx(+ null_mut(),+ COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE,+ );+ let should_uninitialize = coinit == S_OK || coinit == S_FALSE;+ if FAILED(coinit) && coinit != RPC_E_CHANGED_MODE {+ hresult_to_result(coinit, "CoInitializeEx")?;+ }++ let result = (|| {+ let mut dialog: *mut IFileOpenDialog = null_mut();+ hresult_to_result(+ CoCreateInstance(+ &CLSID_FileOpenDialog,+ null_mut(),+ CLSCTX_INPROC_SERVER,+ &IFileOpenDialog::uuidof(),+ &mut dialog as *mut _ as *mut _,+ ),+ "CoCreateInstance(FileOpenDialog)",+ )?;++ let title = wide_null("Choose Application");+ let choose = wide_null("Choose");+ let filter_name = wide_null("Applications (*.exe)");+ let filter_spec = wide_null("*.exe");+ let filters = [COMDLG_FILTERSPEC {+ pszName: filter_name.as_ptr(),+ pszSpec: filter_spec.as_ptr(),+ }];+ let mut selected_path = None;+ let mut result_item: *mut IShellItem = null_mut();+ let mut raw_path: LPWSTR = null_mut();++ let dialog_result = (|| {+ let mut options = std::mem::zeroed();+ hresult_to_result(+ (*dialog).GetOptions(&mut options),+ "IFileDialog::GetOptions",+ )?;+ let options = std::mem::transmute(+ options as u32+ | FOS_FORCEFILESYSTEM as u32+ | FOS_PATHMUSTEXIST as u32+ | FOS_FILEMUSTEXIST as u32+ | FOS_NOCHANGEDIR as u32,+ );+ hresult_to_result((*dialog).SetOptions(options), "IFileDialog::SetOptions")?;+ hresult_to_result(+ (*dialog).SetFileTypes(filters.len() as u32, filters.as_ptr()),+ "IFileDialog::SetFileTypes",+ )?;+ hresult_to_result((*dialog).SetTitle(title.as_ptr()), "IFileDialog::SetTitle")?;+ hresult_to_result(+ (*dialog).SetOkButtonLabel(choose.as_ptr()),+ "IFileDialog::SetOkButtonLabel",+ )?;++ let show_result = (*dialog).Show(hwnd);+ if show_result == HRESULT_FROM_WIN32(ERROR_CANCELLED) {+ return Ok(());+ }+ hresult_to_result(show_result, "IFileDialog::Show")?;++ hresult_to_result(+ (*dialog).GetResult(&mut result_item),+ "IFileDialog::GetResult",+ )?;+ hresult_to_result(+ (*result_item).GetDisplayName(SIGDN_FILESYSPATH, &mut raw_path),+ "IShellItem::GetDisplayName",+ )?;+ selected_path = pathbuf_from_shell_string(raw_path);+ Ok(())+ })();++ if !raw_path.is_null() {+ CoTaskMemFree(raw_path as *mut _);+ }+ if !result_item.is_null() {+ (*result_item).Release();+ }+ (*dialog).Release();++ dialog_result.map(|_| selected_path)+ })();++ if should_uninitialize {+ CoUninitialize();+ }++ result+}+fn rect_height(r: &RECT) -> i32 {r.bottom - r.top}@@ -1001,6 +1098,23 @@ impl WindowOps for Window {.detach();}+ fn pick_app_async(&self, callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>) {+ let hwnd = self.0 .0;+ promise::spawn::spawn(async move {+ let path = unsafe {+ match pick_app_dialog(hwnd) {+ Ok(path) => path,+ Err(err) => {+ log::warn!("failed to show app picker: {err:#}");+ None+ }+ }+ };+ callback(path);+ })+ .detach();+ }+fn invalidate(&self) {let hwnd = self.0 .0;log::trace!("WindowOps::invalidate calling InvalidateRect");diff --git a/window/src/os/x_and_wayland.rs b/window/src/os/x_and_wayland.rsindex e7a1fed8..dea1188e 100644--- a/window/src/os/x_and_wayland.rs+++ b/window/src/os/x_and_wayland.rs@@ -311,6 +311,10 @@ impl WindowOps for Window {crate::os::xdg_desktop_portal::pick_folder_async(callback);}+ fn pick_app_async(&self, callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>) {+ crate::os::xdg_desktop_portal::pick_app_async(callback);+ }+fn invalidate(&self) {match self {Self::X11(x) => x.invalidate(),diff --git a/window/src/os/xdg_desktop_portal.rs b/window/src/os/xdg_desktop_portal.rsindex b2a4c9f5..50ee02ac 100644--- a/window/src/os/xdg_desktop_portal.rs+++ b/window/src/os/xdg_desktop_portal.rs@@ -246,6 +246,69 @@ pub fn pick_folder_async(callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>) {.detach();}+/// File picker used to choose an application (a .desktop entry or an+/// executable); the caller normalizes the selection.+pub async fn pick_app() -> anyhow::Result<Option<PathBuf>> {+ let connection = zbus::ConnectionBuilder::session()?.build().await?;+ let proxy = PortalFileChooserProxy::new(&connection)+ .await+ .context("make file chooser proxy")?;++ let mut options = HashMap::new();+ options.insert("modal", Value::from(true));++ let handle = proxy+ .OpenFile("", "Choose Application", options)+ .or(async {+ async_io::Timer::after(std::time::Duration::from_secs(1)).await;+ Err(std::io::Error::new(+ std::io::ErrorKind::TimedOut,+ "Timed out opening xdg-desktop-portal app picker",+ )+ .into())+ })+ .await+ .context("Opening xdg-desktop-portal app picker")?;++ let request = PortalRequestProxy::builder(&connection)+ .path(handle)?+ .build()+ .await+ .context("make portal request proxy")?;+ let mut stream = request+ .receive_Response()+ .await+ .context("subscribe to portal request response")?;+ let signal = stream+ .next()+ .or(async {+ async_io::Timer::after(std::time::Duration::from_secs(60)).await;+ None+ })+ .await+ .ok_or_else(|| anyhow::anyhow!("Timed out waiting for app picker response"))?;+ let args = signal.args().context("decode app picker response")?;+ if args.response != 0 {+ return Ok(None);+ }++ first_file_uri_to_path(&args.results)+}++pub fn pick_app_async(callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>) {+ promise::spawn::spawn(async move {+ let path = match pick_app().await {+ Ok(path) => path,+ Err(err) => {+ log::warn!("failed to show xdg-desktop-portal app picker: {err:#}");+ None+ }+ };+ callback(path);+ })+ .detach();+}+pub async fn run_signal_loop(stream: &mut SettingChangedStream<'_>) -> Result<(), anyhow::Error> {// query appearance again as it might have changed without us knowingif let Ok(value) =diff --git a/window/src/spawn.rs b/window/src/spawn.rsindex 512e5807..6132851e 100644--- a/window/src/spawn.rs+++ b/window/src/spawn.rs@@ -6,7 +6,7 @@ use promise::spawn::{Runnable, SpawnFunc};use std::collections::VecDeque;use std::panic::{catch_unwind, AssertUnwindSafe};use std::sync::{Arc, Mutex};-use std::time::Instant;+use std::time::{Duration, Instant};#[cfg(all(unix, not(target_os = "macos")))]use {filedescriptor::{FileDescriptor, Pipe},@@ -33,8 +33,20 @@ pub(crate) struct SpawnQueue {write: Mutex<FileDescriptor>,#[cfg(all(unix, not(target_os = "macos")))]read: Mutex<FileDescriptor>,++ #[cfg(target_os = "macos")]+ runloop_source: RunLoopSourceHandle,}+/// A CFRunLoopSourceRef is just a CFTypeRef; signalling it from any thread is+/// documented as safe, and we never mutate through it after creation.+#[cfg(target_os = "macos")]+struct RunLoopSourceHandle(CFRunLoopSourceRef);+#[cfg(target_os = "macos")]+unsafe impl Send for RunLoopSourceHandle {}+#[cfg(target_os = "macos")]+unsafe impl Sync for RunLoopSourceHandle {}+fn schedule_with_pri(runnable: Runnable, high_pri: bool) {SPAWN_QUEUE.spawn_impl(Box::new(move || {@@ -207,6 +219,8 @@ impl SpawnQueue {let spawned_funcs = Mutex::new(VecDeque::new());let spawned_funcs_low_pri = Mutex::new(VecDeque::new());+ // Safety-net drain on every runloop activity, in case the source+ // below is somehow not serviced.let observer = unsafe {CFRunLoopObserverCreate(std::ptr::null(),@@ -221,9 +235,32 @@ impl SpawnQueue {CFRunLoopAddObserver(CFRunLoopGetMain(), observer, kCFRunLoopCommonModes);}+ // The primary wakeup is a version-0 runloop source: unlike a bare+ // CFRunLoopWakeUp (which can be swallowed if it lands while the loop+ // is between activities), a signalled source stays signalled until+ // the loop services it, so queued work can never be stranded until+ // the next user-input event.+ let mut context = CFRunLoopSourceContext {+ version: 0,+ info: std::ptr::null_mut(),+ retain: None,+ release: None,+ copyDescription: None,+ equal: None,+ hash: None,+ schedule: None,+ cancel: None,+ perform: SpawnQueue::perform,+ };+ let source = unsafe { CFRunLoopSourceCreate(std::ptr::null(), 0, &mut context) };+ unsafe {+ CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopCommonModes);+ }+Ok(Self {spawned_funcs,spawned_funcs_low_pri,+ runloop_source: RunLoopSourceHandle(source),})}@@ -233,24 +270,41 @@ impl SpawnQueue {_: *mut std::ffi::c_void,) {if SPAWN_QUEUE.run() {- Self::queue_wakeup();+ SPAWN_QUEUE.signal_and_wake();+ }+ }++ extern "C" fn perform(_info: *const std::ffi::c_void) {+ if SPAWN_QUEUE.run() {+ SPAWN_QUEUE.signal_and_wake();}}- fn queue_wakeup() {+ fn signal_and_wake(&self) {unsafe {+ CFRunLoopSourceSignal(self.runloop_source.0);CFRunLoopWakeUp(CFRunLoopGetMain());}}fn spawn_impl(&self, f: SpawnFunc, high_pri: bool) {self.queue_func(f, high_pri);- Self::queue_wakeup();+ self.signal_and_wake();}fn run_impl(&self) -> bool {- if let Some(func) = self.pop_func() {+ // Drain with a small time budget rather than one task per runloop+ // observer callback: under heavy load the one-at-a-time policy needs+ // a full wakeup round-trip per task, and if any wakeup is coalesced+ // the whole queue (paints, animations, output notifications) stalls+ // until the next user input event. Keep the budget small so native+ // event handling still interleaves.+ let deadline = Instant::now() + Duration::from_millis(2);+ while let Some(func) = self.pop_func() {Self::run_func(func);+ if Instant::now() >= deadline {+ break;+ }}self.has_any_queued()}