diff --git a/Cargo.lock b/Cargo.lock index 37566884278..9bd8b4cc56f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -329,9 +329,9 @@ dependencies = [ [[package]] name = "agent-client-protocol" -version = "5.0.0" +version = "5.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80ce60ce096020c2d0aa10445bc27b8856109e288abaf564ab517031ae819d69" +checksum = "c60cfd8cddbb23d9e30f51dca5316b4cea769ba55900db1fa8951dca4f28d02d" dependencies = [ "agent-client-protocol-derive", "agent-client-protocol-schema", @@ -348,9 +348,9 @@ dependencies = [ [[package]] name = "agent-client-protocol-derive" -version = "5.0.0" +version = "5.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a12951a4e9a163a9384dec4e5681bd774c0fdb3871c5ed1deb7b44bc630df17a" +checksum = "b296716e42d77d38aef7f645cbe0765287b0e0a84722cb9f8ac39e6cdcecdb2a" dependencies = [ "quote", "syn 3.0.3", @@ -358,9 +358,9 @@ dependencies = [ [[package]] name = "agent-client-protocol-schema" -version = "1.15.1" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b2316d2cd561917bc2c16e3c64771c77e24363b56d40b58fdad091d02059992" +checksum = "e20d2c4af6eb08f6a4f562520bdd939a4af803255fec461dd523638c22f5b265" dependencies = [ "anyhow", "derive_more", @@ -12201,6 +12201,7 @@ dependencies = [ "futures 0.3.34", "fuzzy", "gpui", + "menu", "picker", "project", "serde", diff --git a/Cargo.toml b/Cargo.toml index 1f4373ec860..2c21684341f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -535,7 +535,7 @@ accesskit = { version = "0.24.0", features = ["enumn"] } accesskit_macos = "0.26.0" accesskit_unix = "0.22" accesskit_windows = "0.34" -agent-client-protocol = { version = "=5.0.0", features = ["schemars", "unstable", "unstable_protocol_v2"] } +agent-client-protocol = { version = "=5.1.0", features = ["schemars", "unstable", "unstable_protocol_v2"] } aho-corasick = "1.1" alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "4c129667ce56611becdc82de6e28218c80e2e88f" } any_vec = "0.14" diff --git a/assets/settings/default.json b/assets/settings/default.json index 38b266e8f6a..eb13c39315f 100644 --- a/assets/settings/default.json +++ b/assets/settings/default.json @@ -1895,6 +1895,12 @@ // Show "relative" or "absolute" dates in the stash picker. "date_style": "relative", }, + "commit_view": { + // Whether newly opened commit views show the full commit description. + "expand_description": false, + // Whether newly opened commit views expand every changed file. + "expand_files": true, + }, "file_diff": { // Whether newly opened file diffs show the full file instead of changes only. "show_full_file": true, diff --git a/crates/agent_ui/src/config_options.rs b/crates/agent_ui/src/config_options.rs index 6cda24d1a4b..242e9fa10ba 100644 --- a/crates/agent_ui/src/config_options.rs +++ b/crates/agent_ui/src/config_options.rs @@ -285,7 +285,9 @@ impl Render for ConfigOptionsView { .min_w_0() .flex_wrap() .gap_1() - .children(self.selectors.iter().cloned()) + // Options read right to left in the order the agent sent them, so the + // first one sits next to the send button. + .children(self.selectors.iter().rev().cloned()) .into_any_element() } } diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs index 5e265955a6d..e4e42dd9606 100644 --- a/crates/agent_ui/src/conversation_view.rs +++ b/crates/agent_ui/src/conversation_view.rs @@ -874,17 +874,17 @@ impl ConversationView { .pending_tool_call(&session_id, cx) } - pub fn root_thread_has_pending_tool_call(&self, cx: &App) -> bool { + pub fn root_thread_is_waiting_for_input(&self, cx: &App) -> bool { let Some(root_thread) = self.root_thread_view() else { return false; }; let root_session_id = root_thread.read(cx).thread.read(cx).session_id().clone(); self.as_connected().is_some_and(|connected| { - connected - .conversation - .read(cx) + let conversation = connected.conversation.read(cx); + conversation .pending_tool_call(&root_session_id, cx) .is_some() + || !conversation.elicitation_requests.is_empty() }) } diff --git a/crates/anthropic/src/anthropic.rs b/crates/anthropic/src/anthropic.rs index 1b23a88228e..c6cc106a953 100644 --- a/crates/anthropic/src/anthropic.rs +++ b/crates/anthropic/src/anthropic.rs @@ -24,7 +24,11 @@ pub const FAST_MODE_BETA_HEADER: &str = "fast-mode-2026-02-01"; pub fn supports_fast_mode(model_id: &str) -> bool { matches!( model_id, - "claude-opus-5-5" | "claude-opus-5" | "claude-opus-4-8" + "claude-fable-5-2" + | "claude-mythos-5-2" + | "claude-opus-5-5" + | "claude-opus-5" + | "claude-opus-4-8" ) } @@ -50,14 +54,24 @@ pub const THINKING_BINDING_CONTROLS_BETA_HEADER: &str = "thinking-binding-contro pub fn binds_thinking_blocks_to_prefix(model_id: &str) -> bool { matches!( model_id, - "claude-opus-5-5" | "claude-fable-5-1" | "claude-sonnet-5-5" | "claude-haiku-5-5" + "claude-fable-5-2" + | "claude-mythos-5-2" + | "claude-opus-5-5" + | "claude-fable-5-1" + | "claude-sonnet-5-5" + | "claude-haiku-5-5" ) } pub fn supports_forced_tool_use(model_id: &str) -> bool { !matches!( model_id, - "claude-opus-5-5" | "claude-fable-5-1" | "claude-mythos-5-1" | "claude-sonnet-5-5" + "claude-fable-5-2" + | "claude-mythos-5-2" + | "claude-opus-5-5" + | "claude-fable-5-1" + | "claude-mythos-5-1" + | "claude-sonnet-5-5" ) } @@ -201,7 +215,9 @@ impl Model { // let supports_compaction = matches!( entry.id.as_str(), - "claude-opus-5-5" + "claude-fable-5-2" + | "claude-mythos-5-2" + | "claude-opus-5-5" | "claude-fable-5-1" | "claude-fable-5" | "claude-mythos-5-1" @@ -1887,6 +1903,26 @@ mod tests { assert!(!beta_headers.contains(THINKING_BINDING_CONTROLS_BETA_HEADER)); } + #[test] + fn from_listed_enables_fast_mode_compaction_and_binding_controls_for_5_2_models() { + for model_id in ["claude-fable-5-2", "claude-mythos-5-2"] { + let model = Model::from_listed(listed_entry(model_id, ModelCapabilities::default())); + + assert!(model.supports_speed, "{model_id} supports fast mode"); + assert!(model.supports_compaction, "{model_id} supports compaction"); + assert!( + !supports_forced_tool_use(model_id), + "{model_id} rejects forced tool use" + ); + let beta_headers = model + .beta_headers() + .expect("model should have beta headers"); + assert!(beta_headers.contains(FAST_MODE_BETA_HEADER)); + assert!(beta_headers.contains(COMPACTION_BETA_HEADER)); + assert!(beta_headers.contains(THINKING_BINDING_CONTROLS_BETA_HEADER)); + } + } + #[test] fn from_listed_collects_supported_effort_levels() { let entry = listed_entry( diff --git a/crates/anthropic/src/completion.rs b/crates/anthropic/src/completion.rs index b0cf8fde2df..e4eb0303a19 100644 --- a/crates/anthropic/src/completion.rs +++ b/crates/anthropic/src/completion.rs @@ -292,7 +292,11 @@ pub fn into_anthropic( ) -> Result { let requires_adaptive_thinking = matches!( model.as_str(), - "claude-opus-5-5" | "claude-sonnet-5-5" | "claude-haiku-5-5" + "claude-fable-5-2" + | "claude-mythos-5-2" + | "claude-opus-5-5" + | "claude-sonnet-5-5" + | "claude-haiku-5-5" ); let mode = if requires_adaptive_thinking { AnthropicModelMode::AdaptiveThinking @@ -1139,6 +1143,8 @@ mod tests { // its requests opt into dropping invalidated blocks instead. Models // without the prefix-binding check must not receive the beta field. for (model, expects_block_binding) in [ + ("claude-fable-5-2", true), + ("claude-mythos-5-2", true), ("claude-opus-5-5", true), ("claude-fable-5-1", true), ("claude-fable-5", false), @@ -1213,6 +1219,8 @@ mod tests { // outright, so those models must keep omitting the field. for (model, expects_explicit_opt_out) in [ ("claude-opus-5", true), + ("claude-fable-5-2", false), + ("claude-mythos-5-2", false), ("claude-opus-5-5", false), ("claude-opus-4-8", false), ("claude-fable-5", false), @@ -1267,7 +1275,10 @@ mod tests { "{model} should omit the thinking field entirely" ); } - if model == "claude-opus-5-5" { + if matches!( + model, + "claude-opus-5-5" | "claude-fable-5-2" | "claude-mythos-5-2" + ) { assert!( anthropic_request.temperature.is_none(), "{model} must omit temperature because adaptive thinking is always on" diff --git a/crates/editor/src/editor_settings.rs b/crates/editor/src/editor_settings.rs index a06564c2ce1..b18632968b4 100644 --- a/crates/editor/src/editor_settings.rs +++ b/crates/editor/src/editor_settings.rs @@ -71,6 +71,7 @@ pub struct EditorSettings { pub completion_menu_item_kind: CompletionMenuItemKind, pub diff_view_style: DiffViewStyle, pub minimum_split_diff_width: f32, + pub commit_view: CommitViewSettings, pub file_diff: FileDiffSettings, } @@ -79,6 +80,18 @@ pub struct CursorAnimationSettings { pub enabled: bool, } +#[derive(Clone, Copy, Debug)] +pub struct CommitViewSettings { + /// Whether newly opened commit views show the full commit description. + /// + /// Default: false + pub expand_description: bool, + /// Whether newly opened commit views expand every changed file. + /// + /// Default: true + pub expand_files: bool, +} + #[derive(Clone, Copy, Debug)] pub struct FileDiffSettings { /// Whether newly opened file diffs show the full file instead of changes only. @@ -224,6 +237,7 @@ impl Settings for EditorSettings { let search = editor.search.unwrap(); let drag_and_drop_selection = editor.drag_and_drop_selection.unwrap(); let sticky_scroll = editor.sticky_scroll.unwrap(); + let commit_view = content.git.as_ref().unwrap().commit_view.unwrap(); let file_diff = content.git.as_ref().unwrap().file_diff.unwrap(); Self { cursor_blink: editor.cursor_blink.unwrap(), @@ -340,6 +354,10 @@ impl Settings for EditorSettings { completion_menu_item_kind: editor.completion_menu_item_kind.unwrap(), diff_view_style: editor.diff_view_style.unwrap(), minimum_split_diff_width: editor.minimum_split_diff_width.unwrap(), + commit_view: CommitViewSettings { + expand_description: commit_view.expand_description.unwrap(), + expand_files: commit_view.expand_files.unwrap(), + }, file_diff: FileDiffSettings { show_full_file: file_diff.show_full_file.unwrap(), }, diff --git a/crates/editor/src/element.rs b/crates/editor/src/element.rs index 16d62a56f43..2c3370a81bc 100644 --- a/crates/editor/src/element.rs +++ b/crates/editor/src/element.rs @@ -10259,14 +10259,6 @@ impl ScrollbarLayoutInformation { } } -impl IntoElement for EditorElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - pub struct EditorLayout { position_map: Rc, hitbox: Hitbox, diff --git a/crates/editor/src/split_editor_view.rs b/crates/editor/src/split_editor_view.rs index 2dee964f356..bb6aab56fe8 100644 --- a/crates/editor/src/split_editor_view.rs +++ b/crates/editor/src/split_editor_view.rs @@ -261,14 +261,6 @@ struct SplitBufferHeadersPrepaintState { non_sticky_headers: Vec, } -impl IntoElement for SplitBufferHeadersElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl Element for SplitBufferHeadersElement { type RequestLayoutState = (); type PrepaintState = SplitBufferHeadersPrepaintState; diff --git a/crates/extensions_ui/src/extensions_ui.rs b/crates/extensions_ui/src/extensions_ui.rs index f52483e3ae3..6e826a2b9c4 100644 --- a/crates/extensions_ui/src/extensions_ui.rs +++ b/crates/extensions_ui/src/extensions_ui.rs @@ -36,7 +36,7 @@ use ui::{ use util::ResultExt; use vim_mode_setting::VimModeSetting; use workspace::{ - Workspace, + OpenPathPromptMode, Workspace, item::{Item, ItemEvent}, workspace_error::{ErrorAction, ErrorSeverity, WorkspaceError}, }; @@ -181,6 +181,7 @@ pub fn init(cx: &mut App) { workspace.project().clone(), workspace.app_state().fs.clone(), ), + OpenPathPromptMode::SelectPath, window, cx, ); @@ -189,7 +190,7 @@ pub fn init(cx: &mut App) { window .spawn(cx, async move |cx| { let extension_path = match prompt.await.map_err(anyhow::Error::from) { - Ok(Some(mut paths)) => paths.pop()?, + Ok(Some(mut result)) => result.paths.pop()?, Ok(None) => return None, Err(err) => { workspace_handle diff --git a/crates/file_finder/src/file_finder.rs b/crates/file_finder/src/file_finder.rs index b6f773f4332..16dd78c8405 100644 --- a/crates/file_finder/src/file_finder.rs +++ b/crates/file_finder/src/file_finder.rs @@ -6,6 +6,7 @@ mod multi_select_tests; use futures::future::join_all; pub use open_path_prompt::OpenPathDelegate; +use anyhow::Context as _; use channel::ChannelStore; use client::ChannelId; use collections::{HashMap, HashSet}; @@ -22,10 +23,11 @@ use language::{BufferSnapshot, Point}; use open_path_prompt::{OpenPathPrompt, file_finder_settings::FileFinderSettings}; use picker::{Picker, PickerDelegate}; use project::{ - PathMatchCandidateSet, Project, ProjectPath, WorktreeId, worktree_store::WorktreeStore, + PathMatchCandidateSet, Project, ProjectPath, Worktree, WorktreeId, WorktreeSettings, + worktree_store::WorktreeStore, }; -use settings::{ModalWidthContent, SeedQuerySetting, Settings, SettingsStore}; +use settings::{ModalWidthContent, SeedQuerySetting, Settings, SettingsLocation, SettingsStore}; use std::{ borrow::Cow, cmp, mem, @@ -45,8 +47,8 @@ use util::{ rel_path::RelPath, }; use workspace::{ - MAX_RECENT_SELECTIONS, ModalView, OpenChannelNotesById, OpenOptions, OpenVisible, - SplitDirection, Workspace, item::PreviewTabsSettings, notifications::NotifyResultExt, pane, + MAX_RECENT_SELECTIONS, ModalView, OpenChannelNotesById, SplitDirection, Workspace, + item::PreviewTabsSettings, notifications::NotifyResultExt, pane, }; use zed_actions::search::ToggleIncludeIgnored; @@ -324,22 +326,22 @@ impl FileFinder { if let Some(workspace) = delegate.workspace.upgrade() && let Some(m) = delegate.matches.get(delegate.selected_index()) { - let path = match m { - Match::History { path, .. } => { - let worktree_id = path.project.worktree_id; - ProjectPath { - worktree_id, - path: Arc::clone(&path.project.path), - } - } - Match::Search(m) => project_path_for_search_match(&delegate.project, &m.0, cx), - Match::CreateNew(p) => p.clone(), - Match::Channel { .. } => return, - }; - let open_task = workspace.update(cx, move |workspace, cx| { - workspace.split_path_preview(path, false, Some(split_direction), window, cx) - }); - open_task.detach_and_log_err(cx); + if matches!(m, Match::Channel { .. }) { + return; + } + let resolve_path = m.resolve_project_path(&delegate.project, cx); + let workspace = workspace.downgrade(); + cx.spawn_in(window, async move |_, cx| { + let (_worktree, path) = resolve_path.await?; + let Ok(open_task) = workspace.update_in(cx, |workspace, window, cx| { + workspace.split_path_preview(path, false, Some(split_direction), window, cx) + }) else { + return anyhow::Ok(()); + }; + open_task.await?; + Ok(()) + }) + .detach_and_log_err(cx); } }) } @@ -468,6 +470,7 @@ enum Match { panel_match: Option, }, Search(ProjectPanelOrdMatch), + Absolute(PathBuf), Channel { channel_id: ChannelId, channel_name: SharedString, @@ -481,20 +484,17 @@ impl Match { match self { Match::History { path, .. } => Some(&path.project.path), Match::Search(panel_match) => Some(&panel_match.0.path), - Match::Channel { .. } | Match::CreateNew(_) => None, + Match::Absolute(_) | Match::Channel { .. } | Match::CreateNew(_) => None, } } fn abs_path(&self, project: &Entity, cx: &App) -> Option { match self { Match::History { path, .. } => Some(path.absolute.clone()), - Match::Search(ProjectPanelOrdMatch(path_match)) => Some( - project - .read(cx) - .worktree_for_id(WorktreeId::from_usize(path_match.worktree_id), cx)? - .read(cx) - .absolutize(&path_match.path), - ), + Match::Absolute(path) => Some(path.clone()), + Match::Search(ProjectPanelOrdMatch(path_match)) => project + .read(cx) + .absolute_path(&project_path_for_search_match(project, path_match, cx), cx), Match::Channel { .. } | Match::CreateNew(_) => None, } } @@ -503,9 +503,46 @@ impl Match { match self { Match::History { panel_match, .. } => panel_match.as_ref(), Match::Search(panel_match) => Some(panel_match), - Match::Channel { .. } | Match::CreateNew(_) => None, + Match::Absolute(_) | Match::Channel { .. } | Match::CreateNew(_) => None, } } + + fn resolve_project_path( + &self, + project: &Entity, + cx: &mut App, + ) -> Task, ProjectPath)>> { + let path = match self { + Match::History { path, .. } => { + if project + .read(cx) + .worktree_for_id(path.project.worktree_id, cx) + .is_none() + { + return Workspace::project_path_for_path( + project.clone(), + &path.absolute, + false, + cx, + ); + } + path.project.clone() + } + Match::Search(path_match) => project_path_for_search_match(project, &path_match.0, cx), + Match::CreateNew(path) => path.clone(), + Match::Absolute(path) => { + return Workspace::project_path_for_path(project.clone(), path, false, cx); + } + Match::Channel { .. } => return Task::ready(Err(anyhow::anyhow!("not a file"))), + }; + Task::ready( + project + .read(cx) + .worktree_for_id(path.worktree_id, cx) + .map(|worktree| (worktree, path)) + .context("worktree no longer exists"), + ) + } } /// Wrapper with Eq comparing the worktree-qualified path of file matches @@ -515,7 +552,7 @@ struct SelectedMatch(pub Match); impl SelectedMatch { fn new(m: Match) -> Option { match m { - Match::History { .. } | Match::Search(_) => Some(Self(m)), + Match::History { .. } | Match::Search(_) | Match::Absolute(_) => Some(Self(m)), Match::Channel { .. } | Match::CreateNew(_) => None, } } @@ -532,6 +569,7 @@ impl Eq for SelectedMatch {} impl PartialEq for SelectedMatch { fn eq(&self, other: &Match) -> bool { match (&self.0, other) { + (Match::Absolute(left), Match::Absolute(right)) => left == right, (Match::History { path: a, .. }, Match::History { path: b, .. }) => { a.project == b.project } @@ -664,6 +702,13 @@ impl Matches { a: &Match, b: &Match, ) -> cmp::Ordering { + match (a, b) { + (Match::Absolute(left), Match::Absolute(right)) => return left.cmp(right), + (Match::Absolute(_), _) => return cmp::Ordering::Greater, + (_, Match::Absolute(_)) => return cmp::Ordering::Less, + _ => {} + } + // Handle CreateNew variant - always put it at the end match (a, b) { (Match::CreateNew(_), _) => return cmp::Ordering::Less, @@ -709,6 +754,7 @@ impl Matches { match m { Match::History { panel_match, .. } => panel_match.as_ref().map_or(0.0, |pm| pm.0.score), Match::Search(pm) => pm.0.score, + Match::Absolute(_) => 1.0, Match::Channel { string_match, .. } => string_match.score, Match::CreateNew(_) => 0.0, } @@ -1103,6 +1149,10 @@ impl FileFinderDelegate { let absolute = project.absolute_path(&path, cx)?; Some(FoundPath::new(path, absolute)) } + Match::Absolute(path) => { + let project_path = project.project_path_for_absolute_path(path, cx)?; + Some(FoundPath::new(project_path, path.clone())) + } Match::Channel { .. } | Match::CreateNew(_) => None, }), ) @@ -1160,6 +1210,10 @@ impl FileFinderDelegate { Match::Search(path_match) => { retain_path(&project_path_for_search_match(project, &path_match.0, cx)) } + Match::Absolute(path) => project + .read(cx) + .project_path_for_absolute_path(path, cx) + .is_none_or(|path| retain_path(&path)), Match::Channel { .. } | Match::CreateNew(_) => true, }; self.selected_matches.retain(|entry| retain_match(&entry.0)); @@ -1177,13 +1231,26 @@ impl FileFinderDelegate { self.selected_index = selected_index.min(self.matches.len().saturating_sub(1)); } - fn prepend_selected_matches(&mut self) { + fn prepend_selected_matches(&mut self, cx: &App) { if self.selected_matches.is_empty() { return; } - self.matches - .matches - .retain(|m| !self.selected_matches.iter().any(|selected| selected == m)); + self.matches.matches.retain(|entry| { + !self.selected_matches.iter().any(|selected| { + selected == entry + || match (&selected.0, entry) { + (Match::Absolute(path), other) | (other, Match::Absolute(path)) => { + other.abs_path(&self.project, cx).as_ref() == Some(path) + } + (Match::History { path, .. }, Match::Search(search)) + | (Match::Search(search), Match::History { path, .. }) => { + path.project + == project_path_for_search_match(&self.project, &search.0, cx) + } + _ => false, + } + }) + }); let mut new: Vec = self .selected_matches .iter() @@ -1209,6 +1276,64 @@ impl FileFinderDelegate { .visible_worktrees_and_single_files(cx) .collect::>(); let include_root_name = !should_hide_root_in_entry_path(&worktree_store, cx); + let path_style = self.project.read(cx).path_style(cx); + let mut exact_matches = Vec::new(); + if !query.path_query().ends_with(path_style.separators_ch()) + && let Ok(query_path) = RelPath::new(Path::new(query.path_query()), path_style) + { + for worktree in &worktrees { + let worktree = worktree.read(cx); + if worktree.is_single_file() { + continue; + } + let prefixed_path = include_root_name + .then(|| query_path.strip_prefix(worktree.root_name()).ok()) + .flatten(); + for path in std::iter::once(query_path.as_ref()).chain(prefixed_path) { + let project_path = ProjectPath { + worktree_id: worktree.id(), + path: Arc::from(path), + }; + if worktree.entry_for_path(path).is_some() + || !WorktreeSettings::get(Some(SettingsLocation::from(&project_path)), cx) + .is_path_excluded(path) + { + continue; + } + let absolute_path = worktree.absolutize(path); + let Some(absolute_path) = absolute_path.to_str() else { + continue; + }; + let resolve_path = self.project.read(cx).resolve_abs_path(absolute_path, cx); + let path_prefix = if include_root_name { + Arc::from(worktree.root_name()) + } else { + RelPath::empty_arc() + }; + let full_path = path_prefix.join(path); + let matched_start = + full_path.as_unix_str().len() - query_path.as_unix_str().len(); + let path_match = PathMatch { + score: f64::INFINITY, + positions: full_path.as_unix_str()[matched_start..] + .char_indices() + .map(|(offset, _)| matched_start + offset) + .collect(), + worktree_id: project_path.worktree_id.to_usize(), + path: project_path.path, + path_prefix, + is_dir: false, + distance_to_relative_ancestor: usize::MAX, + }; + exact_matches.push(async move { + resolve_path + .await + .filter(|path| path.is_file()) + .map(|_| ProjectPanelOrdMatch(path_match)) + }); + } + } + } let candidate_sets = worktrees .into_iter() .map(|worktree| { @@ -1241,6 +1366,12 @@ impl FileFinderDelegate { .await .into_iter() .map(ProjectPanelOrdMatch); + let exact_matches = join_all(exact_matches) + .await + .into_iter() + .flatten() + .collect::>(); + let matches = exact_matches.into_iter().chain(matches); let did_cancel = cancel_flag.load(atomic::Ordering::Acquire); picker .update(cx, |picker, cx| { @@ -1248,7 +1379,7 @@ impl FileFinderDelegate { .delegate .set_search_matches(search_id, did_cancel, query, matches, cx) }) - .log_err(); + .ok(); }) } @@ -1360,6 +1491,7 @@ impl FileFinderDelegate { let query_path = query.path_query(); if let Ok(mut query_path) = RelPath::new(Path::new(query_path), path_style) { + let original_query_path = query_path.clone(); let available_worktree = self .project .read(cx) @@ -1393,8 +1525,15 @@ impl FileFinderDelegate { if let Some(worktree) = expect_worktree { let worktree = worktree.read(cx); if worktree.entry_for_path(&query_path).is_none() - && !query.path_query().ends_with('/') - && !(path_style.is_windows() && query.path_query().ends_with('\\')) + && !self.matches.matches.iter().any(|entry| { + entry.panel_match().is_some_and(|path_match| { + (path_match.0.worktree_id == worktree.id().to_usize() + && *path_match.0.path == *query_path) + || path_match.0.path_prefix.join(&path_match.0.path) + == *original_query_path + }) + }) + && !query.path_query().ends_with(path_style.separators_ch()) { self.matches.matches.push(Match::CreateNew(ProjectPath { worktree_id: worktree.id(), @@ -1404,7 +1543,7 @@ impl FileFinderDelegate { } } - self.prepend_selected_matches(); + self.prepend_selected_matches(cx); self.selected_index = if !self.selected_matches.is_empty() { 0 @@ -1484,6 +1623,16 @@ impl FileFinderDelegate { } } Match::Search(path_match) => self.labels_for_path_match(&path_match.0, path_style), + Match::Absolute(path) => ( + path_style + .file_name(path) + .map_or_else(String::new, |name| name.to_string_lossy().into_owned()), + Vec::new(), + path_style.parent(path).map_or_else(String::new, |parent| { + parent.to_string_lossy().into_owned() + path_style.primary_separator() + }), + Vec::new(), + ), Match::Channel { channel_name, string_match, @@ -1618,63 +1767,103 @@ impl FileFinderDelegate { ) } - /// Attempts to resolve an absolute file path and update the search matches if found. - /// - /// If the query path resolves to an absolute file that exists in the project, - /// this method will find the corresponding worktree and relative path, create a - /// match for it, and update the picker's search results. - /// - /// Returns `true` if the absolute path exists, otherwise returns `false`. + fn should_strip_diff_prefix(&self, prefix: &str, cx: &App) -> Task { + let Ok(prefix) = RelPath::from_unix_str(prefix) else { + return Task::ready(false); + }; + let project = self.project.read(cx); + let mut absolute_paths = Vec::new(); + for worktree in project.worktrees(cx) { + let worktree = worktree.read(cx); + if let Some(entry) = worktree.entry_for_path(prefix) { + if entry.is_dir() { + return Task::ready(false); + } + continue; + } + let location = SettingsLocation { + worktree_id: worktree.id(), + path: prefix, + }; + if WorktreeSettings::get(Some(location), cx).is_path_excluded(prefix) { + absolute_paths.push(worktree.absolutize(prefix)); + } + } + let checks = absolute_paths + .iter() + .filter_map(|path| path.to_str()) + .map(|path| project.resolve_abs_path(path, cx)) + .collect::>(); + if checks.is_empty() { + return Task::ready(true); + } + cx.background_spawn(async move { + !join_all(checks) + .await + .into_iter() + .flatten() + .any(|path| path.is_dir()) + }) + } + fn lookup_absolute_path( - &self, + &mut self, query: FileSearchQuery, window: &mut Window, cx: &mut Context>, ) -> Task { + let project = self.project.clone(); + let search_id = post_inc(&mut self.search_count); + let resolve_path = project.update(cx, |project, cx| { + project.resolve_abs_file_path(query.path_query(), cx) + }); cx.spawn_in(window, async move |picker, cx| { - let Some(project) = picker - .read_with(cx, |picker, _| picker.delegate.project.clone()) - .log_err() + let Some(absolute_path) = resolve_path.await.and_then(|path| path.into_abs_path()) else { return false; }; - - let query_path = Path::new(query.path_query()); - let mut path_matches = Vec::new(); - - let abs_file_exists = project - .update(cx, |this, cx| { - this.resolve_abs_file_path(query.path_query(), cx) - }) - .await - .is_some(); - - if abs_file_exists { - project.update(cx, |project, cx| { - if let Some((worktree, relative_path)) = project.find_worktree(query_path, cx) { - path_matches.push(ProjectPanelOrdMatch(PathMatch { - score: 1.0, - positions: Vec::new(), - worktree_id: worktree.read(cx).id().to_usize(), - path: relative_path, - path_prefix: RelPath::empty_arc(), - is_dir: false, // File finder doesn't support directories - distance_to_relative_ancestor: usize::MAX, - })); - } - }); - } - + let absolute_path = PathBuf::from(absolute_path); picker - .update_in(cx, |picker, _, cx| { - let picker_delegate = &mut picker.delegate; - let search_id = util::post_inc(&mut picker_delegate.search_count); - picker_delegate.set_search_matches(search_id, false, query, path_matches, cx); - - anyhow::Ok(()) + .update(cx, |picker, cx| { + let delegate = &mut picker.delegate; + if search_id < delegate.latest_search_id { + return; + } + let path_match = project + .read(cx) + .find_worktree(&absolute_path, cx) + .filter(|(worktree, _)| worktree.read(cx).is_visible()) + .map(|(worktree, relative_path)| { + ProjectPanelOrdMatch(PathMatch { + score: 1.0, + positions: Vec::new(), + worktree_id: worktree.read(cx).id().to_usize(), + path: if worktree.read(cx).is_single_file() { + Arc::from(worktree.read(cx).root_name()) + } else { + relative_path + }, + path_prefix: RelPath::empty_arc(), + is_dir: false, + distance_to_relative_ancestor: usize::MAX, + }) + }); + let outside_project = path_match.is_none(); + delegate.set_search_matches(search_id, false, query, path_match, cx); + if outside_project { + delegate.matches.matches.retain(|entry| { + entry.abs_path(&project, cx).as_ref() != Some(&absolute_path) + }); + delegate + .matches + .matches + .insert(0, Match::Absolute(absolute_path)); + delegate.prepend_selected_matches(cx); + delegate.selected_index = 0; + } }) - .log_err(); - abs_file_exists + .ok(); + true }) } @@ -1756,10 +1945,10 @@ impl FileFinderDelegate { let focus_item = dismiss_after_open; let open_task = workspace.update(cx, |workspace, cx| { - let split_or_open = |workspace: &mut Workspace, - project_path, - window: &mut Window, - cx: &mut Context| { + let split_or_open = move |workspace: &mut Workspace, + project_path, + window: &mut Window, + cx: &mut Context| { if secondary { workspace.split_path_preview(project_path, allow_preview, None, window, cx) } else { @@ -1791,42 +1980,22 @@ impl FileFinderDelegate { ) } } - Match::History { path, .. } => { - let worktree_id = path.project.worktree_id; - if workspace - .project() - .read(cx) - .worktree_for_id(worktree_id, cx) - .is_some() - { - split_or_open( - workspace, - ProjectPath { - worktree_id, - path: Arc::clone(&path.project.path), - }, - window, - cx, - ) - } else if secondary { - workspace.split_abs_path(path.absolute.clone(), false, window, cx) - } else { - workspace.open_abs_path( - path.absolute.clone(), - OpenOptions { - visible: Some(OpenVisible::None), - ..Default::default() - }, - window, - cx, - ) - } - } Match::Search(path_match) => { let project_path = project_path_for_search_match(workspace.project(), &path_match.0, cx); split_or_open(workspace, project_path, window, cx) } + Match::History { .. } | Match::Absolute(_) => { + let resolve_path = m.resolve_project_path(workspace.project(), cx); + cx.spawn_in(window, async move |workspace, cx| { + let (_worktree, path) = resolve_path.await?; + workspace + .update_in(cx, |workspace, window, cx| { + split_or_open(workspace, path, window, cx) + })? + .await + }) + } Match::Channel { .. } => unreachable!("handled above"), } }); @@ -1887,37 +2056,39 @@ impl FileFinderDelegate { return; }; let selected = std::mem::take(&mut self.selected_matches); - let paths: Vec = selected - .iter() - .filter_map(|selected| match &selected.0 { - Match::History { path, .. } => Some(ProjectPath { - worktree_id: path.project.worktree_id, - path: Arc::clone(&path.project.path), - }), - Match::Search(m) => Some(project_path_for_search_match(&self.project, &m.0, cx)), - Match::Channel { .. } | Match::CreateNew(_) => None, - }) - .collect(); - if paths.is_empty() { + if selected.is_empty() { return; } + let paths = selected + .iter() + .map(|selected| selected.0.resolve_project_path(&self.project, cx)) + .collect::>(); workspace.update(cx, |workspace, cx| { let new_pane = workspace.split_pane(workspace.active_pane().clone(), split_direction, window, cx); let count = paths.len(); - for (i, path) in paths.into_iter().enumerate() { - let focus_item = i + 1 == count; - workspace - .open_path_preview( - path, - Some(new_pane.downgrade()), - focus_item, - false, - true, - window, - cx, - ) - .detach_and_log_err(cx); + for (index, path) in paths.into_iter().enumerate() { + let new_pane = new_pane.downgrade(); + let is_last = index + 1 == count; + cx.spawn_in(window, async move |workspace, cx| { + let (_worktree, path) = path.await?; + let Ok(open_task) = workspace.update_in(cx, |workspace, window, cx| { + workspace.open_path_preview( + path, + Some(new_pane), + is_last, + false, + is_last, + window, + cx, + ) + }) else { + return anyhow::Ok(()); + }; + open_task.await?; + Ok(()) + }) + .detach_and_log_err(cx); } }); // Deferred because this runs from a `FileFinder` action handler, so @@ -2032,27 +2203,10 @@ impl PickerDelegate for FileFinderDelegate { let debounce_refresh = mem::take(&mut self.debounce_next_refresh); let raw_query = raw_query.trim(); - let raw_query = match &raw_query.get(0..2) { - Some(".\\" | "./") => &raw_query[2..], - Some(prefix @ ("a\\" | "a/" | "b\\" | "b/")) => { - if self - .workspace - .upgrade() - .into_iter() - .flat_map(|workspace| workspace.read(cx).worktrees(cx)) - .all(|worktree| { - worktree - .read(cx) - .entry_for_path(RelPath::from_unix_str(prefix.split_at(1).0).unwrap()) - .is_none_or(|entry| !entry.is_dir()) - }) - { - &raw_query[2..] - } else { - raw_query - } - } - _ => raw_query, + let (raw_query, diff_prefix) = match raw_query.split_once(['/', '\\']) { + Some((".", remainder)) => (remainder, None), + Some((prefix @ ("a" | "b"), _)) => (raw_query, Some(prefix.to_owned())), + _ => (raw_query, None), }; if raw_query.is_empty() { @@ -2090,19 +2244,17 @@ impl PickerDelegate for FileFinderDelegate { self.first_update = false; self.selected_index = 0; } - self.prepend_selected_matches(); + self.prepend_selected_matches(cx); cx.notify(); self.search_in_flight .store(false, atomic::Ordering::Release); Task::ready(()) } else { - let query = parse_file_search_query(raw_query); - let path = query.path_position.path.clone(); - + let raw_query = raw_query.to_owned(); let search_in_flight = self.search_in_flight.clone(); let was_in_flight = search_in_flight.swap(true, atomic::Ordering::Relaxed); - cx.spawn_in(window, async move |this, cx| { + cx.spawn_in(window, async move |picker, cx| { if debounce_refresh { cx.background_executor() .timer(WORKTREE_UPDATE_REFRESH_DEBOUNCE) @@ -2111,11 +2263,37 @@ impl PickerDelegate for FileFinderDelegate { cx.background_executor().timer(SEARCH_DEBOUNCE).await; } let _ = maybe!(async move { - let is_absolute_path = path.is_absolute(); + let strip_diff_prefix = if let Some(prefix) = diff_prefix { + picker + .read_with(cx, |picker, cx| { + picker.delegate.should_strip_diff_prefix(&prefix, cx) + })? + .await + } else { + false + }; + let raw_query = if strip_diff_prefix { + raw_query + .split_once(['/', '\\']) + .map_or(raw_query.as_str(), |(_, remainder)| remainder) + } else { + &raw_query + }; + if raw_query.is_empty() { + picker + .update_in(cx, |picker, window, cx| { + picker.delegate.update_matches(String::new(), window, cx) + })? + .await; + return anyhow::Ok(()); + } + let query = parse_file_search_query(raw_query); + let is_absolute_path = query.path_position.path.is_absolute(); let did_resolve_abs_path = is_absolute_path - && this - .update_in(cx, |this, window, cx| { - this.delegate + && picker + .update_in(cx, |picker, window, cx| { + picker + .delegate .lookup_absolute_path(query.clone(), window, cx) })? .await; @@ -2123,10 +2301,11 @@ impl PickerDelegate for FileFinderDelegate { // Only check for relative paths if no absolute paths were // found. if !did_resolve_abs_path { - this.update_in(cx, |this, window, cx| { - this.delegate.spawn_search(query, window, cx) - })? - .await; + picker + .update_in(cx, |picker, window, cx| { + picker.delegate.spawn_search(query, window, cx) + })? + .await; } anyhow::Ok(()) }) @@ -2331,7 +2510,7 @@ impl FileFinderDelegate { .size(IconSize::Small) .into_any_element(), ), - Match::Search(_) | Match::Channel { .. } => Some( + Match::Search(_) | Match::Absolute(_) | Match::Channel { .. } => Some( div() .flex_none() .size(IconSize::Small.rems()) diff --git a/crates/file_finder/src/file_finder_tests.rs b/crates/file_finder/src/file_finder_tests.rs index 84bf6a2fc94..59cff873c66 100644 --- a/crates/file_finder/src/file_finder_tests.rs +++ b/crates/file_finder/src/file_finder_tests.rs @@ -12,8 +12,8 @@ use serde_json::json; use settings::{SettingsStore, SplicingVec}; use util::{path, rel_path::rel_path}; use workspace::{ - AppState, CloseActiveItem, Item, MultiWorkspace, OpenOptions, ToggleFileFinder, Workspace, - open_paths, + AppState, CloseActiveItem, Item, MultiWorkspace, OpenOptions, OpenVisible, ToggleFileFinder, + Workspace, invalid_item_view::InvalidItemView, open_paths, }; #[ctor::ctor(unsafe)] @@ -400,6 +400,379 @@ async fn test_absolute_paths(cx: &mut TestAppContext) { }); } +#[gpui::test] +async fn test_exact_excluded_paths(cx: &mut TestAppContext) { + let app_state = init_test(cx); + cx.update(|cx| { + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.project.worktree.file_scan_exclusions = Some(SplicingVec::from(vec![ + "**/docs".to_string(), + "**/.DS_Store".to_string(), + "**/a".to_string(), + "**/b".to_string(), + ])); + }); + }); + }); + app_state + .fs + .as_fake() + .insert_tree( + path!("/root"), + json!({ + "docs": { "spec.json": "first\nsecond\nthird" }, + ".DS_Store": "metadata", + "a": { "config.json": "excluded" }, + "config.json": "root", + }), + ) + .await; + let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await; + let (picker, workspace, cx) = build_find_picker(project.clone(), cx); + + for query in [ + "spec.json", + "docs/sp", + "docs/missing.json", + "./b/config.json", + ".\\b/config.json", + "a/missing.json", + ] { + assert_eq!( + search_file_paths(&picker, query, cx).await, + vec![None], + "query: {query}" + ); + } + for query in ["docs/", "a/", "b/"] { + assert_eq!(search_file_paths(&picker, query, cx).await, Vec::new()); + } + for (query, expected_path) in [ + (path!("/root/docs/spec.json"), path!("/root/docs/spec.json")), + (path!("/root/.DS_Store"), path!("/root/.DS_Store")), + ("docs/spec.json", path!("/root/docs/spec.json")), + ("./docs/spec.json", path!("/root/docs/spec.json")), + (".\\docs/spec.json", path!("/root/docs/spec.json")), + ("a/config.json", path!("/root/a/config.json")), + ("./a/config.json", path!("/root/a/config.json")), + ("b/config.json", path!("/root/config.json")), + ("b\\config.json", path!("/root/config.json")), + ("docs/spec.json:2:3", path!("/root/docs/spec.json")), + ] { + assert_eq!( + search_file_paths(&picker, query, cx).await, + vec![Some(PathBuf::from(expected_path))], + "query: {query}" + ); + } + cx.dispatch_action(Confirm); + cx.read(|cx| { + let editor = workspace.read(cx).active_item_as::(cx).unwrap(); + assert_eq!(editor.read(cx).text(cx), "first\nsecond\nthird"); + let worktree = project.read(cx).visible_worktrees(cx).next().unwrap(); + assert!( + worktree + .read(cx) + .entry_for_path(rel_path("docs/spec.json")) + .is_none() + ); + }); + + app_state + .fs + .as_fake() + .insert_tree( + path!("/other"), + json!({ + "docs": { "spec.json": "other" }, + }), + ) + .await; + project + .update(cx, |project, cx| { + project.find_or_create_worktree(path!("/other"), true, cx) + }) + .await + .unwrap(); + let picker = open_file_picker(&workspace, cx); + assert_eq!( + search_file_paths(&picker, "other/docs/spec.json", cx).await, + vec![Some(PathBuf::from(path!("/other/docs/spec.json")))] + ); +} + +#[gpui::test] +async fn test_absolute_paths_outside_project(cx: &mut TestAppContext) { + let app_state = init_test(cx); + bind_default_keymap(cx); + app_state + .fs + .as_fake() + .insert_tree( + path!("/root"), + json!({ + "project": {}, + "outside": { ".DS_Store": "metadata", "文件.txt": "first\nsecond" }, + }), + ) + .await; + let project = Project::test(app_state.fs.clone(), [path!("/root/project").as_ref()], cx).await; + let (picker, workspace, cx) = build_find_picker(project.clone(), cx); + + for query in [path!("/root/outside/missing.txt"), path!("/root/outside")] { + assert_eq!(search_file_paths(&picker, query, cx).await, Vec::new()); + } + let positioned_path = format!("{}:2:3", path!("/root/outside/文件.txt")); + for (query, expected_path) in [ + ( + path!("/root/outside/.DS_Store"), + path!("/root/outside/.DS_Store"), + ), + (positioned_path.as_str(), path!("/root/outside/文件.txt")), + ] { + assert_eq!( + search_file_paths(&picker, query, cx).await, + vec![Some(PathBuf::from(expected_path))] + ); + cx.read(|cx| assert_eq!(project.read(cx).visible_worktrees(cx).count(), 1)); + } + cx.simulate_keystrokes("enter"); + cx.read(|cx| assert!(workspace.read(cx).active_modal::(cx).is_none())); + cx.update(|_, cx| { + let editor = workspace.read(cx).active_item_as::(cx).unwrap(); + editor.update(cx, |editor, cx| { + assert_eq!(editor.text(cx), "first\nsecond"); + assert_eq!( + editor + .selections + .newest::(&editor.display_snapshot(cx)) + .head(), + Point::new(1, 2) + ); + }); + }); + + let picker = open_file_picker(&workspace, cx); + assert_eq!( + search_file_paths(&picker, "", cx).await, + vec![Some(PathBuf::from(path!("/root/outside/文件.txt")))] + ); + for query in [ + path!("/root/outside/.DS_Store"), + path!("/root/outside/文件.txt"), + ] { + let paths = search_file_paths(&picker, query, cx).await; + let index = paths + .iter() + .position(|path| path.as_deref() == Some(Path::new(query))) + .unwrap(); + picker.update_in(cx, |picker, window, cx| { + let (name, _) = picker.delegate.labels_for_match( + picker.delegate.matches.get(index).unwrap(), + window, + cx, + ); + assert_eq!( + name.text(), + Path::new(query).file_name().unwrap().to_str().unwrap() + ); + picker.delegate.toggle_item_selected(index, window, cx); + }); + } + for query in [".DS_Store", "文件.txt"] { + assert_eq!( + search_file_paths(&picker, query, cx) + .await + .into_iter() + .flatten() + .collect::>(), + vec![ + PathBuf::from(path!("/root/outside/.DS_Store")), + PathBuf::from(path!("/root/outside/文件.txt")) + ] + ); + } + cx.dispatch_action(pane::SplitRight::default()); + cx.read(|cx| { + let workspace = workspace.read(cx); + assert_eq!(workspace.panes().len(), 2); + assert_eq!( + workspace + .active_item_as::(cx) + .unwrap() + .read(cx) + .title(cx), + "文件.txt" + ); + let mut titles = workspace + .active_pane() + .read(cx) + .items() + .map(|item| item.downcast::().unwrap().read(cx).title(cx)) + .collect::>(); + titles.sort(); + assert_eq!(titles, vec![".DS_Store", "文件.txt"]); + }); + + let picker = open_file_picker(&workspace, cx); + search_file_paths(&picker, ".DS_Store", cx).await; + picker.update_in(cx, |picker, window, cx| { + picker.delegate.toggle_item_selected(0, window, cx); + }); + assert_eq!( + search_file_paths(&picker, path!("/root/outside/.DS_Store"), cx).await, + vec![Some(PathBuf::from(path!("/root/outside/.DS_Store")))] + ); +} + +#[gpui::test] +async fn test_binary_absolute_path_history(cx: &mut TestAppContext) { + let app_state = init_test(cx); + bind_default_keymap(cx); + app_state + .fs + .as_fake() + .insert_tree( + path!("/root"), + json!({ + "project": { + "main.rs": "fn main() {}", + "binary.dat": "\0".repeat(1024), + }, + "outside": { ".DS_Store": "\0".repeat(1024) }, + }), + ) + .await; + let project = Project::test(app_state.fs.clone(), [path!("/root/project").as_ref()], cx).await; + let (picker, workspace, cx) = build_find_picker(project.clone(), cx); + let project_file = path!("/root/project/main.rs"); + assert_eq!( + search_file_paths(&picker, "main.rs", cx).await, + vec![Some(PathBuf::from(project_file))] + ); + cx.simulate_keystrokes("enter"); + drop(picker); + let picker = open_file_picker(&workspace, cx); + let absolute_path = path!("/root/outside/.DS_Store"); + let query = format!("{absolute_path}\n"); + assert_eq!( + search_file_paths(&picker, &query, cx).await, + vec![Some(PathBuf::from(absolute_path))] + ); + cx.simulate_keystrokes("enter"); + cx.condition(&workspace, |workspace, cx| { + workspace.active_modal::(cx).is_none() + }) + .await; + drop(picker); + let (item, external_worktree_id) = cx.read(|cx| { + let workspace = workspace.read(cx); + let item = workspace.active_item_as::(cx).unwrap(); + assert_eq!( + item.read(cx).error.as_ref(), + "Binary files are not supported" + ); + ( + item.downgrade(), + item.read(cx).active_project_path(cx).unwrap().worktree_id, + ) + }); + let picker = open_file_picker(&workspace, cx); + assert_eq!( + search_file_paths(&picker, "", cx).await, + vec![ + Some(PathBuf::from(absolute_path)), + Some(PathBuf::from(project_file)), + ] + ); + assert_eq!( + search_file_paths(&picker, "main.rs", cx).await, + vec![Some(PathBuf::from(project_file))] + ); + cx.simulate_keystrokes("escape"); + drop(picker); + workspace + .update_in(cx, |workspace, window, cx| { + workspace.active_pane().update(cx, |pane, cx| { + pane.activate_item(0, true, true, window, cx); + }); + workspace.clear_navigation_history(window, cx); + workspace.active_pane().update(cx, |pane, cx| { + pane.close_item_by_id(item.entity_id(), pane::SaveIntent::Close, window, cx) + }) + }) + .await + .unwrap(); + cx.run_until_parked(); + cx.read(|cx| { + assert!(item.upgrade().is_none()); + assert!( + project + .read(cx) + .worktree_for_id(external_worktree_id, cx) + .is_none() + ); + }); + let picker = open_file_picker(&workspace, cx); + assert_eq!( + search_file_paths(&picker, "", cx).await, + vec![ + Some(PathBuf::from(project_file)), + Some(PathBuf::from(absolute_path)), + ] + ); + picker.update_in(cx, |picker, window, cx| { + picker.set_selected_index(1, None, false, window, cx); + }); + cx.dispatch_action(pane::SplitRight::default()); + cx.run_until_parked(); + cx.read(|cx| { + let workspace = workspace.read(cx); + assert_eq!(workspace.panes().len(), 2); + let reopened = workspace.active_item_as::(cx).unwrap(); + assert_ne!(reopened.entity_id(), item.entity_id()); + assert_eq!( + reopened.read(cx).error.as_ref(), + "Binary files are not supported" + ); + }); + drop(picker); + let picker = open_file_picker(&workspace, cx); + let deleted_path = path!("/root/project/binary.dat"); + assert_eq!( + search_file_paths(&picker, deleted_path, cx).await, + vec![Some(PathBuf::from(deleted_path))] + ); + cx.simulate_keystrokes("enter"); + drop(picker); + app_state + .fs + .remove_file(Path::new(deleted_path), RemoveOptions::default()) + .await + .unwrap(); + advance_worktree_update_refresh(cx); + cx.dispatch_action(CloseActiveItem::default()); + cx.read(|cx| { + let mut history = workspace + .read(cx) + .recent_navigation_history(None, cx) + .into_iter() + .map(|(path, absolute_path)| { + absolute_path.or_else(|| project.read(cx).absolute_path(&path, cx)) + }) + .collect::>(); + history.sort(); + assert_eq!( + history, + vec![ + Some(PathBuf::from(absolute_path)), + Some(PathBuf::from(project_file)), + ] + ); + }); +} + #[gpui::test] async fn test_complex_path(cx: &mut TestAppContext) { let app_state = init_test(cx); @@ -3542,6 +3915,187 @@ async fn test_nonexistent_history_items_not_shown(cx: &mut gpui::TestAppContext) }); } +#[gpui::test] +async fn test_remote_diff_prefix_avoids_unnecessary_metadata( + cx: &mut TestAppContext, + server_cx: &mut TestAppContext, +) { + cx.update(|cx| release_channel::init("0.0.0".parse().unwrap(), cx)); + server_cx.update(|cx| release_channel::init("0.0.0".parse().unwrap(), cx)); + let app_state = init_test(cx); + let server_app_state = init_test(server_cx); + let server_fs = server_app_state.fs.as_fake(); + server_fs + .insert_tree( + path!("/remote"), + json!({ + "first": { + ".zed": { + "settings.json": r#"{"file_scan_exclusions": ["**/a"]}"#, + }, + "a": { "file.rs": "" }, + }, + "second": { "a": { "file.rs": "" } }, + }), + ) + .await; + + let (options, session, _) = RemoteClient::fake_server(cx, server_cx); + server_cx.update(HeadlessProject::init); + let _headless_project = server_cx.new(|cx| { + HeadlessProject::new( + HeadlessAppState { + session, + fs: server_app_state.fs.clone(), + http_client: server_app_state.client.http_client(), + node_runtime: server_app_state.node_runtime.clone(), + languages: server_app_state.languages.clone(), + extension_host_proxy: Arc::default(), + startup_time: std::time::Instant::now(), + }, + false, + cx, + ) + }); + let remote = RemoteClient::connect_mock(options, cx).await; + let project = cx.update(|cx| { + Project::init(&app_state.client, cx); + Project::remote( + remote, + app_state.client.clone(), + app_state.node_runtime.clone(), + app_state.user_store.clone(), + app_state.languages.clone(), + app_state.fs.clone(), + false, + cx, + ) + }); + let (first_worktree, _) = project + .update(cx, |project, cx| { + project.find_or_create_worktree(path!("/remote/first"), true, cx) + }) + .await + .unwrap(); + let (multi_workspace, cx) = cx.add_window_view(|window, cx| { + window.activate_window(); + let workspace = + cx.new(|cx| Workspace::new(None, project.clone(), app_state.clone(), window, cx)); + window.focus(&workspace.read(cx).focus_handle(cx), cx); + MultiWorkspace::new(workspace, window, cx) + }); + let workspace = multi_workspace.read_with(cx, |workspace, _| workspace.workspace().clone()); + let picker = open_file_picker(&workspace, cx); + cx.run_until_parked(); + first_worktree.read_with(cx, |worktree, cx| { + assert!(worktree.as_remote().is_some()); + assert_eq!(worktree.scan_id(), worktree.completed_scan_id()); + assert!(worktree.entry_for_path(rel_path("a")).is_none()); + assert!( + WorktreeSettings::get( + Some(SettingsLocation { + worktree_id: worktree.id(), + path: rel_path("a"), + }), + cx, + ) + .is_path_excluded(rel_path("a")) + ); + }); + + let baseline = server_fs.metadata_call_count(); + let strip_prefix = picker + .read_with(cx, |picker, cx| { + picker.delegate.should_strip_diff_prefix("a", cx) + }) + .await; + cx.run_until_parked(); + assert!(!strip_prefix); + assert_eq!(server_fs.metadata_call_count() - baseline, 1); + + let baseline = server_fs.metadata_call_count(); + picker.update_in(cx, |picker, window, cx| { + picker.update_matches("x".to_string(), window, cx); + picker.update_matches("a/file.rs".to_string(), window, cx); + }); + cx.run_until_parked(); + let mut metadata_calls = vec![( + "search debounce", + server_fs.metadata_call_count() - baseline, + )]; + picker.update_in(cx, |picker, window, cx| { + picker.update_matches("x".to_string(), window, cx) + }); + cx.executor().advance_clock(SEARCH_DEBOUNCE); + cx.run_until_parked(); + metadata_calls.push(( + "search cancellation", + server_fs.metadata_call_count() - baseline, + )); + + let (second_worktree, _) = project + .update(cx, |project, cx| { + project.find_or_create_worktree(path!("/remote/second"), true, cx) + }) + .await + .unwrap(); + cx.run_until_parked(); + server_fs + .touch_path(path!("/remote/first/.zed/settings.json")) + .await; + advance_worktree_update_refresh(cx); + project.read_with(cx, |project, cx| { + assert_eq!( + project + .worktrees(cx) + .map(|worktree| { + let worktree = worktree.read(cx); + assert_eq!(worktree.scan_id(), worktree.completed_scan_id()); + ( + worktree.id(), + worktree + .entry_for_path(rel_path("a")) + .map(|entry| entry.is_dir()), + WorktreeSettings::get( + Some(SettingsLocation { + worktree_id: worktree.id(), + path: rel_path("a"), + }), + cx, + ) + .is_path_excluded(rel_path("a")), + ) + }) + .collect::>(), + vec![ + (first_worktree.read(cx).id(), None, true), + (second_worktree.read(cx).id(), Some(true), false), + ] + ); + }); + + let baseline = server_fs.metadata_call_count(); + let strip_prefix = picker + .read_with(cx, |picker, cx| { + picker.delegate.should_strip_diff_prefix("a", cx) + }) + .await; + cx.run_until_parked(); + assert!(!strip_prefix); + metadata_calls.push(( + "later indexed directory", + server_fs.metadata_call_count() - baseline, + )); + assert_eq!( + metadata_calls, + vec![ + ("search debounce", 0), + ("search cancellation", 0), + ("later indexed directory", 0), + ] + ); +} + #[gpui::test] async fn test_deleted_remote_history_items_not_shown( cx: &mut TestAppContext, @@ -5033,6 +5587,46 @@ fn simulate_input(cx: &mut VisualTestContext, input: &str) { cx.run_until_parked(); } +fn bind_default_keymap(cx: &mut TestAppContext) { + cx.update(|cx| { + let asset = if cfg!(target_os = "macos") { + "keymaps/default-macos.json" + } else if cfg!(target_os = "windows") { + "keymaps/default-windows.json" + } else { + "keymaps/default-linux.json" + }; + let bindings = settings::KeymapFile::load_asset_allow_partial_failure(asset, cx).unwrap(); + cx.bind_keys(bindings); + }); +} + +async fn search_file_paths( + picker: &Entity>, + query: &str, + cx: &mut VisualTestContext, +) -> Vec> { + picker.update_in(cx, |picker, window, cx| picker.set_query(query, window, cx)); + cx.run_until_parked(); + cx.condition(picker, |picker, _| { + !picker + .delegate + .search_in_flight + .load(atomic::Ordering::Relaxed) + }) + .await; + cx.run_until_parked(); + picker.read_with(cx, |picker, cx| { + picker + .delegate + .matches + .matches + .iter() + .map(|entry| entry.abs_path(&picker.delegate.project, cx)) + .collect() + }) +} + fn advance_worktree_update_refresh(cx: &mut VisualTestContext) { cx.executor() .advance_clock(FS_WATCH_LATENCY + WORKTREE_UPDATE_REFRESH_DEBOUNCE); @@ -5060,11 +5654,13 @@ struct SearchEntries { history_found_paths: Vec, search: Vec>, search_matches: Vec, + absolute: Vec, } impl SearchEntries { #[track_caller] fn search_paths_only(self) -> Vec> { + assert_eq!(self.absolute, Vec::::new()); assert!( self.history.is_empty(), "Should have no history matches, but got: {:?}", @@ -5075,6 +5671,7 @@ impl SearchEntries { #[track_caller] fn search_matches_only(self) -> Vec { + assert_eq!(self.absolute, Vec::::new()); assert!( self.history.is_empty(), "Should have no history matches, but got: {:?}", @@ -5111,6 +5708,7 @@ fn collect_search_matches(picker: &Picker) -> SearchEntries .push(path_match.0.path_prefix.join(&path_match.0.path).into()); search_entries.search_matches.push(path_match.0.clone()); } + Match::Absolute(path) => search_entries.absolute.push(path.clone()), Match::CreateNew(_) => {} Match::Channel { .. } => {} } @@ -5335,6 +5933,7 @@ fn assert_match_at_position( let match_file_name = match &match_item { Match::History { path, .. } => path.absolute.file_name().and_then(|s| s.to_str()), Match::Search(path_match) => path_match.0.path.file_name(), + Match::Absolute(path) => path.file_name().and_then(|name| name.to_str()), Match::CreateNew(project_path) => project_path.path.file_name(), Match::Channel { channel_name, .. } => Some(channel_name.as_str()), } diff --git a/crates/git_ui/src/commit_view.rs b/crates/git_ui/src/commit_view.rs index 0e4faccbb1a..e2c94792c1f 100644 --- a/crates/git_ui/src/commit_view.rs +++ b/crates/git_ui/src/commit_view.rs @@ -360,9 +360,12 @@ impl CommitView { let project_clone = project.clone(); let reveal_file_clone = reveal_file.clone(); let mut files = commit_diff.files; + let commit_view_settings = EditorSettings::get_global(cx).commit_view; + // A view filtered to a single file is opened to look at that file, so keep it expanded. + let collapse_files = !commit_view_settings.expand_files && file_filter.is_none(); let load_diff_task = cx.spawn_in(window, async move |this, cx| { - let mut binary_buffer_ids: HashSet = HashSet::default(); + let mut folded_buffer_ids: HashSet = HashSet::default(); let mut file_statuses: HashMap = HashMap::default(); // In case there's a file we should scroll to, i.e., @@ -389,8 +392,9 @@ impl CommitView { file_statuses.insert(buffer_id, file_status); + // The revealed file is the one asked for, so keep it expanded. if is_binary { - binary_buffer_ids.insert(buffer_id); + folded_buffer_ids.insert(buffer_id); } // Establish the scroll anchor before inserting files that may @@ -415,8 +419,8 @@ impl CommitView { file_statuses.insert(buffer_id, file_status); - if is_binary { - binary_buffer_ids.insert(buffer_id); + if is_binary || collapse_files { + folded_buffer_ids.insert(buffer_id); } } @@ -430,8 +434,8 @@ impl CommitView { commit_view, }); - if !binary_buffer_ids.is_empty() { - editor.fold_buffers(binary_buffer_ids, cx); + if !folded_buffer_ids.is_empty() { + editor.fold_buffers(folded_buffer_ids, cx); } }); }); @@ -459,7 +463,7 @@ impl CommitView { commit, editor, message, - message_expanded: false, + message_expanded: commit_view_settings.expand_description, message_scroll_handle: ScrollHandle::new(), multibuffer, stash, @@ -1674,13 +1678,166 @@ fn stash_matches_index(sha: &str, stash_index: usize, repo: &Repository) -> bool #[cfg(test)] mod tests { use super::*; - use gpui::{EmptyView, TestAppContext}; + use gpui::{EmptyView, TestAppContext, UpdateGlobal, VisualTestContext}; use indoc::indoc; use language::{Language, LanguageConfig, LanguageMatcher, markdown_lang}; + use project::FakeFs; use serde_json::json; use settings::SettingsStore; use std::path::Path; use util::path; + use workspace::MultiWorkspace; + + fn init_test(cx: &mut TestAppContext) { + cx.update(|cx| { + let settings_store = SettingsStore::test(cx); + cx.set_global(settings_store); + theme_settings::init(theme::LoadThemes::JustBase, cx); + language_model::init(cx); + editor::init(cx); + crate::init(cx); + }); + } + + /// Opens a commit view for a commit that modifies `a.txt` and `b.txt`. + async fn open_test_commit_view( + file_filter: Option, + cx: &mut TestAppContext, + ) -> (Entity, &mut VisualTestContext) { + let fs = FakeFs::new(cx.executor()); + fs.insert_tree( + path!("/project"), + json!({ ".git": {}, "a.txt": "a new\n", "b.txt": "b new\n" }), + ) + .await; + let project = Project::test(fs, [Path::new(path!("/project"))], cx).await; + cx.run_until_parked(); + let repository = project.read_with(cx, |project, cx| { + project + .active_repository(cx) + .expect("project should have a repository") + }); + + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx)); + let workspace = multi_workspace.read_with(&*cx, |multi, _| multi.workspace().clone()); + + let commit = CommitDetails { + sha: "0123456789abcdef0123456789abcdef01234567".into(), + message: "Subject\n\nA longer description.".into(), + ..Default::default() + }; + let commit_diff = CommitDiff { + files: ["a.txt", "b.txt"] + .map(|path| CommitFile { + path: RepoPath::new(path).expect("valid repository path"), + old_text: Some(format!("{path} old\n")), + new_text: Some(format!("{path} new\n")), + is_binary: false, + }) + .into(), + is_shallow_boundary: false, + }; + let commit_view = workspace.update_in(cx, |workspace, window, cx| { + let workspace_entity = cx.entity(); + let commit_view = cx.new(|cx| { + CommitView::new( + commit, + commit_diff, + repository, + project.clone(), + workspace_entity, + CommitViewOptions { + file_filter, + ..Default::default() + }, + window, + cx, + ) + }); + workspace.add_item_to_active_pane( + Box::new(commit_view.clone()), + None, + true, + window, + cx, + ); + commit_view + }); + cx.run_until_parked(); + (commit_view, cx) + } + + fn folded_files(commit_view: &CommitView, cx: &App) -> usize { + let editor = commit_view.editor.read(cx).rhs_editor().read(cx); + commit_view + .multibuffer + .read(cx) + .all_buffers() + .iter() + .filter(|buffer| editor.is_buffer_folded(buffer.read(cx).remote_id(), cx)) + .count() + } + + #[gpui::test] + async fn test_commit_view_opens_with_defaults(cx: &mut TestAppContext) { + init_test(cx); + let (commit_view, cx) = open_test_commit_view(None, cx).await; + + commit_view.read_with(cx, |commit_view, cx| { + assert!(!commit_view.message_expanded); + assert_eq!(folded_files(commit_view, cx), 0); + }); + } + + #[gpui::test] + async fn test_commit_view_settings_expand_description_and_collapse_files( + cx: &mut TestAppContext, + ) { + init_test(cx); + cx.update(|cx| { + SettingsStore::update_global(cx, |store, cx| { + store.update_user_settings(cx, |settings| { + let commit_view = settings + .git + .get_or_insert_default() + .commit_view + .get_or_insert_default(); + commit_view.expand_description = Some(true); + commit_view.expand_files = Some(false); + }) + }); + }); + let (commit_view, cx) = open_test_commit_view(None, cx).await; + + commit_view.read_with(cx, |commit_view, cx| { + assert!(commit_view.message_expanded); + assert_eq!(folded_files(commit_view, cx), 2); + }); + } + + #[gpui::test] + async fn test_commit_view_filtered_to_file_ignores_collapse_files(cx: &mut TestAppContext) { + init_test(cx); + cx.update(|cx| { + SettingsStore::update_global(cx, |store, cx| { + store.update_user_settings(cx, |settings| { + settings + .git + .get_or_insert_default() + .commit_view + .get_or_insert_default() + .expand_files = Some(false); + }) + }); + }); + let file_filter = RepoPath::new("a.txt").expect("valid repository path"); + let (commit_view, cx) = open_test_commit_view(Some(file_filter), cx).await; + + commit_view.read_with(cx, |commit_view, cx| { + assert_eq!(folded_files(commit_view, cx), 0); + }); + } #[gpui::test] async fn test_build_buffer_resolves_injected_languages(cx: &mut TestAppContext) { diff --git a/crates/gpui/examples/input.rs b/crates/gpui/examples/input.rs index 5bff4ce3423..7b1a212b98f 100644 --- a/crates/gpui/examples/input.rs +++ b/crates/gpui/examples/input.rs @@ -470,14 +470,6 @@ struct PrepaintState { selection: Option, } -impl IntoElement for TextElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl Element for TextElement { type RequestLayoutState = (); type PrepaintState = PrepaintState; diff --git a/crates/gpui/examples/view_example/example_editor.rs b/crates/gpui/examples/view_example/example_editor.rs index 2064d7cacef..4655455f394 100644 --- a/crates/gpui/examples/view_example/example_editor.rs +++ b/crates/gpui/examples/view_example/example_editor.rs @@ -349,14 +349,6 @@ struct EditorTextPrepaint { cursor: Option, } -impl IntoElement for EditorText { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl Element for EditorText { type RequestLayoutState = (); type PrepaintState = EditorTextPrepaint; diff --git a/crates/gpui/src/element.rs b/crates/gpui/src/element.rs index 8f980bd53a9..c9ec80acfa9 100644 --- a/crates/gpui/src/element.rs +++ b/crates/gpui/src/element.rs @@ -49,7 +49,7 @@ use std::{ /// Elements form a tree and are laid out according to web-based layout rules, as implemented by Taffy. /// You can create custom elements by implementing this trait, see the module-level documentation /// for more details. -pub trait Element: 'static + IntoElement { +pub trait Element: 'static + Sized { /// The type of state returned from [`Element::request_layout`]. A mutable reference to this state is subsequently /// provided to [`Element::prepaint`] and [`Element::paint`]. type RequestLayoutState: 'static; @@ -138,7 +138,15 @@ pub trait Element: 'static + IntoElement { /// Convert this element into a dynamically-typed [`AnyElement`]. fn into_any(self) -> AnyElement { - AnyElement::new(self) + AnyElement::new_please_call_into_any_to_avoid_double_box(self) + } +} + +impl IntoElement for T { + type Element = Self; + + fn into_element(self) -> Self::Element { + self } } @@ -650,7 +658,12 @@ where pub struct AnyElement(ArenaBox); impl AnyElement { - pub(crate) fn new(element: E) -> Self + /// Boxes `element` into an `AnyElement`, erasing its concrete type. + /// + /// This always allocates and always adds a level of boxing, even when `element` is + /// already an [`AnyElement`], which would nest one `AnyElement` inside another. Call + /// [`Element::into_any`] instead; it skips the wrapper for `AnyElement` itself. + fn new_please_call_into_any_to_avoid_double_box(element: E) -> Self where E: 'static + Element, E::RequestLayoutState: Any, @@ -772,16 +785,8 @@ impl Element for AnyElement { ) { self.paint(window, cx); } -} -impl IntoElement for AnyElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } - - fn into_any_element(self) -> AnyElement { + fn into_any(self) -> AnyElement { self } } @@ -789,14 +794,6 @@ impl IntoElement for AnyElement { /// The empty element, which renders nothing. pub struct Empty; -impl IntoElement for Empty { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl Element for Empty { type RequestLayoutState = (); type PrepaintState = (); diff --git a/crates/gpui/src/elements/anchored.rs b/crates/gpui/src/elements/anchored.rs index 12f3f086c14..63a07b03b76 100644 --- a/crates/gpui/src/elements/anchored.rs +++ b/crates/gpui/src/elements/anchored.rs @@ -4,8 +4,8 @@ use smallvec::SmallVec; use crate::{ Anchor, AnyElement, App, Axis, Bounds, Display, Edges, Element, GlobalElementId, - InspectorElementId, IntoElement, LayoutId, ParentElement, Pixels, Point, Position, Size, Style, - Window, point, px, + InspectorElementId, LayoutId, ParentElement, Pixels, Point, Position, Size, Style, Window, + point, px, }; /// The state that the anchored element element uses to track its children. @@ -307,14 +307,6 @@ impl Element for Anchored { } } -impl IntoElement for Anchored { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - /// Which side of a box `anchor` is on along `axis`. `Less` is left or top, `Equal` is the /// center, and `Greater` is right or bottom. fn side_along(anchor: Anchor, axis: Axis) -> Ordering { diff --git a/crates/gpui/src/elements/animation.rs b/crates/gpui/src/elements/animation.rs index 70613f38c5a..33f7bc19fd6 100644 --- a/crates/gpui/src/elements/animation.rs +++ b/crates/gpui/src/elements/animation.rs @@ -196,14 +196,6 @@ impl SpringAnimationElement { } } -impl IntoElement for SpringAnimationElement { - type Element = SpringAnimationElement; - - fn into_element(self) -> Self::Element { - self - } -} - impl ParentElement for AnimationElement { fn extend(&mut self, elements: impl IntoIterator) { let Some(element) = &mut self.element else { @@ -223,14 +215,6 @@ impl AnimationElement { } } -impl IntoElement for AnimationElement { - type Element = AnimationElement; - - fn into_element(self) -> Self::Element { - self - } -} - struct AnimationState { start: Instant, animation_ix: usize, diff --git a/crates/gpui/src/elements/canvas.rs b/crates/gpui/src/elements/canvas.rs index d57d2f60416..8c06494f04b 100644 --- a/crates/gpui/src/elements/canvas.rs +++ b/crates/gpui/src/elements/canvas.rs @@ -1,8 +1,8 @@ use refineable::Refineable as _; use crate::{ - App, Bounds, Element, ElementId, GlobalElementId, InspectorElementId, IntoElement, Pixels, - Style, StyleRefinement, Styled, Window, + App, Bounds, Element, ElementId, GlobalElementId, InspectorElementId, Pixels, Style, + StyleRefinement, Styled, Window, }; /// Construct a canvas element with the given paint callback. @@ -26,14 +26,6 @@ pub struct Canvas { style: StyleRefinement, } -impl IntoElement for Canvas { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl Element for Canvas { type RequestLayoutState = Style; type PrepaintState = Option; diff --git a/crates/gpui/src/elements/container_query.rs b/crates/gpui/src/elements/container_query.rs index 0363ce69008..e4e1ed8b21e 100644 --- a/crates/gpui/src/elements/container_query.rs +++ b/crates/gpui/src/elements/container_query.rs @@ -111,14 +111,6 @@ impl Element for ContainerQuery { } } -impl IntoElement for ContainerQuery { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl Styled for ContainerQuery { fn style(&mut self) -> &mut StyleRefinement { &mut self.style diff --git a/crates/gpui/src/elements/deferred.rs b/crates/gpui/src/elements/deferred.rs index 3496268a532..f54056159f6 100644 --- a/crates/gpui/src/elements/deferred.rs +++ b/crates/gpui/src/elements/deferred.rs @@ -78,14 +78,6 @@ impl Element for Deferred { } } -impl IntoElement for Deferred { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl Deferred { /// Sets a priority for the element. A higher priority conceptually means painting the element /// on top of deferred draws with a lower priority (i.e. closer to the viewer). diff --git a/crates/gpui/src/elements/div.rs b/crates/gpui/src/elements/div.rs index f28f091739d..ce038047780 100644 --- a/crates/gpui/src/elements/div.rs +++ b/crates/gpui/src/elements/div.rs @@ -19,12 +19,12 @@ use crate::{ Action, AnyDrag, AnyElement, AnyTooltip, AnyView, App, BackGestureEvent, Bounds, ClickEvent, DispatchPhase, Display, Element, ElementId, Entity, EntityId, ExternalDragPayload, ExternalDragPayloadSource, FileDropEvent, FocusHandle, Global, GlobalElementId, Hitbox, - HitboxBehavior, HitboxId, InspectorElementId, IntoElement, IsZero, KeyContext, KeyDownEvent, - KeyUpEvent, KeyboardButton, KeyboardClickEvent, LayoutId, LongPressEvent, - ModifiersChangedEvent, MouseButton, MouseClickEvent, MouseDownEvent, MouseExitEvent, - MouseMoveEvent, MousePressureEvent, MouseUpEvent, OngoingScroll, Overflow, ParentElement, - PinchEvent, Pixels, Point, Render, ScrollEvent, SharedString, Size, Style, StyleRefinement, - Styled, Task, TooltipId, TouchPhase, Visibility, Window, WindowControlArea, point, px, size, + HitboxBehavior, HitboxId, InspectorElementId, IsZero, KeyContext, KeyDownEvent, KeyUpEvent, + KeyboardButton, KeyboardClickEvent, LayoutId, LongPressEvent, ModifiersChangedEvent, + MouseButton, MouseClickEvent, MouseDownEvent, MouseExitEvent, MouseMoveEvent, + MousePressureEvent, MouseUpEvent, OngoingScroll, Overflow, ParentElement, PinchEvent, Pixels, + Point, Render, ScrollEvent, SharedString, Size, Style, StyleRefinement, Styled, Task, + TooltipId, TouchPhase, Visibility, Window, WindowControlArea, point, px, size, }; use collections::HashMap; use gpui_util::ResultExt; @@ -2196,14 +2196,6 @@ impl Element for Div { } } -impl IntoElement for Div { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - #[derive(Default)] pub(crate) struct AriaProperties { pub(crate) author_id: Option, @@ -4282,17 +4274,6 @@ where } } -impl IntoElement for Stateful -where - E: Element, -{ - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl ParentElement for Stateful where E: ParentElement, @@ -4555,8 +4536,9 @@ impl ScrollHandle { mod tests { use super::*; use crate::{ - AnyWindowHandle, AppContext as _, Context, GestureTuning, InputEvent, Keystroke, - MouseMoveEvent, TestAppContext, TouchEvent, TouchId, canvas, util::FluentBuilder as _, + AnyWindowHandle, AppContext as _, Context, GestureTuning, InputEvent, IntoElement, + Keystroke, MouseMoveEvent, TestAppContext, TouchEvent, TouchId, canvas, + util::FluentBuilder as _, }; use std::{cell::Cell, rc::Weak}; @@ -4900,14 +4882,6 @@ mod tests { captured_active_tooltip: CapturedActiveTooltip, } - impl IntoElement for TooltipCaptureElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } - } - impl Element for TooltipCaptureElement { type RequestLayoutState = (); type PrepaintState = (); diff --git a/crates/gpui/src/elements/image_cache.rs b/crates/gpui/src/elements/image_cache.rs index 1920944299b..3d9d4ce6113 100644 --- a/crates/gpui/src/elements/image_cache.rs +++ b/crates/gpui/src/elements/image_cache.rs @@ -1,6 +1,6 @@ use crate::{ AnyElement, AnyEntity, App, AppContext, Asset, AssetLogger, Bounds, Element, ElementId, Entity, - GlobalElementId, ImageAssetLoader, ImageCacheError, InspectorElementId, IntoElement, LayoutId, + GlobalElementId, ImageAssetLoader, ImageCacheError, InspectorElementId, LayoutId, ParentElement, Pixels, RenderImage, Resource, Style, StyleRefinement, Styled, Window, hash, }; @@ -86,14 +86,6 @@ impl Styled for ImageCacheElement { } } -impl IntoElement for ImageCacheElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl Element for ImageCacheElement { type RequestLayoutState = SmallVec<[LayoutId; 4]>; type PrepaintState = (); diff --git a/crates/gpui/src/elements/img.rs b/crates/gpui/src/elements/img.rs index a9878f4f70c..6cc5db89ab0 100644 --- a/crates/gpui/src/elements/img.rs +++ b/crates/gpui/src/elements/img.rs @@ -1,9 +1,9 @@ use crate::{ AnyElement, AnyImageCache, App, Asset, AssetLogger, Bounds, DefiniteLength, Element, ElementId, Entity, GlobalElementId, Hitbox, Image, ImageCache, InspectorElementId, InteractiveElement, - Interactivity, IntoElement, LayoutId, Length, ObjectFit, Pixels, RenderImage, Resource, - SharedString, SharedUri, StyleRefinement, Styled, Task, Window, decode_gif_image, - decode_static_image, decode_webp_image, px, + Interactivity, LayoutId, Length, ObjectFit, Pixels, RenderImage, Resource, SharedString, + SharedUri, StyleRefinement, Styled, Task, Window, decode_gif_image, decode_static_image, + decode_webp_image, px, }; use anyhow::Result; @@ -518,14 +518,6 @@ impl InteractiveElement for Img { } } -impl IntoElement for Img { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl StatefulInteractiveElement for Img {} impl ImageSource { @@ -736,7 +728,7 @@ impl From for ImageCacheError { #[cfg(test)] mod tests { use super::*; - use crate::{ParentElement as _, TestAppContext, canvas, div, point, px, size}; + use crate::{IntoElement, ParentElement as _, TestAppContext, canvas, div, point, px, size}; use image::{Frame, ImageBuffer, Rgba}; use smallvec::SmallVec; diff --git a/crates/gpui/src/elements/list.rs b/crates/gpui/src/elements/list.rs index 7fc9b28696b..a63c4d630df 100644 --- a/crates/gpui/src/elements/list.rs +++ b/crates/gpui/src/elements/list.rs @@ -10,8 +10,8 @@ use crate::{ Along as _, AnyElement, App, AvailableSpace, Axis, Bounds, ContentMask, DispatchPhase, Edges, Element, EntityId, FocusHandle, GlobalElementId, Hitbox, HitboxBehavior, InspectorElementId, - IntoElement, Overflow, Pixels, Point, ScrollDelta, ScrollEvent, Size, Style, StyleRefinement, - Styled, Window, point, px, size, + Overflow, Pixels, Point, ScrollDelta, ScrollEvent, Size, Style, StyleRefinement, Styled, + Window, point, px, size, }; use collections::VecDeque; use refineable::Refineable as _; @@ -1659,14 +1659,6 @@ fn content_insets(style: &Style, size: Size, rem_size: Pixels) -> Edges< padding + border } -impl IntoElement for List { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl Styled for List { fn style(&mut self) -> &mut StyleRefinement { &mut self.style diff --git a/crates/gpui/src/elements/surface.rs b/crates/gpui/src/elements/surface.rs index acd29329109..043315f90d5 100644 --- a/crates/gpui/src/elements/surface.rs +++ b/crates/gpui/src/elements/surface.rs @@ -1,6 +1,6 @@ use crate::{ - App, Bounds, Element, ElementId, GlobalElementId, InspectorElementId, IntoElement, LayoutId, - ObjectFit, Pixels, Style, StyleRefinement, Styled, Window, + App, Bounds, Element, ElementId, GlobalElementId, InspectorElementId, LayoutId, ObjectFit, + Pixels, Style, StyleRefinement, Styled, Window, }; #[cfg(any(target_os = "macos", target_os = "ios"))] use objc2_core_foundation::CFRetained; @@ -119,14 +119,6 @@ impl Element for Surface { } } -impl IntoElement for Surface { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl Styled for Surface { fn style(&mut self) -> &mut StyleRefinement { &mut self.style diff --git a/crates/gpui/src/elements/svg.rs b/crates/gpui/src/elements/svg.rs index 176072f1c88..e87f0da63ca 100644 --- a/crates/gpui/src/elements/svg.rs +++ b/crates/gpui/src/elements/svg.rs @@ -7,8 +7,8 @@ use std::{ use crate::{ App, Asset, Bounds, Element, GlobalElementId, Hitbox, InspectorElementId, InteractiveElement, - Interactivity, IntoElement, LayoutId, Pixels, Point, Radians, SharedString, Size, - StyleRefinement, Styled, TransformationMatrix, Window, point, px, radians, size, + Interactivity, LayoutId, Pixels, Point, Radians, SharedString, Size, StyleRefinement, Styled, + TransformationMatrix, Window, point, px, radians, size, }; use gpui_util::ResultExt; @@ -189,14 +189,6 @@ impl Element for Svg { } } -impl IntoElement for Svg { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl Styled for Svg { fn style(&mut self) -> &mut StyleRefinement { &mut self.interactivity.base_style diff --git a/crates/gpui/src/elements/text.rs b/crates/gpui/src/elements/text.rs index 5d0c4292964..096e3040f22 100644 --- a/crates/gpui/src/elements/text.rs +++ b/crates/gpui/src/elements/text.rs @@ -166,14 +166,6 @@ macro_rules! text { }}; } -impl IntoElement for Text { - type Element = Self; - #[inline] - fn into_element(self) -> Self::Element { - self - } -} - impl Element for Text { type RequestLayoutState = TextLayout; type PrepaintState = (); @@ -301,14 +293,6 @@ impl Element for &'static str { } } -impl IntoElement for &'static str { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl IntoElement for String { type Element = SharedString; @@ -375,14 +359,6 @@ impl Element for SharedString { } } -impl IntoElement for SharedString { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - /// Renders text with runs of different styles. /// /// Callers are responsible for setting the correct style for each run. @@ -601,14 +577,6 @@ impl Element for StyledText { } } -impl IntoElement for StyledText { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - /// The Layout for TextElement. This can be used to map indices to pixels and vice versa. #[derive(Default, Clone)] pub struct TextLayout(Rc>>); @@ -1405,14 +1373,6 @@ impl Element for InteractiveText { } } -impl IntoElement for InteractiveText { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/gpui/src/elements/uniform_list.rs b/crates/gpui/src/elements/uniform_list.rs index f07b03af677..e1967b07604 100644 --- a/crates/gpui/src/elements/uniform_list.rs +++ b/crates/gpui/src/elements/uniform_list.rs @@ -571,14 +571,6 @@ impl Element for UniformList { } } -impl IntoElement for UniformList { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - /// A decoration for a [`UniformList`]. This can be used for various things, /// such as rendering indent guides, or other visual effects. pub trait UniformListDecoration { diff --git a/crates/gpui/src/key_dispatch.rs b/crates/gpui/src/key_dispatch.rs index e4bce617277..764f31f7d4f 100644 --- a/crates/gpui/src/key_dispatch.rs +++ b/crates/gpui/src/key_dispatch.rs @@ -736,14 +736,6 @@ mod tests { } } - impl IntoElement for PendingTextInputTestView { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } - } - impl InputHandler for PendingTextInputTestView { fn accepts_text_input(&mut self, _: &mut Window, _: &mut App) -> bool { self.accepts_text_input.get() @@ -1214,14 +1206,6 @@ mod tests { } } - impl IntoElement for CustomElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } - } - impl InputHandler for CustomElement { fn selected_text_range( &mut self, diff --git a/crates/gpui/src/view.rs b/crates/gpui/src/view.rs index 37418510d9c..733373aac18 100644 --- a/crates/gpui/src/view.rs +++ b/crates/gpui/src/view.rs @@ -312,14 +312,6 @@ impl ViewElement { } } -impl IntoElement for ViewElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - struct ViewElementState { prepaint_range: Range, paint_range: Range, diff --git a/crates/gpui_macos/src/pasteboard.rs b/crates/gpui_macos/src/pasteboard.rs index 23ac6a0e763..e9565b7b0da 100644 --- a/crates/gpui_macos/src/pasteboard.rs +++ b/crates/gpui_macos/src/pasteboard.rs @@ -1,7 +1,7 @@ use std::ffi::CStr; use std::path::PathBuf; -use objc2::{Message, rc::Retained}; +use objc2::{Message, class, msg_send, rc::Retained}; #[expect( deprecated, reason = "Preserve the existing file-copy pasteboard format" @@ -28,14 +28,16 @@ pub struct Pasteboard { } impl Pasteboard { - pub fn general() -> Self { - Self::new(NSPasteboard::generalPasteboard()) + pub fn general() -> Option { + let pasteboard: Option> = + unsafe { msg_send![class!(NSPasteboard), generalPasteboard] }; + pasteboard.map(Self::new) } - pub fn find() -> Self { - Self::new(NSPasteboard::pasteboardWithName(unsafe { - NSPasteboardNameFind - })) + pub fn find() -> Option { + let pasteboard: Option> = + unsafe { msg_send![class!(NSPasteboard), pasteboardWithName: NSPasteboardNameFind] }; + pasteboard.map(Self::new) } #[cfg(test)] diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rs index f22510f8ebd..7d02fcbcba6 100644 --- a/crates/gpui_macos/src/platform.rs +++ b/crates/gpui_macos/src/platform.rs @@ -171,8 +171,8 @@ pub(crate) struct MacPlatformState { headless: bool, activation_policy: ActivationPolicy, application_created: bool, - general_pasteboard: Pasteboard, - find_pasteboard: Pasteboard, + general_pasteboard: Option, + find_pasteboard: Option, reopen: Option>, on_keyboard_layout_change: Option>, thermal_observer: Option, @@ -1205,22 +1205,26 @@ impl Platform for MacPlatform { fn read_from_clipboard(&self) -> Option { let state = self.0.lock(); - state.general_pasteboard.read() + state.general_pasteboard.as_ref()?.read() } fn write_to_clipboard(&self, item: ClipboardItem) { let state = self.0.lock(); - state.general_pasteboard.write(item); + if let Some(pasteboard) = &state.general_pasteboard { + pasteboard.write(item); + } } fn read_from_find_pasteboard(&self) -> Option { let state = self.0.lock(); - state.find_pasteboard.read() + state.find_pasteboard.as_ref()?.read() } fn write_to_find_pasteboard(&self, item: ClipboardItem) { let state = self.0.lock(); - state.find_pasteboard.write(item); + if let Some(pasteboard) = &state.find_pasteboard { + pasteboard.write(item); + } } fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task> { diff --git a/crates/image_viewer/src/image_viewer.rs b/crates/image_viewer/src/image_viewer.rs index 95109499db3..b757c46aa10 100644 --- a/crates/image_viewer/src/image_viewer.rs +++ b/crates/image_viewer/src/image_viewer.rs @@ -367,14 +367,6 @@ impl ImageContentElement { } } -impl IntoElement for ImageContentElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl Element for ImageContentElement { type RequestLayoutState = (); type PrepaintState = Option<(AnyElement, bool)>; diff --git a/crates/language_tools/src/key_context_view.rs b/crates/language_tools/src/key_context_view.rs index 9eb4d4c7493..612704a485a 100644 --- a/crates/language_tools/src/key_context_view.rs +++ b/crates/language_tools/src/key_context_view.rs @@ -1,10 +1,11 @@ use gpui::{ Action, App, AppContext as _, Entity, EventEmitter, FocusHandle, Focusable, - KeyBindingContextPredicate, KeyContext, Keystroke, MouseButton, Render, Subscription, Task, + KeyBindingContextPredicate, KeyContext, Keystroke, MouseButton, Render, ScrollHandle, + Subscription, Task, }; use itertools::Itertools; use serde_json::json; -use ui::{Button, ButtonStyle}; +use ui::{Button, ButtonStyle, ScrollAxes, Scrollbars, WithScrollbar}; use ui::{ ButtonCommon, Clickable, Context, FluentBuilder, InteractiveElement, Label, LabelCommon, LabelSize, ParentElement, SharedString, StatefulInteractiveElement, Styled, Window, div, @@ -34,6 +35,7 @@ struct KeyContextView { last_possibilities: Vec<(SharedString, SharedString, Option)>, context_stack: Vec, focus_handle: FocusHandle, + scroll_handle: ScrollHandle, _subscriptions: [Subscription; 2], } @@ -101,6 +103,7 @@ impl KeyContextView { }); Self { + scroll_handle: ScrollHandle::new(), context_stack: Vec::new(), pending_keystrokes: None, last_keystrokes: None, @@ -168,10 +171,10 @@ impl Item for KeyContextView { } impl Render for KeyContextView { - fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl ui::IntoElement { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl ui::IntoElement { use itertools::Itertools; - let key_equivalents = cx.keyboard_mapper().get_key_equivalents(); + let key_equivalents = cx.keyboard_mapper().get_key_equivalents().cloned(); v_flex() .id("key-context-view") .overflow_scroll() @@ -261,22 +264,41 @@ impl Render for KeyContextView { }) .when_some(self.last_keystrokes.as_ref(), |el, keystrokes| { el.child(Label::new(format!("Typed: {}", keystrokes)).ml_4()) - .children( - self.last_possibilities - .iter() - .map(|(name, predicate, state)| { - let (text, color) = match state { - Some(true) => ("(match)", ui::Color::Success), - Some(false) => ("(low precedence)", ui::Color::Hint), - None => ("(no match)", ui::Color::Error), - }; - h_flex() - .gap_2() - .ml_8() - .child(div().min_w(px(200.)).child(Label::new(name.clone()))) - .child(Label::new(predicate.clone())) - .child(Label::new(text).color(color)) - }), + .child( + div() + .w_full() + .pr_4() + .child( + v_flex() + .id("key-context-possibilities") + .track_scroll(&self.scroll_handle) + .pb_4() + .pl_8() + .overflow_x_scroll() + .items_start() + .children( + self.last_possibilities + .iter() + .map(|(name, predicate, state)| { + let (text, color) = match state { + Some(true) => ("(match)", ui::Color::Success), + Some(false) => ("(low precedence)", ui::Color::Hint), + None => ("(no match)", ui::Color::Error), + }; + h_flex() + .gap_2() + .child(div().min_w(px(200.)).flex_shrink_0().child(Label::new(name.clone()).single_line())) + .child(Label::new(predicate.clone()).single_line().flex_shrink_0()) + .child(Label::new(text).color(color).single_line().flex_shrink_0()) + }), + ) + ) + .custom_scrollbars( + Scrollbars::new(ScrollAxes::Horizontal) + .tracked_scroll_handle(&self.scroll_handle), + window, + cx, + ) ) }) .when_some(key_equivalents, |el, key_equivalents| { diff --git a/crates/markdown/src/markdown.rs b/crates/markdown/src/markdown.rs index 1cecbdc0fdd..7335744ddbd 100644 --- a/crates/markdown/src/markdown.rs +++ b/crates/markdown/src/markdown.rs @@ -1566,6 +1566,36 @@ impl ParsedMarkdown { &self.root_block_starts } + /// The source offset of the first block that renders anything. Leading blank lines and + /// HTML blocks that render nothing (such as a comment) come before it, so this is the + /// block that sits at the top of the rendered markdown. + fn first_rendered_block_start(&self) -> usize { + let mut in_empty_html_block = false; + for (range, event) in self.events.iter() { + match event { + MarkdownEvent::RootStart | MarkdownEvent::RootEnd(_) => {} + MarkdownEvent::Start(MarkdownTag::HtmlBlock) => { + in_empty_html_block = match self.html_blocks.get(&range.start) { + Some(block) => block.children.is_empty(), + None => { + let html = self.source[range.clone()].trim(); + html.starts_with("") + } + }; + if !in_empty_html_block { + return range.start; + } + } + MarkdownEvent::End(MarkdownTagEnd::HtmlBlock) if in_empty_html_block => { + in_empty_html_block = false; + } + _ if in_empty_html_block => {} + _ => return range.start, + } + } + 0 + } + fn non_rendered_source_ranges(&self) -> Vec> { let mut ranges = Vec::new(); let mut active_link = None; @@ -2686,6 +2716,7 @@ impl Element for MarkdownElement { self.style.base_text_style.clone(), self.style.syntax.clone(), highlights, + parsed_markdown.first_rendered_block_start(), ); let markdown_end = if let Some(last) = parsed_markdown.events.last() { last.0.end @@ -3671,14 +3702,6 @@ fn render_copy_code_block_button( }) } -impl IntoElement for MarkdownElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - pub enum AnyDiv { Div(Div), Stateful(Stateful
), @@ -3826,6 +3849,8 @@ struct MarkdownElementBuilder { rendered_image_links: Vec, rendered_footnote_refs: Vec, current_source_index: usize, + /// The source offset of the first rendered block, whose top margin is removed. + first_block_start: usize, html_comment: bool, rendered_footnote_separator: bool, base_text_style: TextStyle, @@ -3932,6 +3957,7 @@ impl MarkdownElementBuilder { base_text_style: TextStyle, syntax_theme: Arc, highlights: MarkdownHighlights, + first_block_start: usize, ) -> Self { Self { div_stack: vec![{ @@ -3945,6 +3971,7 @@ impl MarkdownElementBuilder { rendered_image_links: Vec::new(), rendered_footnote_refs: Vec::new(), current_source_index: 0, + first_block_start, html_comment: false, rendered_footnote_separator: false, base_text_style, @@ -3996,7 +4023,7 @@ impl MarkdownElementBuilder { let mut div = div.into(); self.flush_text(); - if range.start == 0 { + if range.start == self.first_block_start { // Remove the top margin on the first element. div.style().refine(&StyleRefinement { margin: gpui::EdgesRefinement { @@ -4468,14 +4495,6 @@ impl Element for RenderedLineElement { } } -impl IntoElement for RenderedLineElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - struct RenderedLine { layout: TextLayout, visible_bounds: Cell>>, @@ -6859,6 +6878,38 @@ mod tests { } } + #[gpui::test] + fn test_first_rendered_block_has_no_top_margin(cx: &mut TestAppContext) { + let mut heading_top = |source: &'static str| { + let mut cx = render_image_layout(source, cx); + let selectors = image_selectors(source); + let [image] = selectors.as_slice() else { + panic!("expected one image, found {}", selectors.len()); + }; + cx.debug_bounds(image) + .expect("image should be rendered") + .top() + }; + + // Leading blank lines and comments render nothing, so the heading after them is the + // first rendered block. Its top margin would otherwise collapse through the empty + // blocks before it and push everything below it down. + let expected = heading_top("# ![](icon.png)"); + for source in [ + "\n# ![](icon.png)", + "\n\n# ![](icon.png)", + "\n\n# ![](icon.png)", + "\n\n\n# ![](icon.png)", + "[zed]: https://zed.dev\n\n# ![](icon.png)", + ] { + assert_eq!( + heading_top(source), + expected, + "heading in {source:?} should sit at the top like it does without the leading content" + ); + } + } + #[test] fn test_collect_image_alt_text() { let alt_text = |markdown: &str| { @@ -8637,14 +8688,6 @@ mod tests { rendered_text: Rc>>, } - impl IntoElement for CapturingMarkdownElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } - } - impl Element for CapturingMarkdownElement { type RequestLayoutState = RenderedMarkdown; type PrepaintState = Hitbox; diff --git a/crates/open_path_prompt/Cargo.toml b/crates/open_path_prompt/Cargo.toml index 55e143de895..1ef3b06740f 100644 --- a/crates/open_path_prompt/Cargo.toml +++ b/crates/open_path_prompt/Cargo.toml @@ -10,6 +10,7 @@ file_icons.workspace = true futures.workspace = true fuzzy.workspace = true gpui.workspace = true +menu.workspace = true picker.workspace = true project.workspace = true serde.workspace = true diff --git a/crates/open_path_prompt/src/open_path_prompt.rs b/crates/open_path_prompt/src/open_path_prompt.rs index 3a46504b74d..1e511419b7c 100644 --- a/crates/open_path_prompt/src/open_path_prompt.rs +++ b/crates/open_path_prompt/src/open_path_prompt.rs @@ -7,7 +7,7 @@ use file_finder_settings::FileFinderSettings; use file_icons::FileIcons; use futures::channel::oneshot; use fuzzy::{CharBag, StringMatch, StringMatchCandidate}; -use gpui::{HighlightStyle, StyledText, Task}; +use gpui::{Action, HighlightStyle, StyledText, Task}; use picker::{Picker, PickerDelegate}; use project::{DirectoryItem, DirectoryLister}; use settings::SettingsStore; @@ -19,18 +19,19 @@ use std::{ atomic::{self, AtomicBool}, }, }; -use ui::{Context, LabelLike, ListItem, Window}; +use ui::{Context, KeyBinding, LabelLike, ListItem, Window}; use ui::{HighlightedLabel, ListItemSpacing, prelude::*}; use util::{ maybe, paths::{PathStyle, compare_paths}, }; -use workspace::Workspace; +use workspace::{OpenPathPromptMode, OpenPathPromptResult, Workspace}; pub struct OpenPathPrompt; pub struct OpenPathDelegate { - tx: Option>>>, + on_confirm: Option)>>, + mode: OpenPathPromptMode, lister: DirectoryLister, selected_index: usize, directory_state: DirectoryState, @@ -53,31 +54,15 @@ impl OpenPathDelegate { creating_path: bool, cx: &App, ) -> Self { - let path_style = lister.path_style(cx); - let sort_mode = cx - .try_global::() - .and_then(|store| store.merged_settings().project_panel.as_ref()?.sort_mode) - .unwrap_or_default(); - Self { - tx: Some(tx), + Self::with_confirmation( + Box::new(move |result| { + tx.send(result.map(|result| result.paths)).ok(); + }), lister, - selected_index: 0, - directory_state: DirectoryState::None { - create: creating_path, - }, - string_matches: Vec::new(), - cancel_flag: Arc::new(AtomicBool::new(false)), - should_dismiss: true, - prompt_root: match path_style { - PathStyle::Unix => "/".to_string(), - PathStyle::Windows => "C:\\".to_string(), - }, - path_style, - replace_prompt: Task::ready(()), - render_footer: Arc::new(|_, _| None), - hidden_entries: false, - sort_mode, - } + creating_path, + OpenPathPromptMode::SelectPath, + cx, + ) } pub fn with_footer( @@ -157,6 +142,92 @@ impl OpenPathDelegate { } } + fn for_open( + tx: oneshot::Sender>, + lister: DirectoryLister, + mode: OpenPathPromptMode, + cx: &App, + ) -> Self { + let delegate = Self::with_confirmation( + Box::new(move |result| { + tx.send(result).ok(); + }), + lister, + false, + mode, + cx, + ); + if mode == OpenPathPromptMode::SelectPath { + return delegate; + } + delegate.with_footer(Arc::new(move |_, cx| { + let (primary_label, secondary_label) = if mode == OpenPathPromptMode::NewWindow { + ("New Window", "This Window") + } else { + ("This Window", "New Window") + }; + Some( + h_flex() + .flex_1() + .p_1p5() + .gap_1() + .justify_end() + .border_t_1() + .border_color(cx.theme().colors().border_variant) + .child( + Button::new("open_secondary", secondary_label) + .key_binding(KeyBinding::for_action(&menu::SecondaryConfirm, cx)) + .on_click(|_, window, cx| { + window.dispatch_action(menu::SecondaryConfirm.boxed_clone(), cx) + }), + ) + .child( + Button::new("open_primary", primary_label) + .key_binding(KeyBinding::for_action(&menu::Confirm, cx)) + .on_click(|_, window, cx| { + window.dispatch_action(menu::Confirm.boxed_clone(), cx) + }), + ) + .into_any_element(), + ) + })) + } + + fn with_confirmation( + on_confirm: Box)>, + lister: DirectoryLister, + creating_path: bool, + mode: OpenPathPromptMode, + cx: &App, + ) -> Self { + let path_style = lister.path_style(cx); + let sort_mode = cx + .try_global::() + .and_then(|store| store.merged_settings().project_panel.as_ref()?.sort_mode) + .unwrap_or_default(); + Self { + on_confirm: Some(on_confirm), + mode, + lister, + selected_index: 0, + directory_state: DirectoryState::None { + create: creating_path, + }, + string_matches: Vec::new(), + cancel_flag: Arc::new(AtomicBool::new(false)), + should_dismiss: true, + prompt_root: match path_style { + PathStyle::Unix => "/".to_string(), + PathStyle::Windows => "C:\\".to_string(), + }, + path_style, + replace_prompt: Task::ready(()), + render_footer: Arc::new(|_, _| None), + hidden_entries: false, + sort_mode, + } + } + fn current_dir(&self) -> &'static str { match self.path_style { PathStyle::Unix => "./", @@ -201,9 +272,10 @@ impl OpenPathPrompt { _window: Option<&mut Window>, _: &mut Context, ) { - workspace.set_prompt_for_open_path(Box::new(|workspace, lister, window, cx| { - let (tx, rx) = futures::channel::oneshot::channel(); - Self::prompt_for_open_path(workspace, lister, false, None, tx, window, cx); + workspace.set_prompt_for_open_path(Box::new(|workspace, lister, mode, window, cx| { + let (tx, rx) = oneshot::channel(); + let delegate = OpenPathDelegate::for_open(tx, lister, mode, cx); + Self::prompt_for_path(workspace, delegate, None, window, cx); rx })); } @@ -215,27 +287,24 @@ impl OpenPathPrompt { ) { workspace.set_prompt_for_new_path(Box::new( |workspace, lister, suggested_name, window, cx| { - let (tx, rx) = futures::channel::oneshot::channel(); - Self::prompt_for_new_path(workspace, lister, suggested_name, tx, window, cx); + let (tx, rx) = oneshot::channel(); + let delegate = OpenPathDelegate::new(tx, lister, true, cx); + Self::prompt_for_path(workspace, delegate, suggested_name, window, cx); rx }, )); } - fn prompt_for_open_path( + fn prompt_for_path( workspace: &mut Workspace, - lister: DirectoryLister, - creating_path: bool, + delegate: OpenPathDelegate, suggested_name: Option, - tx: oneshot::Sender>>, window: &mut Window, cx: &mut Context, ) { workspace.toggle_modal(window, cx, |window, cx| { - let delegate = - OpenPathDelegate::new(tx, lister.clone(), creating_path, cx).show_hidden(); - let picker = Picker::uniform_list(delegate, window, cx); - let mut query = lister.default_query(cx); + let mut query = delegate.lister.default_query(cx); + let picker = Picker::uniform_list(delegate.show_hidden(), window, cx); if let Some(suggested_name) = suggested_name { query.push_str(&suggested_name); } @@ -243,17 +312,6 @@ impl OpenPathPrompt { picker }); } - - fn prompt_for_new_path( - workspace: &mut Workspace, - lister: DirectoryLister, - suggested_name: Option, - tx: oneshot::Sender>>, - window: &mut Window, - cx: &mut Context, - ) { - Self::prompt_for_open_path(workspace, lister, true, suggested_name, tx, window, cx); - } } impl PickerDelegate for OpenPathDelegate { @@ -659,10 +717,15 @@ impl PickerDelegate for OpenPathDelegate { ) } - fn confirm(&mut self, _: bool, window: &mut Window, cx: &mut Context>) { + fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context>) { let Some(candidate) = self.get_entry(self.selected_index) else { return; }; + let open_in_new_window = match self.mode { + OpenPathPromptMode::SelectPath => false, + OpenPathPromptMode::CurrentWindow => secondary, + OpenPathPromptMode::NewWindow => !secondary, + }; match &self.directory_state { DirectoryState::None { .. } => return, @@ -676,8 +739,11 @@ impl PickerDelegate for OpenPathDelegate { &candidate.path.string, )) }; - if let Some(tx) = self.tx.take() { - tx.send(Some(vec![confirmed_path])).ok(); + if let Some(on_confirm) = self.on_confirm.take() { + on_confirm(Some(OpenPathPromptResult { + paths: vec![confirmed_path], + open_in_new_window, + })); } } DirectoryState::Create { @@ -716,16 +782,22 @@ impl PickerDelegate for OpenPathDelegate { if answer != Some(0) { return; } - if let Some(tx) = picker.delegate.tx.take() { - tx.send(Some(vec![prompted_path])).ok(); + if let Some(on_confirm) = picker.delegate.on_confirm.take() { + on_confirm(Some(OpenPathPromptResult { + paths: vec![prompted_path], + open_in_new_window, + })); } cx.emit(gpui::DismissEvent); }) .ok(); }); return; - } else if let Some(tx) = self.tx.take() { - tx.send(Some(vec![prompted_path])).ok(); + } else if let Some(on_confirm) = self.on_confirm.take() { + on_confirm(Some(OpenPathPromptResult { + paths: vec![prompted_path], + open_in_new_window, + })); } } }, @@ -740,8 +812,8 @@ impl PickerDelegate for OpenPathDelegate { fn dismissed(&mut self, _: &mut Window, cx: &mut Context>) { self.cancel_flag.store(true, atomic::Ordering::Release); - if let Some(tx) = self.tx.take() { - tx.send(None).ok(); + if let Some(on_confirm) = self.on_confirm.take() { + on_confirm(None); } cx.emit(gpui::DismissEvent) } diff --git a/crates/open_path_prompt/src/open_path_prompt_tests.rs b/crates/open_path_prompt/src/open_path_prompt_tests.rs index 26e7dc638a6..fcbb560b399 100644 --- a/crates/open_path_prompt/src/open_path_prompt_tests.rs +++ b/crates/open_path_prompt/src/open_path_prompt_tests.rs @@ -1,14 +1,21 @@ -use std::sync::{Arc, atomic}; +use std::{ + path::PathBuf, + sync::{Arc, atomic}, +}; use fuzzy::{StringMatch, StringMatchCandidate}; -use gpui::{AppContext, Entity, TestAppContext, VisualTestContext}; +use gpui::{AppContext, Entity, KeyBinding, PathPromptOptions, TestAppContext, VisualTestContext}; use picker::{Picker, PickerDelegate}; -use project::Project; +use project::{DirectoryLister, DisableAiSettings, Project}; use serde_json::json; +use settings::{Settings, SettingsStore}; use util::path; -use workspace::{AppState, MultiWorkspace}; +use workspace::{ + AppState, MultiWorkspace, OpenOptions, OpenPathPromptMode, Workspace, item::test::TestItem, + prompt_for_open_path_and_open, +}; -use crate::{CandidateInfo, DirectoryState, OpenPathDelegate}; +use crate::{CandidateInfo, DirectoryState, OpenPathDelegate, OpenPathPrompt}; #[gpui::test] async fn test_open_path_prompt(cx: &mut TestAppContext) { @@ -398,7 +405,9 @@ async fn test_create_confirmation_keeps_the_checked_destination(cx: &mut TestApp let (tx, receiver) = futures::channel::oneshot::channel(); picker.update_in(cx, |picker, window, cx| { - picker.delegate.tx = Some(tx); + picker.delegate.on_confirm = Some(Box::new(move |result| { + tx.send(result.map(|result| result.paths)).ok(); + })); picker.delegate.confirm(false, window, cx); }); @@ -515,6 +524,283 @@ async fn test_dismiss_cancels_in_flight_match(cx: &mut TestAppContext) { ); } +#[gpui::test] +async fn test_open_path_prompt_initial_query_for_file_and_directory_roots(cx: &mut TestAppContext) { + let app_state = init_test(cx); + app_state + .fs + .as_fake() + .insert_tree( + path!("/"), + json!({ "root": { "first.txt": "" }, "root-file.txt": "" }), + ) + .await; + + for (root, expected_query) in [ + (path!("/root/first.txt"), path!("/root/")), + (path!("/root"), path!("/root/")), + (path!("/root-file.txt"), path!("/")), + (path!("/"), path!("/")), + ] { + let project = Project::test(app_state.fs.clone(), [root.as_ref()], cx).await; + assert_eq!( + cx.update(|cx| DirectoryLister::Project(project).default_query(cx)), + expected_query + ); + } +} + +#[gpui::test] +async fn test_open_file_selections_preserve_workspace_and_dirty_items(cx: &mut TestAppContext) { + let app_state = init_test(cx); + app_state + .fs + .as_fake() + .insert_tree( + path!("/"), + json!({ + "root": { + "first.txt": "first", + "second.txt": "second", + "third.txt": "third", + }, + "outside.txt": "outside", + }), + ) + .await; + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.workspace.use_system_path_prompts = Some(true); + }); + }); + + for (root, disable_ai) in [ + (path!("/root/first.txt"), false), + (path!("/root/first.txt"), true), + (path!("/root"), false), + (path!("/root"), true), + ] { + cx.update(|cx| DisableAiSettings::override_global(DisableAiSettings { disable_ai }, cx)); + let project = Project::test(app_state.fs.clone(), [root.as_ref()], cx).await; + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx)); + let workspace = multi_workspace.read_with(cx, |multi_workspace, cx| { + assert_eq!(multi_workspace.multi_workspace_enabled(cx), !disable_ai); + multi_workspace.workspace().clone() + }); + workspace + .update_in(cx, |workspace, window, cx| { + workspace.open_abs_path( + PathBuf::from(path!("/root/first.txt")), + OpenOptions::default(), + window, + cx, + ) + }) + .await + .unwrap(); + let dirty_item = cx.new(|cx| TestItem::new(cx).with_dirty(true)); + workspace.update_in(cx, |workspace, window, cx| { + workspace.add_item_to_active_pane(Box::new(dirty_item.clone()), None, true, window, cx); + }); + let window_count = cx.update(|_, cx| cx.windows().len()); + let mut expected_paths = vec![PathBuf::from(path!("/root/first.txt"))]; + + for selected_paths in [ + vec![PathBuf::from(path!("/root/second.txt"))], + vec![ + PathBuf::from(path!("/root/third.txt")), + PathBuf::from(path!("/outside.txt")), + ], + ] { + expected_paths.extend(selected_paths.iter().cloned()); + expected_paths.sort(); + prompt_and_select_paths(&workspace, selected_paths, false, cx); + + assert!(!cx.has_pending_prompt()); + assert_eq!(cx.update(|_, cx| cx.windows().len()), window_count); + multi_workspace.read_with(cx, |multi_workspace, _| { + assert_eq!(multi_workspace.workspace(), &workspace); + assert_eq!(multi_workspace.workspaces().count(), 1); + }); + workspace.read_with(cx, |workspace, cx| { + let mut paths = workspace.open_item_abs_paths(cx); + paths.sort(); + assert_eq!(paths, expected_paths); + assert_eq!( + workspace.root_paths(cx), + vec![Arc::::from(PathBuf::from(root))] + ); + + assert_eq!( + workspace.items_of_type::(cx).collect::>(), + vec![dirty_item.clone()] + ); + assert!(dirty_item.read(cx).is_dirty); + }); + } + } +} + +#[gpui::test] +async fn test_open_project_stays_in_window(cx: &mut TestAppContext) { + let app_state = init_test(cx); + app_state + .fs + .as_fake() + .insert_tree( + path!("/"), + json!({ "root": { "file.txt": "" }, "other": {} }), + ) + .await; + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.workspace.use_system_path_prompts = Some(true); + }); + }); + + for (mut paths, disable_ai) in [ + (vec![PathBuf::from(path!("/other"))], false), + ( + vec![ + PathBuf::from(path!("/other")), + PathBuf::from(path!("/root/file.txt")), + ], + false, + ), + (vec![PathBuf::from(path!("/other"))], true), + ] { + cx.update(|cx| DisableAiSettings::override_global(DisableAiSettings { disable_ai }, cx)); + let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await; + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx)); + let workspace = + multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone()); + let window_count = cx.update(|_, cx| cx.windows().len()); + prompt_and_select_paths(&workspace, paths.clone(), false, cx); + assert_eq!(cx.update(|_, cx| cx.windows().len()), window_count); + let opened_workspace = + multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone()); + assert_ne!(opened_workspace, workspace); + paths.sort(); + opened_workspace.read_with(cx, |workspace, cx| { + let mut roots = workspace + .root_paths(cx) + .iter() + .map(|path| path.to_path_buf()) + .collect::>(); + roots.sort(); + assert_eq!(roots, paths); + }); + prompt_and_select_paths(&opened_workspace, paths, false, cx); + multi_workspace.read_with(cx, |multi_workspace, _| { + assert_eq!(multi_workspace.workspace(), &opened_workspace); + }); + if disable_ai { + prompt_and_select_paths( + &opened_workspace, + vec![ + PathBuf::from(path!("/other")), + PathBuf::from(path!("/root/file.txt")), + ], + false, + cx, + ); + multi_workspace.read_with(cx, |multi_workspace, _| { + assert_eq!(multi_workspace.workspace(), &opened_workspace); + }); + } + } +} + +#[gpui::test] +async fn test_open_path_prompt_window_choices(cx: &mut TestAppContext) { + let app_state = init_test(cx); + cx.update(|cx| { + cx.bind_keys([ + KeyBinding::new("enter", menu::Confirm, None), + KeyBinding::new("ctrl-enter", menu::SecondaryConfirm, None), + KeyBinding::new("escape", menu::Cancel, None), + ]) + }); + app_state + .fs + .as_fake() + .insert_tree(path!("/root"), json!({ "file.txt": "" })) + .await; + let project = Project::test(app_state.fs.clone(), [], cx).await; + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx)); + let workspace = + multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone()); + workspace.update_in(cx, |workspace, window, cx| { + OpenPathPrompt::register(workspace, Some(window), cx) + }); + let mut expected_paths = Vec::new(); + + for (system_prompt, default_new_window, key, new_window) in [ + (false, false, "ctrl-enter", true), + (false, false, "enter", false), + (false, true, "enter", true), + (false, true, "ctrl-enter", false), + (false, false, "escape", false), + (true, false, "enter", false), + (true, true, "enter", true), + (true, false, "escape", false), + ] { + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.workspace.use_system_path_prompts = Some(system_prompt) + }); + }); + let window_count = cx.update(|_, cx| cx.windows().len()); + open_path_prompt(&workspace, default_new_window, cx); + if system_prompt { + cx.simulate_path_prompt_response(|options| { + assert_eq!( + options.prompt.as_deref(), + Some(if default_new_window { + "Open in New Window" + } else { + "Open in This Window" + }) + ); + (key != "escape").then(|| vec![PathBuf::from(path!("/root/file.txt"))]) + }); + } else { + let picker = workspace.read_with(cx, |workspace, cx| { + workspace + .active_modal::>(cx) + .unwrap() + }); + picker.update_in(cx, |picker, window, cx| { + assert!(picker.delegate.render_footer(window, cx).is_some()); + picker.set_query(path!("/root/file.txt"), window, cx); + }); + cx.simulate_keystrokes(key); + } + cx.run_until_parked(); + assert_eq!( + cx.update(|_, cx| cx.windows().len()), + window_count + usize::from(new_window) + ); + multi_workspace.read_with(cx, |multi_workspace, _| { + assert_eq!(multi_workspace.workspace(), &workspace) + }); + if key != "escape" && !new_window { + expected_paths = vec![PathBuf::from(path!("/root/file.txt"))]; + } + workspace.read_with(cx, |workspace, cx| { + assert_eq!(workspace.open_item_abs_paths(cx), expected_paths); + assert!( + workspace + .active_modal::>(cx) + .is_none() + ); + }); + } +} + fn init_test(cx: &mut TestAppContext) -> Arc { cx.update(|cx| { let state = AppState::test(cx); @@ -588,3 +874,42 @@ fn collect_match_candidates( ) -> Vec { picker.update(cx, |f, _| f.delegate.collect_match_candidates()) } + +fn prompt_and_select_paths( + workspace: &Entity, + paths: Vec, + create_new_window: bool, + cx: &mut VisualTestContext, +) { + open_path_prompt(workspace, create_new_window, cx); + cx.simulate_path_prompt_response(|_| Some(paths)); + cx.run_until_parked(); +} + +fn open_path_prompt( + workspace: &Entity, + create_new_window: bool, + cx: &mut VisualTestContext, +) { + workspace.update_in(cx, |workspace, window, cx| { + let app_state = workspace.app_state().clone(); + prompt_for_open_path_and_open( + workspace, + app_state, + PathPromptOptions { + files: true, + directories: true, + multiple: true, + prompt: None, + }, + if create_new_window { + OpenPathPromptMode::NewWindow + } else { + OpenPathPromptMode::CurrentWindow + }, + window, + cx, + ); + }); + cx.run_until_parked(); +} diff --git a/crates/picker/src/picker.rs b/crates/picker/src/picker.rs index 248a7970b0b..e96d8060b53 100644 --- a/crates/picker/src/picker.rs +++ b/crates/picker/src/picker.rs @@ -823,11 +823,7 @@ impl Picker { if let Some(action) = self.delegate.selected_index_changed(ix, window, cx) { action(window, cx); } - if let Some(preview) = &mut self.preview - && let Some(update) = self.delegate.try_get_preview_data_for_match(cx) - { - preview.update(update, window, cx); - } + self.update_preview(window, cx); } } @@ -892,11 +888,7 @@ impl Picker { if let Some(action) = self.delegate.selected_index_changed(ix, window, cx) { action(window, cx); } - if let Some(preview) = &mut self.preview - && let Some(update) = self.delegate.try_get_preview_data_for_match(cx) - { - preview.update(update, window, cx); - } + self.update_preview(window, cx); if scroll_to_index { self.scroll_to_item_index(ix); } @@ -1304,12 +1296,17 @@ impl Picker { }, } self.pending_update_matches = None; - if let Some(update) = self.delegate.try_get_preview_data_for_match(cx) - && let Some(preview) = &mut self.preview + self.update_preview(window, cx); + cx.notify(); + } + + fn update_preview(&mut self, window: &mut Window, cx: &mut Context) { + if let Some(preview) = &mut self.preview + && preview.layout != preview::Layout::Hidden + && let Some(update) = self.delegate.try_get_preview_data_for_match(cx) { preview.update(update, window, cx); } - cx.notify(); } pub fn query(&self, cx: &App) -> String { @@ -1612,7 +1609,7 @@ impl Picker { fn set_preview_layout( &mut self, layout: preview::Layout, - _window: &mut Window, + window: &mut Window, cx: &mut Context, ) { persistence::store_last_layout(D::name(), self.preview.as_ref().map(|_| layout), cx); @@ -1620,7 +1617,11 @@ impl Picker { let Some(preview) = &mut self.preview else { return; }; + let was_hidden = preview.layout == preview::Layout::Hidden; preview.layout = layout; + if was_hidden { + self.update_preview(window, cx); + } // Restore the size the user last left this layout at, or fall back to the // layout's default (simple when hidden, larger when a preview is shown). self.shape = persistence::try_load_shape(D::name(), layout, cx) @@ -1643,6 +1644,7 @@ mod tests { use super::*; use gpui::TestAppContext; use std::cell::Cell; + use std::sync::Mutex; struct TestDelegate { items: Vec, @@ -1783,6 +1785,14 @@ mod tests { fn dismissed(&mut self, _window: &mut Window, _cx: &mut Context>) {} + fn try_get_preview_data_for_match(&self, _cx: &App) -> Option { + let selected_index = self.selected_index; + Some(PreviewUpdate::message(HighlightedText { + text: SharedString::from(format!("Item {selected_index}")), + highlights: Vec::new(), + })) + } + fn render_match( &self, ix: usize, @@ -1925,6 +1935,33 @@ mod tests { }); } + #[gpui::test] + async fn test_hidden_preview_is_not_updated(cx: &mut TestAppContext) { + init_test(cx); + let updates = Arc::new(Mutex::new(Vec::new())); + let (picker, cx) = cx.add_window_view(|window, cx| { + Picker::uniform_list_with_preview( + TestDelegate::new(vec![true, true, true]), + Arc::new(TestPreview(updates.clone())), + window, + cx, + ) + }); + + picker.update_in(cx, |picker, window, cx| { + picker.set_selected_index(1, None, false, window, cx); + picker.set_preview_layout(preview::Layout::Right, window, cx); + picker.set_selected_index(2, None, false, window, cx); + picker.set_preview_layout(preview::Layout::Below, window, cx); + picker.set_preview_layout(preview::Layout::Hidden, window, cx); + picker.set_selected_index(0, None, false, window, cx); + }); + assert_eq!( + *updates.lock().unwrap(), + vec![SharedString::from("Item 1"), SharedString::from("Item 2")] + ); + } + #[gpui::test] async fn test_multi_select_mode_routes_clicks(cx: &mut TestAppContext) { init_test(cx); @@ -2057,6 +2094,24 @@ mod tests { ); }); } + + struct TestPreview(Arc>>); + + impl PreviewBackend for TestPreview { + fn update(&self, update: PreviewUpdate, _: &mut Window, _: &mut App) { + if let PreviewSource::Message(message) = update.source { + self.0.lock().unwrap().push(message.text); + } + } + + fn render(&self, _: PreviewLayout, _: &mut App) -> AnyElement { + div().into_any_element() + } + + fn adjust_to_new_size(&self, _: &mut Window, _: &mut App) {} + + fn clear(&self, _: &mut App) {} + } } impl EventEmitter for Picker {} diff --git a/crates/picker_preview/src/picker_preview.rs b/crates/picker_preview/src/picker_preview.rs index d46ff5bb797..c4bb0e7e7b2 100644 --- a/crates/picker_preview/src/picker_preview.rs +++ b/crates/picker_preview/src/picker_preview.rs @@ -8,7 +8,7 @@ use gpui::{ }; use language::{Bias, Buffer, HighlightedText, HighlightedTextBuilder, ToPoint}; use picker::{MatchLocation, PreviewBackend, PreviewLayout, PreviewSource, PreviewUpdate}; -use project::{Project, Symbol}; +use project::{Project, ProjectPath, Symbol, Worktree}; use rope::Point; use settings::Settings; use ui::{ActiveTheme, Color, div, prelude::*, v_flex}; @@ -59,6 +59,7 @@ struct SearchMatchLineHighlight; struct EditorPreview { project: Entity, current_path: Option>, + _worktree: Option>, /// When set show a text message instead of a preview message: Option, preview_editor: Entity, @@ -112,6 +113,7 @@ impl EditorPreview { project, preview_editor, current_path: None, + _worktree: None, message: None, single_row_highlight_anchor: None, pending_update: Task::ready(()), @@ -124,6 +126,7 @@ impl EditorPreview { fn clear(&mut self) { self.pending_update = Task::ready(()); self.single_row_highlight_anchor = None; + self._worktree = None; let mut message = HighlightedTextBuilder::default(); message.push_plain("No results to preview"); self.message = Some(message.build()); @@ -136,6 +139,9 @@ impl EditorPreview { source, match_location: highlight, } = update; + if !matches!(&source, PreviewSource::Path(_)) { + self._worktree = None; + } match source { PreviewSource::Path(abs_path) => { @@ -162,28 +168,44 @@ impl EditorPreview { window: &mut Window, cx: &mut Context, ) { - let open_task = self.project.update(cx, |project, cx| { - match project.project_path_for_absolute_path(&abs_path, cx) { - Some(project_path) => { - if let Some(buffer) = project.get_open_buffer(&project_path, cx) { - Task::ready(Ok(buffer)) - } else { - project.open_buffer(project_path, cx) - } - } - None => project.open_local_buffer(&abs_path, cx), - } + let worktree_task = self.project.update(cx, |project, cx| { + project.find_or_create_worktree(&abs_path, false, cx) }); - self.pending_update = cx.spawn_in(window, async move |this, cx| { - let Some(buffer) = open_task.await.log_err() else { - return; - }; - this.update_in(cx, |this, window, cx| { - this.update_from_buffer(buffer, highlight, window, cx); - cx.notify(); - }) - .ok(); + self.pending_update = cx.spawn_in(window, async move |preview, cx| { + let result = async { + let (worktree, path) = worktree_task.await?; + preview + .update(cx, |preview, cx| { + let project_path = ProjectPath { + worktree_id: worktree.read(cx).id(), + path, + }; + preview._worktree = Some(worktree); + preview.project.update(cx, |project, cx| { + if let Some(buffer) = project.get_open_buffer(&project_path, cx) { + Task::ready(Ok(buffer)) + } else { + project.open_buffer(project_path, cx) + } + }) + })? + .await + } + .await; + preview + .update_in(cx, |preview, window, cx| { + match result { + Ok(buffer) => preview.update_from_buffer(buffer, highlight, window, cx), + Err(error) => { + let mut message = HighlightedTextBuilder::default(); + message.push_plain(error.root_cause().to_string()); + preview.message = Some(message.build()); + } + } + cx.notify(); + }) + .ok(); }); } diff --git a/crates/project/src/git_store.rs b/crates/project/src/git_store.rs index 1d8bb4ece0b..9310d612d08 100644 --- a/crates/project/src/git_store.rs +++ b/crates/project/src/git_store.rs @@ -124,6 +124,11 @@ const MIN_PARKED_REPOSITORY_DEPTH: usize = 2; pub const MAX_CONCURRENT_OBJECT_READS: usize = 16; +/// Git matches every pathspec against every index entry, so the cost of a +/// scoped `git status`/`git diff` grows with the number of paths. On large +/// repositories a scan of the whole repository is cheaper than this many paths. +const MAX_SCOPED_STATUS_PATHS: usize = 64; + #[derive(Clone, Debug)] pub struct ParkedRepository { worktree_id: WorktreeId, @@ -5112,6 +5117,14 @@ impl GitStore { coalesced } + fn limit_repo_paths(paths: Vec) -> Vec { + if paths.len() > MAX_SCOPED_STATUS_PATHS { + vec![RepoPath::from_rel_path(RelPath::empty())] + } else { + paths + } + } + fn process_updated_entries( &self, worktree: &Entity, @@ -10434,14 +10447,15 @@ impl Repository { let changed_path_statuses = cx .background_spawn(async move { - let changed_paths = GitStore::coalesce_repo_paths( - changed_paths - .into_iter() - .flatten() - .collect::>() - .into_iter() - .collect(), - ); + let changed_paths = + GitStore::limit_repo_paths(GitStore::coalesce_repo_paths( + changed_paths + .into_iter() + .flatten() + .collect::>() + .into_iter() + .collect(), + )); let changed_paths_vec = changed_paths.iter().cloned().collect::>(); let status_task = backend.status(&changed_paths_vec); @@ -12950,6 +12964,19 @@ mod tests { assert_eq!(coalesced, repo_paths(&[""])); } + #[test] + fn limit_repo_paths_falls_back_to_root_above_threshold() { + let at_limit = (0..MAX_SCOPED_STATUS_PATHS) + .map(|index| repo_path(&format!("dir{index}/file.rs"))) + .collect::>(); + assert_eq!(GitStore::limit_repo_paths(at_limit.clone()), at_limit); + + let over_limit = (0..=MAX_SCOPED_STATUS_PATHS) + .map(|index| repo_path(&format!("dir{index}/file.rs"))) + .collect::>(); + assert_eq!(GitStore::limit_repo_paths(over_limit), repo_paths(&[""])); + } + #[test] fn coalesce_repo_paths_keeps_existing_ancestors() { let coalesced = GitStore::coalesce_repo_paths(repo_paths(&[ diff --git a/crates/project/src/project.rs b/crates/project/src/project.rs index 42a6bfe6168..17859117649 100644 --- a/crates/project/src/project.rs +++ b/crates/project/src/project.rs @@ -1128,11 +1128,22 @@ impl DirectoryLister { project .visible_worktrees(cx) .next() - .map(|worktree| worktree.read(cx).abs_path().to_string_lossy().into_owned()) + .map(|worktree| { + let worktree = worktree.read(cx); + let abs_path = worktree.abs_path(); + let directory = if worktree.root_entry().is_some_and(|entry| entry.is_file()) { + path_style.parent(&abs_path).unwrap_or(&abs_path) + } else { + &abs_path + }; + directory.to_string_lossy().into_owned() + }) .or_else(|| std::env::home_dir().map(|dir| dir.to_string_lossy().into_owned())) - .map(|mut s| { - s.push_str(path_style.primary_separator()); - s + .map(|mut query| { + if !query.ends_with(path_style.separators_ch()) { + query.push_str(path_style.primary_separator()); + } + query }) .unwrap_or_else(|| { if path_style.is_windows() { diff --git a/crates/recent_projects/src/recent_projects.rs b/crates/recent_projects/src/recent_projects.rs index 38df2653dd6..c3d1654a95e 100644 --- a/crates/recent_projects/src/recent_projects.rs +++ b/crates/recent_projects/src/recent_projects.rs @@ -36,7 +36,7 @@ use project::{Worktree, git_store::Repository}; pub use remote_connections::RemoteSettings; pub use remote_servers::RemoteServerProjects; use settings::{DefaultOpenBehavior, Settings, WorktreeId}; -use workspace::ProjectGroupKey; +use workspace::{OpenPathPromptMode, ProjectGroupKey}; use dev_container::{DevContainerContext, find_devcontainer_configs}; use ui::{ @@ -304,6 +304,7 @@ pub fn init(cx: &mut App) { workspace.project().clone(), workspace.app_state().fs.clone(), ), + OpenPathPromptMode::SelectPath, window, cx, ); @@ -314,9 +315,10 @@ pub fn init(cx: &mut App) { cx.spawn_in(window, async move |workspace, cx| { use util::paths::SanitizedPath; - let Some(paths) = paths.await.log_err().flatten() else { + let Some(result) = paths.await.log_err().flatten() else { return; }; + let paths = result.paths; let wsl_path = paths .iter() @@ -2077,58 +2079,30 @@ fn open_local_project( cx: &mut App, ) { use gpui::PathPromptOptions; - use project::DirectoryLister; let Some(workspace) = workspace.upgrade() else { return; }; - let paths = workspace.update(cx, |workspace, cx| { - workspace.prompt_for_open_path( + workspace.update(cx, |workspace, cx| { + workspace::prompt_for_open_path_and_open( + workspace, + workspace.app_state().clone(), PathPromptOptions { files: true, directories: true, multiple: true, prompt: None, }, - DirectoryLister::Local( - workspace.project().clone(), - workspace.app_state().fs.clone(), - ), + if create_new_window { + OpenPathPromptMode::NewWindow + } else { + OpenPathPromptMode::CurrentWindow + }, window, cx, - ) + ); }); - - let multi_workspace_handle = window.window_handle().downcast::(); - window - .spawn(cx, async move |cx| { - let Some(paths) = paths.await.log_err().flatten() else { - return; - }; - if !create_new_window { - if let Some(handle) = multi_workspace_handle { - if let Some(task) = handle - .update(cx, |multi_workspace, window, cx| { - multi_workspace.open_project(paths, OpenMode::Activate, window, cx) - }) - .log_err() - { - task.await.log_err(); - } - return; - } - } - if let Some(task) = workspace - .update_in(cx, |workspace, window, cx| { - workspace.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx) - }) - .log_err() - { - task.await.log_err(); - } - }) - .detach(); } impl RecentProjectsDelegate { @@ -2497,7 +2471,7 @@ mod tests { use serde_json::json; use settings::SettingsStore; use util::path; - use workspace::{AppState, PathList, open_paths}; + use workspace::{AppState, OpenPathPromptResult, PathList, open_paths}; use super::*; @@ -2985,10 +2959,13 @@ mod tests { // Set up the prompt mock to return the new project path. workspace.update(cx, |workspace, _cx| { - workspace.set_prompt_for_open_path(Box::new(|_, _, _, _| { + workspace.set_prompt_for_open_path(Box::new(|_, _, mode, _, _| { let (tx, rx) = futures::channel::oneshot::channel(); - tx.send(Some(vec![PathBuf::from(path!("/new-project"))])) - .ok(); + tx.send(Some(OpenPathPromptResult { + paths: vec![PathBuf::from(path!("/new-project"))], + open_in_new_window: mode == OpenPathPromptMode::NewWindow, + })) + .ok(); rx })); }); @@ -3061,10 +3038,13 @@ mod tests { // Set up the prompt mock to return the new project path. workspace.update(cx, |workspace, _cx| { - workspace.set_prompt_for_open_path(Box::new(|_, _, _, _| { + workspace.set_prompt_for_open_path(Box::new(|_, _, mode, _, _| { let (tx, rx) = futures::channel::oneshot::channel(); - tx.send(Some(vec![PathBuf::from(path!("/new-project"))])) - .ok(); + tx.send(Some(OpenPathPromptResult { + paths: vec![PathBuf::from(path!("/new-project"))], + open_in_new_window: mode == OpenPathPromptMode::NewWindow, + })) + .ok(); rx })); }); diff --git a/crates/remote/src/transport/ssh.rs b/crates/remote/src/transport/ssh.rs index 51c5fe71614..433ce4d9830 100644 --- a/crates/remote/src/transport/ssh.rs +++ b/crates/remote/src/transport/ssh.rs @@ -1643,12 +1643,18 @@ impl SshSocket { self.ssh_command(ShellKind::Posix, "sh", &["-s"], false) } + fn environment_posix_argument_command(&self, script: &str) -> Command { + self.ssh_command(ShellKind::Posix, "sh", &["-c", script], false) + } + async fn environment_posix(&self) -> Result { let script = RemoteEnvironment::posix_script(); - let output = command_output(self.environment_posix_command(), Some(script.as_bytes())) - .await - .context("determining remote environment")?; - RemoteEnvironment::parse_posix(&output) + probe_environment_posix( + self.environment_posix_command(), + || self.environment_posix_argument_command(&script), + &script, + ) + .await } /// Best-effort detection of the remote OS version. Failures are logged and @@ -1786,6 +1792,28 @@ async fn command_output(mut command: Command, input: Option<&[u8]>) -> Result Command, + script: &str, +) -> Result { + let output = command_output(stdin_command, Some(script.as_bytes())) + .await + .context("determining remote environment")?; + match RemoteEnvironment::parse_posix(&output) { + Ok(environment) => Ok(environment), + Err(error) => { + log::warn!( + "Failed to parse the remote environment probed via stdin, retrying with the script as an argument: {error:#}" + ); + let output = command_output(argument_command(), None) + .await + .context("determining remote environment")?; + RemoteEnvironment::parse_posix(&output) + } + } +} + fn parse_port_number(port_str: &str) -> Result { port_str .parse() @@ -2592,6 +2620,27 @@ mod tests { Ok(()) } + #[cfg(unix)] + #[test] + fn environment_posix_probe_retries_when_stdin_is_consumed() -> Result<()> { + let socket = smol::block_on(SshSocket::new( + SshConnectionOptions::default(), + PathBuf::from("/tmp/zed-test.sock"), + ))?; + let script = RemoteEnvironment::posix_script(); + let stdin_command = stdin_consuming_remote_shell(&socket.environment_posix_command())?; + let argument_command = + stdin_consuming_remote_shell(&socket.environment_posix_argument_command(&script))?; + let environment = smol::block_on(probe_environment_posix( + stdin_command, + move || argument_command, + &script, + ))?; + assert_eq!(environment.shell, "/bin/bash"); + assert_eq!(environment.platform.arch.as_str(), std::env::consts::ARCH); + Ok(()) + } + #[cfg(unix)] #[test] fn version_query_failure_does_not_abort_probe() -> Result<()> { @@ -3331,4 +3380,22 @@ mod tests { ["--", "-oProxyCommand=touch /tmp/pwned"] ); } + + #[cfg(unix)] + fn stdin_consuming_remote_shell(ssh_command: &Command) -> Result { + let remote_command = ssh_command + .get_args() + .last() + .context("Missing remote command")? + .to_string_lossy(); + let mut command = util::command::new_command("/bin/sh"); + command + .arg("-c") + .arg(format!("cat > /dev/null; {remote_command}")) + .env("SHELL", "/bin/bash") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + Ok(command) + } } diff --git a/crates/settings_content/src/project.rs b/crates/settings_content/src/project.rs index 05be8098bb8..cff041fe7ea 100644 --- a/crates/settings_content/src/project.rs +++ b/crates/settings_content/src/project.rs @@ -663,6 +663,8 @@ pub struct GitSettings { pub branch_picker: Option, /// Stash picker settings. pub stash_picker: Option, + /// Commit view settings. + pub commit_view: Option, /// File diff settings. pub file_diff: Option, /// How hunks are displayed visually in the editor. @@ -879,6 +881,20 @@ pub struct StashPickerSettings { pub date_style: Option, } +#[with_fallible_options] +#[derive(Clone, Copy, PartialEq, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom)] +#[serde(rename_all = "snake_case")] +pub struct CommitViewSettingsContent { + /// Whether newly opened commit views show the full commit description. + /// + /// Default: false + pub expand_description: Option, + /// Whether newly opened commit views expand every changed file. + /// + /// Default: true + pub expand_files: Option, +} + #[with_fallible_options] #[derive(Clone, Copy, PartialEq, Debug, Default, Serialize, Deserialize, JsonSchema, MergeFrom)] #[serde(rename_all = "snake_case")] diff --git a/crates/settings_ui/src/page_data.rs b/crates/settings_ui/src/page_data.rs index d0801b2052c..3c96ecd45c6 100644 --- a/crates/settings_ui/src/page_data.rs +++ b/crates/settings_ui/src/page_data.rs @@ -8879,9 +8879,63 @@ fn version_control_page() -> SettingsPage { ] } - fn file_diff_section() -> [SettingsPageItem; 2] { + fn commit_view_section() -> [SettingsPageItem; 4] { [ - SettingsPageItem::SectionHeader("File Diff"), + SettingsPageItem::SectionHeader("Git Commit View"), + SettingsPageItem::SettingItem(SettingItem { + title: "Expand Description by Default", + description: "Whether newly opened commit views show the full commit description.", + field: Box::new(SettingField { + organization_override: None, + json_path: Some("git.commit_view.expand_description"), + pick: |settings_content| { + settings_content + .git + .as_ref()? + .commit_view + .as_ref()? + .expand_description + .as_ref() + }, + write: |settings_content, value, _| { + settings_content + .git + .get_or_insert_default() + .commit_view + .get_or_insert_default() + .expand_description = value; + }, + }), + metadata: None, + files: USER, + }), + SettingsPageItem::SettingItem(SettingItem { + title: "Expand Files by Default", + description: "Whether newly opened commit views expand every changed file.", + field: Box::new(SettingField { + organization_override: None, + json_path: Some("git.commit_view.expand_files"), + pick: |settings_content| { + settings_content + .git + .as_ref()? + .commit_view + .as_ref()? + .expand_files + .as_ref() + }, + write: |settings_content, value, _| { + settings_content + .git + .get_or_insert_default() + .commit_view + .get_or_insert_default() + .expand_files = value; + }, + }), + metadata: None, + files: USER, + }), SettingsPageItem::SettingItem(SettingItem { title: "Show Full File by Default", description: "Whether newly opened file diffs show the full file instead of changes only.", @@ -8921,8 +8975,8 @@ fn version_control_page() -> SettingsPage { git_blame_view_section(), branch_picker_section(), stash_picker_section(), + commit_view_section(), git_graph_section(), - file_diff_section(), git_hunks_section(), ], } diff --git a/crates/sidebar/src/sidebar.rs b/crates/sidebar/src/sidebar.rs index 36ba069cdae..fe99729a61d 100644 --- a/crates/sidebar/src/sidebar.rs +++ b/crates/sidebar/src/sidebar.rs @@ -8109,9 +8109,9 @@ fn all_thread_infos_for_workspace( .conversation_views() .into_iter() .filter_map(|conversation_view| { - let has_pending_tool_call = conversation_view + let is_waiting_for_input = conversation_view .read(cx) - .root_thread_has_pending_tool_call(cx); + .root_thread_is_waiting_for_input(cx); let conversation_thread_id = conversation_view.read(cx).parent_id(); let thread_view = conversation_view.read(cx).root_thread_view()?; let thread_view_ref = thread_view.read(cx); @@ -8128,7 +8128,7 @@ fn all_thread_infos_for_workspace( let session_id = thread.session_id().clone(); let is_background = agent_panel.is_retained_thread(&conversation_thread_id); - let status = if has_pending_tool_call { + let status = if is_waiting_for_input { AgentThreadStatus::WaitingForConfirmation } else if thread.had_error() { AgentThreadStatus::Error @@ -8355,7 +8355,7 @@ fn dump_single_workspace(workspace: &Workspace, output: &mut String, cx: &gpui:: .is_some_and(|conversation_view| { conversation_view .read(cx) - .root_thread_has_pending_tool_call(cx) + .root_thread_is_waiting_for_input(cx) }) { write!(output, ", awaiting confirmation").ok(); @@ -8387,7 +8387,7 @@ fn dump_single_workspace(workspace: &Workspace, output: &mut String, cx: &gpui:: write!(output, " [{status}, {entry_count} entries").ok(); if conversation_view .read(cx) - .root_thread_has_pending_tool_call(cx) + .root_thread_is_waiting_for_input(cx) { write!(output, ", awaiting confirmation").ok(); } diff --git a/crates/sidebar/src/sidebar_tests.rs b/crates/sidebar/src/sidebar_tests.rs index 7b1daa468de..8c18bfe172f 100644 --- a/crates/sidebar/src/sidebar_tests.rs +++ b/crates/sidebar/src/sidebar_tests.rs @@ -4640,6 +4640,90 @@ async fn test_subagent_permission_request_marks_parent_sidebar_thread_waiting( assert_eq!(parent_status, AgentThreadStatus::WaitingForConfirmation); } +#[gpui::test] +async fn test_elicitation_marks_sidebar_thread_waiting_until_responded(cx: &mut TestAppContext) { + let project = init_test_project_with_agent_panel("/my-project", cx).await; + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx)); + let (sidebar, panel) = setup_sidebar_with_agent_panel(&multi_workspace, cx); + + open_thread_with_connection(&panel, StubAgentConnection::new(), cx); + send_message(&panel, cx); + let session_id = active_session_id(&panel, cx); + save_test_thread_metadata(&session_id, &project, cx).await; + let thread = cx.update(|_, cx| panel.read(cx).active_agent_thread(cx).unwrap()); + let thread_status = |cx: &mut VisualTestContext| { + sidebar.read_with(cx, |sidebar, _cx| { + sidebar + .contents + .entries + .iter() + .find_map(|entry| match entry { + ListEntry::Thread(thread) + if thread.metadata.session_id.as_ref() == Some(&session_id) => + { + Some(thread.status) + } + _ => None, + }) + .expect("Expected thread entry in sidebar") + }) + }; + assert_eq!(thread_status(cx), AgentThreadStatus::Running); + + for action in [ + acp_v2::ElicitationAction::Accept(acp_v2::ElicitationAcceptAction::new().content( + std::collections::BTreeMap::from([( + "choice".to_string(), + acp_v2::ElicitationContentValue::from("first"), + )]), + )), + acp_v2::ElicitationAction::Decline, + acp_v2::ElicitationAction::Cancel, + ] { + let (elicitation_id, response_task) = thread.update(cx, |thread, cx| { + thread + .request_elicitation_with_id( + acp_v2::CreateElicitationRequest::new( + acp_v2::ElicitationFormMode::new( + acp_v2::ElicitationSessionScope::new(session_id.clone()), + serde_json::from_value(serde_json::json!({ + "type": "object", + "required": ["choice"], + "properties": { + "choice": { + "type": "string", + "oneOf": [ + { "const": "first", "title": "First" }, + { "const": "second", "title": "Second" } + ] + } + } + })) + .expect("Valid single-select schema"), + ), + "Choose one", + ), + cx, + ) + .expect("Elicitation should be accepted") + }); + cx.run_until_parked(); + assert_eq!(thread_status(cx), AgentThreadStatus::WaitingForConfirmation); + + thread.update(cx, |thread, cx| { + thread.respond_to_elicitation( + &elicitation_id, + acp_v2::CreateElicitationResponse::new(action), + cx, + ); + }); + response_task.await; + cx.run_until_parked(); + assert_eq!(thread_status(cx), AgentThreadStatus::Running); + } +} + #[gpui::test] async fn test_background_thread_completion_triggers_notification(cx: &mut TestAppContext) { let project_a = init_test_project_with_agent_panel("/project-a", cx).await; diff --git a/crates/terminal_view/src/terminal_element.rs b/crates/terminal_view/src/terminal_element.rs index 6db4b3b079f..27469eeac2a 100644 --- a/crates/terminal_view/src/terminal_element.rs +++ b/crates/terminal_view/src/terminal_element.rs @@ -1753,14 +1753,6 @@ impl Element for TerminalElement { } } -impl IntoElement for TerminalElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - struct TerminalInputHandler { terminal_view: Entity, workspace: WeakEntity, diff --git a/crates/ui/src/components/indent_guides.rs b/crates/ui/src/components/indent_guides.rs index f83dda592f6..6ad29a294ce 100644 --- a/crates/ui/src/components/indent_guides.rs +++ b/crates/ui/src/components/indent_guides.rs @@ -432,14 +432,6 @@ impl Element for IndentGuidesElement { } } -impl IntoElement for IndentGuidesElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - fn compute_indent_guides( indents: &[usize], offset: usize, diff --git a/crates/ui/src/components/popover_menu.rs b/crates/ui/src/components/popover_menu.rs index 44a381ccd11..c1c078d6dba 100644 --- a/crates/ui/src/components/popover_menu.rs +++ b/crates/ui/src/components/popover_menu.rs @@ -503,14 +503,6 @@ impl Element for PopoverMenu { } } -impl IntoElement for PopoverMenu { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - #[cfg(test)] mod tests { use gpui::{EventEmitter, FocusHandle, Focusable, TestAppContext, VisualTestContext}; diff --git a/crates/ui/src/components/right_click_menu.rs b/crates/ui/src/components/right_click_menu.rs index 9cc792326b1..b7c29bf6bc6 100644 --- a/crates/ui/src/components/right_click_menu.rs +++ b/crates/ui/src/components/right_click_menu.rs @@ -299,11 +299,3 @@ impl Element for RightClickMenu { ) } } - -impl IntoElement for RightClickMenu { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} diff --git a/crates/ui/src/components/scrollbar.rs b/crates/ui/src/components/scrollbar.rs index 679b6bc17f0..de9df116bca 100644 --- a/crates/ui/src/components/scrollbar.rs +++ b/crates/ui/src/components/scrollbar.rs @@ -2,12 +2,12 @@ use std::{any::Any, fmt::Debug, ops::Not, time::Duration}; use web_time::Instant; use gpui::{ - Along, Anchor, AnyElement, App, AppContext as _, Axis as ScrollbarAxis, BorderStyle, Bounds, - ContentMask, Context, Corners, CursorStyle, DispatchPhase, Div, Edges, Element, ElementId, - Entity, EntityId, GlobalElementId, Hitbox, HitboxBehavior, Hsla, InteractiveElement, - IntoElement, IsZero, LayoutId, ListState, MouseButton, MouseDownEvent, MouseMoveEvent, - MouseUpEvent, ParentElement, Pixels, Point, Position, Render, ScrollEvent, ScrollHandle, Size, - Stateful, StatefulInteractiveElement, Style, StyleRefinement, Styled, Subscription, Task, + Along, Anchor, App, AppContext as _, Axis as ScrollbarAxis, BorderStyle, Bounds, ContentMask, + Context, Corners, CursorStyle, DispatchPhase, Div, Edges, Element, ElementId, Entity, EntityId, + GlobalElementId, Hitbox, HitboxBehavior, Hsla, InteractiveElement, IntoElement, IsZero, + LayoutId, ListState, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, + Pixels, Point, Position, Render, ScrollEvent, ScrollHandle, Size, Stateful, + StatefulInteractiveElement, Style, StyleRefinement, Styled, Subscription, Task, UniformListDecoration, UniformListScrollHandle, Window, ease_in_out, fill, prelude::FluentBuilder as _, px, quad, relative, size, }; @@ -1011,11 +1011,6 @@ impl ThumbState { } impl ScrollableHandle for UniformListScrollHandle { - #[inline(never)] - fn into_scrollbar_element(element: ScrollbarElement) -> AnyElement { - element.into_any() - } - fn max_offset(&self) -> Point { self.0.borrow().base_handle.max_offset() } @@ -1034,11 +1029,6 @@ impl ScrollableHandle for UniformListScrollHandle { } impl ScrollableHandle for ListState { - #[inline(never)] - fn into_scrollbar_element(element: ScrollbarElement) -> AnyElement { - element.into_any() - } - fn max_offset(&self) -> Point { self.max_offset_for_scrollbar() } @@ -1065,11 +1055,6 @@ impl ScrollableHandle for ListState { } impl ScrollableHandle for ScrollHandle { - #[inline(never)] - fn into_scrollbar_element(element: ScrollbarElement) -> AnyElement { - element.into_any() - } - fn max_offset(&self) -> Point { self.max_offset() } @@ -1088,10 +1073,6 @@ impl ScrollableHandle for ScrollHandle { } pub trait ScrollableHandle: 'static + Any + Sized + Clone { - fn into_scrollbar_element(element: ScrollbarElement) -> AnyElement { - element.into_any() - } - fn max_offset(&self) -> Point; fn set_offset(&self, point: Point); fn offset(&self) -> Point; @@ -1751,18 +1732,6 @@ impl Element for ScrollbarElement { } } -impl IntoElement for ScrollbarElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } - - fn into_any_element(self) -> AnyElement { - T::into_scrollbar_element(self) - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui/src/components/sticky_items.rs b/crates/ui/src/components/sticky_items.rs index bf64622b29a..be233b3e65d 100644 --- a/crates/ui/src/components/sticky_items.rs +++ b/crates/ui/src/components/sticky_items.rs @@ -66,14 +66,6 @@ struct StickyItemsElement { rest_decorations: SmallVec<[AnyElement; 1]>, } -impl IntoElement for StickyItemsElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} - impl Element for StickyItemsElement { type RequestLayoutState = (); type PrepaintState = (); diff --git a/crates/ui/src/utils/with_rem_size.rs b/crates/ui/src/utils/with_rem_size.rs index b9770b086ca..d8e6c633a1a 100644 --- a/crates/ui/src/utils/with_rem_size.rs +++ b/crates/ui/src/utils/with_rem_size.rs @@ -1,7 +1,6 @@ use gpui::{ AnyElement, App, Bounds, Div, DivFrameState, Element, ElementId, GlobalElementId, Hitbox, - InteractiveElement as _, IntoElement, LayoutId, ParentElement, Pixels, StyleRefinement, Styled, - Window, div, + InteractiveElement as _, LayoutId, ParentElement, Pixels, StyleRefinement, Styled, Window, div, }; /// An element that sets a particular rem size for its children. @@ -104,11 +103,3 @@ impl Element for WithRemSize { }) } } - -impl IntoElement for WithRemSize { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } -} diff --git a/crates/workspace/src/invalid_item_view.rs b/crates/workspace/src/invalid_item_view.rs index 08242a1ed0c..3af6d83ad1e 100644 --- a/crates/workspace/src/invalid_item_view.rs +++ b/crates/workspace/src/invalid_item_view.rs @@ -1,6 +1,7 @@ -use std::{path::Path, sync::Arc}; +use std::{fmt, path::Path, sync::Arc}; -use gpui::{EventEmitter, FocusHandle, Focusable}; +use gpui::{Entity, EventEmitter, FocusHandle, Focusable}; +use project::{ProjectPath, Worktree}; use ui::{ App, Button, ButtonCommon, ButtonStyle, Clickable, Context, FluentBuilder, InteractiveElement, KeyBinding, Label, LabelCommon, LabelSize, ParentElement, Render, SharedString, Styled as _, @@ -8,10 +9,9 @@ use ui::{ }; use zed_actions::workspace::OpenWithSystem; -use crate::Item; +use crate::{Item, ItemNavHistory, Workspace}; /// A view to display when a certain buffer/image/other item fails to open. -#[derive(Debug)] pub struct InvalidItemView { /// Which path was attempted to open. pub abs_path: Arc, @@ -19,6 +19,8 @@ pub struct InvalidItemView { pub error: SharedString, is_local: bool, focus_handle: FocusHandle, + project_identity: Option<(Entity, ProjectPath)>, + nav_history: Option, } impl InvalidItemView { @@ -34,8 +36,37 @@ impl InvalidItemView { abs_path: Arc::from(abs_path), error: format!("{}", e.root_cause()).into(), focus_handle: cx.focus_handle(), + project_identity: None, + nav_history: None, } } + + pub(crate) fn with_project_path( + mut self, + worktree: Entity, + project_path: ProjectPath, + ) -> Self { + self.project_identity = Some((worktree, project_path)); + self + } + + pub(crate) fn has_deleted_file(&self, cx: &App) -> bool { + self.project_identity + .as_ref() + .is_some_and(|(worktree, project_path)| { + Workspace::history_path_is_removed(worktree.read(cx), &project_path.path, cx) + }) + } +} + +impl fmt::Debug for InvalidItemView { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("InvalidItemView") + .field("abs_path", &self.abs_path) + .field("error", &self.error) + .finish_non_exhaustive() + } } impl Item for InvalidItemView { @@ -65,6 +96,24 @@ impl Item for InvalidItemView { SharedString::new(path.to_string_lossy()) } + + fn active_project_path(&self, _: &App) -> Option { + self.project_identity + .as_ref() + .map(|(_, project_path)| project_path.clone()) + } + + fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut Window, _: &mut Context) { + self.nav_history = Some(history); + } + + fn deactivated(&mut self, _: &mut Window, cx: &mut Context) { + if let Some((_, project_path)) = &self.project_identity + && let Some(history) = &mut self.nav_history + { + history.push_path(project_path.clone(), self.abs_path.to_path_buf(), cx); + } + } } impl EventEmitter<()> for InvalidItemView {} diff --git a/crates/workspace/src/multi_workspace.rs b/crates/workspace/src/multi_workspace.rs index 12d18436bfc..ec35dd8ff11 100644 --- a/crates/workspace/src/multi_workspace.rs +++ b/crates/workspace/src/multi_workspace.rs @@ -28,7 +28,7 @@ const SIDEBAR_RESIZE_HANDLE_SIZE: Pixels = px(6.0); use crate::open_remote_project_with_existing_connection; use crate::{ CloseIntent, CloseWindow, DockPosition, Event as WorkspaceEvent, Item, ModalView, OpenMode, - Panel, Workspace, WorkspaceId, client_side_decorations, + OpenOptions, OpenVisible, Panel, Workspace, WorkspaceId, client_side_decorations, persistence::model::MultiWorkspaceState, }; @@ -2006,7 +2006,35 @@ impl MultiWorkspace { }) } else { let workspace = self.workspace().clone(); - cx.spawn_in(window, async move |_this, cx| { + let project = workspace.read(cx).project().read(cx); + let reuse_workspace = open_mode != OpenMode::NewWindow + && project.is_local() + && project.visibility_for_paths(&paths, true, cx).is_some(); + cx.spawn_in(window, async move |_, cx| { + if reuse_workspace { + let results = workspace + .update_in(cx, |workspace, window, cx| { + workspace.open_paths( + paths, + OpenOptions { + visible: Some(OpenVisible::All), + ..OpenOptions::default() + }, + None, + window, + cx, + ) + })? + .await; + workspace.update(cx, |workspace, cx| { + for result in results.into_iter().flatten() { + if let Err(error) = result { + workspace.show_error(error, cx); + } + } + }); + return Ok(workspace); + } let should_continue = workspace .update_in(cx, |workspace, window, cx| { workspace.prepare_to_close(crate::CloseIntent::ReplaceWindow, window, cx) @@ -2015,9 +2043,18 @@ impl MultiWorkspace { if should_continue { workspace .update_in(cx, |workspace, window, cx| { - workspace.open_workspace_for_paths(open_mode, paths, window, cx) + Workspace::new_local( + paths, + workspace.app_state().clone(), + window.window_handle().downcast(), + None, + None, + open_mode, + cx, + ) })? .await + .map(|result| result.workspace) } else { Ok(workspace) } diff --git a/crates/workspace/src/pane.rs b/crates/workspace/src/pane.rs index faf7cbeb468..20011850842 100644 --- a/crates/workspace/src/pane.rs +++ b/crates/workspace/src/pane.rs @@ -1167,6 +1167,8 @@ impl Pane { { if already_open_view.is_none() && existing_error_view.read(cx).error == invalid_buffer_view.read(cx).error + && existing_error_view.read(cx).active_project_path(cx) + == invalid_buffer_view.read(cx).active_project_path(cx) { already_open_view = Some(existing_error_view); } else { @@ -4810,6 +4812,20 @@ impl ItemNavHistory { pub fn pop_forward(&mut self, cx: &mut App) -> Option { self.history.pop(NavigationMode::GoingForward, cx) } + + pub(crate) fn push_path( + &mut self, + project_path: ProjectPath, + absolute_path: PathBuf, + cx: &mut App, + ) { + self.history + .0 + .lock() + .paths_by_item + .insert(self.item.id(), (project_path, Some(absolute_path))); + self.push::<()>(None, None, cx); + } } impl NavHistory { @@ -5206,6 +5222,82 @@ mod tests { } } + #[gpui::test] + async fn test_invalid_item_identity_deduplication(cx: &mut TestAppContext) { + init_test(cx); + let fs = FakeFs::new(cx.executor()); + fs.insert_tree(util::path!("/root"), serde_json::json!({ "file.bin": "" })) + .await; + let project = Project::test(fs, [util::path!("/root").as_ref()], cx).await; + let (workspace, cx) = + cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx)); + let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone()); + let mut original_item_id = None; + + for replace_identity in [false, false, true] { + if replace_identity { + project.update(cx, |project, cx| { + let worktree_id = project.worktrees(cx).next().unwrap().read(cx).id(); + project.remove_worktree(worktree_id, cx); + }); + project + .update(cx, |project, cx| { + project.find_or_create_worktree(util::path!("/root"), true, cx) + }) + .await + .unwrap(); + } + + let (item, expected_item_id, project_path) = pane.update_in(cx, |pane, window, cx| { + let absolute_path = util::path!("/root/file.bin").as_ref(); + let (worktree, path) = project.read(cx).find_worktree(absolute_path, cx).unwrap(); + let project_path = ProjectPath { + worktree_id: worktree.read(cx).id(), + path, + }; + let new_item = cx.new(|cx| { + InvalidItemView::new( + absolute_path, + true, + &anyhow::anyhow!("binary file"), + window, + cx, + ) + .with_project_path(worktree, project_path.clone()) + }); + let expected_item_id = if replace_identity { + new_item.entity_id() + } else { + *original_item_id.get_or_insert(new_item.entity_id()) + }; + let item = pane.open_item( + None, + project_path.clone(), + true, + false, + true, + None, + window, + cx, + Box::new(move |_, _, _| new_item.boxed_clone()), + ); + (item, expected_item_id, project_path) + }); + assert_eq!(item.item_id(), expected_item_id); + cx.run_until_parked(); + pane.read_with(cx, |pane, cx| { + assert_eq!( + pane.items().map(|item| item.item_id()).collect::>(), + vec![expected_item_id], + ); + assert_eq!( + pane.active_item().unwrap().project_path(cx), + Some(project_path) + ); + }); + } + } + #[gpui::test] async fn test_remove_navigation_history_paths(cx: &mut TestAppContext) { init_test(cx); diff --git a/crates/workspace/src/pane_group.rs b/crates/workspace/src/pane_group.rs index 672190aff60..41721c6c553 100644 --- a/crates/workspace/src/pane_group.rs +++ b/crates/workspace/src/pane_group.rs @@ -1142,8 +1142,8 @@ mod element { use gpui::{ Along, AnyElement, App, Axis, BorderStyle, Bounds, Element, GlobalElementId, - HitboxBehavior, IntoElement, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, - Pixels, Point, Size, Style, WeakEntity, Window, px, relative, size, + HitboxBehavior, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, Point, + Size, Style, WeakEntity, Window, px, relative, size, }; use gpui::{CursorStyle, Hitbox}; use parking_lot::Mutex; @@ -1347,14 +1347,6 @@ mod element { } } - impl IntoElement for PaneAxisElement { - type Element = Self; - - fn into_element(self) -> Self::Element { - self - } - } - impl Element for PaneAxisElement { type RequestLayoutState = (); type PrepaintState = PaneAxisLayout; diff --git a/crates/workspace/src/workspace.rs b/crates/workspace/src/workspace.rs index a6961f516d2..f8177139acd 100644 --- a/crates/workspace/src/workspace.rs +++ b/crates/workspace/src/workspace.rs @@ -68,6 +68,7 @@ use gpui::{ transparent_black, }; pub use history_manager::*; +use invalid_item_view::InvalidItemView; pub use item::{ FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings, ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle, @@ -903,7 +904,11 @@ fn prompt_and_open_paths( workspace, app_state, options, - create_new_window, + if create_new_window { + OpenPathPromptMode::NewWindow + } else { + OpenPathPromptMode::CurrentWindow + }, window, cx, ); @@ -930,7 +935,7 @@ fn prompt_and_open_paths( workspace, app_state, options, - create_new_window, + OpenPathPromptMode::SelectPath, window, cx, ); @@ -946,40 +951,91 @@ pub fn prompt_for_open_path_and_open( workspace: &mut Workspace, app_state: Arc, options: PathPromptOptions, - create_new_window: bool, + mode: OpenPathPromptMode, window: &mut Window, cx: &mut Context, ) { let paths = workspace.prompt_for_open_path( options, DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()), + mode, window, cx, ); let multi_workspace_handle = window.window_handle().downcast::(); - cx.spawn_in(window, async move |this, cx| { - let Some(paths) = paths.await.log_err().flatten() else { + cx.spawn_in(window, async move |workspace, cx| { + let Some(OpenPathPromptResult { + paths, + open_in_new_window, + }) = paths.await.log_err().flatten() + else { return; }; - if !create_new_window { + if !open_in_new_window { + let is_local = workspace + .read_with(cx, |workspace, cx| workspace.project().read(cx).is_local()) + .unwrap_or(false); + if is_local + && !futures::future::join_all(paths.iter().map(|path| app_state.fs.is_dir(path))) + .await + .into_iter() + .any(|is_directory| is_directory) + { + let Ok(task) = workspace.update_in(cx, |workspace, window, cx| { + let visible = if workspace + .project() + .read(cx) + .visible_worktrees(cx) + .next() + .is_none() + { + OpenVisible::All + } else { + OpenVisible::None + }; + workspace.open_paths( + paths, + OpenOptions { + visible: Some(visible), + ..OpenOptions::default() + }, + None, + window, + cx, + ) + }) else { + return; + }; + for result in task.await.into_iter().flatten() { + if let Err(error) = result { + workspace + .update(cx, |workspace, cx| workspace.show_error(error, cx)) + .ok(); + } + } + return; + } if let Some(handle) = multi_workspace_handle { - if let Some(task) = handle - .update(cx, |multi_workspace, window, cx| { - multi_workspace.open_project(paths, OpenMode::Activate, window, cx) - }) - .log_err() - { + if let Ok(task) = handle.update(cx, |multi_workspace, window, cx| { + multi_workspace.open_project(paths, OpenMode::Activate, window, cx) + }) { task.await.log_err(); } return; } } - if let Some(task) = this - .update_in(cx, |this, window, cx| { - this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx) - }) - .log_err() - { + if let Ok(task) = workspace.update_in(cx, |_, _, cx| { + open_paths( + &paths, + app_state, + OpenOptions { + open_mode: OpenMode::NewWindow, + workspace_matching: WorkspaceMatching::None, + ..OpenOptions::default() + }, + cx, + ) + }) { task.await.log_err(); } }) @@ -1026,7 +1082,8 @@ pub fn init(app_state: Arc, cx: &mut App) { multiple: true, prompt: None, }, - true, + WorkspaceSettings::get_global(cx).default_open_behavior + == DefaultOpenBehavior::NewWindow, cx, ); }); @@ -1068,6 +1125,7 @@ impl ProjectItemRegistry { .is_some_and(|entry| entry.is_file()); let entry_abs_path = project.read(cx).absolute_path(&project_path, cx); let is_local = project.read(cx).is_local(); + let worktree = project.read(cx).worktree_for_id(project_path.worktree_id, cx); let project_item = ::try_open(project, &project_path, cx)?; let project = project.clone(); @@ -1110,6 +1168,11 @@ impl ProjectItemRegistry { ) })? { + let broken_project_item_view = if let Some(worktree) = worktree { + broken_project_item_view.with_project_path(worktree, project_path) + } else { + broken_project_item_view + }; let build_workspace_item = Box::new( move |_: &mut Pane, _: &mut Window, cx: &mut Context| { cx.new(|_| broken_project_item_view).boxed_clone() @@ -1535,6 +1598,19 @@ pub enum OpenVisible { OnlyDirectories, } +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum OpenPathPromptMode { + SelectPath, + CurrentWindow, + NewWindow, +} + +#[derive(Debug)] +pub struct OpenPathPromptResult { + pub paths: Vec, + pub open_in_new_window: bool, +} + enum WorkspaceLocation { // Valid local paths or SSH project to serialize Location(SerializedWorkspaceLocation, PathList), @@ -1556,9 +1632,10 @@ type PromptForOpenPath = Box< dyn Fn( &mut Workspace, DirectoryLister, + OpenPathPromptMode, &mut Window, &mut Context, - ) -> oneshot::Receiver>>, + ) -> oneshot::Receiver>, >; #[derive(Default)] @@ -2166,6 +2243,10 @@ impl Workspace { open_mode: OpenMode, cx: &mut App, ) -> Task> { + #[cfg(target_os = "windows")] + let wsl_path = abs_paths + .iter() + .find_map(|path| util::paths::WslPath::from_path(path)); let project_handle = Project::local( app_state.client.clone(), app_state.node_runtime.clone(), @@ -2361,6 +2442,10 @@ impl Workspace { }; notify_if_database_failed(window, cx); + #[cfg(target_os = "windows")] + if let Some(wsl_path) = wsl_path { + workspace.update(cx, |workspace, cx| workspace.notify_wsl_path(wsl_path, cx)); + } // Check if this is an empty workspace (no paths to open) // An empty workspace is one where project_paths is empty let is_empty_workspace = project_paths.is_empty(); @@ -3470,21 +3555,30 @@ impl Workspace { pub fn prompt_for_open_path( &mut self, - path_prompt_options: PathPromptOptions, + mut path_prompt_options: PathPromptOptions, lister: DirectoryLister, + mode: OpenPathPromptMode, window: &mut Window, cx: &mut Context, - ) -> oneshot::Receiver>> { + ) -> oneshot::Receiver> { // TODO: If `on_prompt_for_open_path` is set, we should always use it // rather than gating on `use_system_path_prompts`. This would let tests // inject a mock without also having to disable the setting. if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts { let prompt = self.on_prompt_for_open_path.take().unwrap(); - let rx = prompt(self, lister, window, cx); + let rx = prompt(self, lister, mode, window, cx); self.on_prompt_for_open_path = Some(prompt); rx } else { let (tx, rx) = oneshot::channel(); + if path_prompt_options.prompt.is_none() { + path_prompt_options.prompt = match mode { + OpenPathPromptMode::SelectPath => None, + OpenPathPromptMode::CurrentWindow => Some("Open in This Window"), + OpenPathPromptMode::NewWindow => Some("Open in New Window"), + } + .map(SharedString::from); + } let abs_path = cx.prompt_for_paths(path_prompt_options); cx.spawn_in(window, async move |workspace, cx| { @@ -3494,14 +3588,18 @@ impl Workspace { match result { Ok(result) => { - tx.send(result).ok(); + tx.send(result.map(|paths| OpenPathPromptResult { + paths, + open_in_new_window: mode == OpenPathPromptMode::NewWindow, + })) + .ok(); } Err(err) => { let rx = workspace.update_in(cx, |workspace, window, cx| { workspace .show_error(workspace_error::PortalError::new(err.to_string()), cx); let prompt = workspace.on_prompt_for_open_path.take().unwrap(); - let rx = prompt(workspace, lister, window, cx); + let rx = prompt(workspace, lister, mode, window, cx); workspace.on_prompt_for_open_path = Some(prompt); rx })?; @@ -4122,6 +4220,14 @@ impl Workspace { window: &mut Window, cx: &mut Context, ) -> Task>>>> { + #[cfg(target_os = "windows")] + if self.project.read(cx).is_local() + && let Some(wsl_path) = abs_paths + .iter() + .find_map(|path| util::paths::WslPath::from_path(path)) + { + self.notify_wsl_path(wsl_path, cx); + } let fs = self.app_state.fs.clone(); let caller_ordered_abs_paths = abs_paths.clone(); @@ -4350,15 +4456,16 @@ impl Workspace { prompt: None, }, DirectoryLister::Project(self.project.clone()), + OpenPathPromptMode::SelectPath, window, cx, ); cx.spawn_in(window, async move |this, cx| { - if let Some(paths) = paths.await.log_err().flatten() { + if let Some(result) = paths.await.log_err().flatten() { let results = this .update_in(cx, |this, window, cx| { this.open_paths( - paths, + result.paths, OpenOptions { visible: Some(OpenVisible::All), ..Default::default() @@ -6353,6 +6460,9 @@ impl Workspace { if item .project_path(cx) .is_some_and(|path| self.is_deleted_history_path(&path, cx)) + || item + .downcast::() + .is_some_and(|view| view.read(cx).has_deleted_file(cx)) { pane.update(cx, |pane, _| { pane.nav_history_mut().remove_item(item.item_id()) @@ -7824,6 +7934,30 @@ impl Workspace { .collect::>() } + #[cfg(target_os = "windows")] + fn notify_wsl_path(&mut self, wsl_path: util::paths::WslPath, cx: &mut Context) { + struct OpenInWsl; + let util::paths::WslPath { distro, path } = wsl_path; + self.show_notification(NotificationId::unique::(), cx, move |cx| { + let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy()); + let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote"); + cx.new(move |cx| { + MessageNotification::new(msg, cx) + .primary_message("Open in WSL") + .primary_icon(IconName::FolderOpen) + .primary_on_click(move |window, cx| { + window.dispatch_action(Box::new(remote::OpenWslPath { + distro: remote::WslConnectionOptions { + distro_name: distro.clone(), + user: None, + }, + paths: vec![path.clone().into()], + }), cx) + }) + }) + }); + } + fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context) { match member { Member::Axis(PaneAxis { members, .. }) => { @@ -11115,7 +11249,11 @@ pub fn workspace_windows_for_location<'a>( }) } -fn preferred_target_for_files(host: &ProjectHost<'_>, cx: &App) -> Option { +fn preferred_workspace_target( + host: &ProjectHost<'_>, + visible: OpenVisible, + cx: &App, +) -> Option { let target_for_window = |window: WindowHandle| { let multi_workspace = window.read(cx).ok()?; let active_workspace = multi_workspace.workspace(); @@ -11134,7 +11272,7 @@ fn preferred_target_for_files(host: &ProjectHost<'_>, cx: &App) -> Option()) { if let Ok(multi_workspace) = window.read(cx) { - for workspace in multi_workspace.workspaces() { + let active_workspace = multi_workspace.workspace(); + for workspace in std::iter::once(active_workspace).chain( + multi_workspace + .workspaces() + .filter(|workspace| *workspace != active_workspace), + ) { let workspace_ref = workspace.read(cx); let project = workspace_ref.project.read(cx); @@ -11193,27 +11337,26 @@ pub fn find_existing_workspace( } }; - if visibility > best_match { - existing = Some(WorkspaceOpenTarget { - window, - workspace: workspace.clone(), - visible: OpenVisible::All, - }); - best_match = visibility; - } else if best_match.is_none() - && open_options.workspace_matching - == WorkspaceMatching::MatchSubdirectory - { + let match_priority = visibility + .map(|visible| (visible, Some(window.into()) == active_window)); + if match_priority > best_match { existing = Some(WorkspaceOpenTarget { window, workspace: workspace.clone(), visible: OpenVisible::All, }); + best_match = match_priority; } } } } + if existing.is_none() + && open_options.workspace_matching == WorkspaceMatching::MatchSubdirectory + { + existing = preferred_workspace_target(host, OpenVisible::All, cx); + } + let all_paths_are_files = existing.as_ref().is_some_and(|target| { let workspace = target.workspace.read(cx); let project = workspace.project.read(cx); @@ -11240,7 +11383,7 @@ pub fn find_existing_workspace( }); if open_options.wait && existing.is_some() && all_paths_are_files { - existing = preferred_target_for_files(host, cx).or(existing); + existing = preferred_workspace_target(host, OpenVisible::None, cx).or(existing); } } @@ -11261,10 +11404,8 @@ pub enum WorkspaceMatching { /// worktree roots themselves. MatchSubpaths, /// Match paths against existing worktrees including subdirectories, and - /// fall back to any existing window if no worktree matched. - /// - /// For example, `zed -a foo/bar` will activate the `bar` workspace if it - /// exists, otherwise it will open a new window with `foo/bar` as the root. + /// fall back to a workspace on the requested host if none match, preferring + /// the focused window and its active workspace. MatchSubdirectory, } @@ -11440,10 +11581,6 @@ pub fn open_paths( cx: &mut App, ) -> Task> { let abs_paths = abs_paths.to_vec(); - #[cfg(target_os = "windows")] - let wsl_path = abs_paths - .iter() - .find_map(|p| util::paths::WslPath::from_path(p)); cx.spawn(async move |cx| { let mut reuse_target = @@ -11462,7 +11599,9 @@ pub fn open_paths( if all_metadatas.into_iter().all(|file| !file.is_dir) { reuse_target = cx - .update(|cx| preferred_target_for_files(&ProjectHost::Local, cx)) + .update(|cx| { + preferred_workspace_target(&ProjectHost::Local, OpenVisible::None, cx) + }) .or(reuse_target); } } @@ -11514,11 +11653,12 @@ pub fn open_paths( let open_in_dev_container = open_options.open_in_dev_container; - let result = if let Some(WorkspaceOpenTarget { + if let Some(WorkspaceOpenTarget { window: target_window, workspace: target_workspace, visible: open_visible, - }) = reuse_target { + }) = reuse_target + { let open_task = target_window .update(cx, |multi_workspace, window, cx| { window.activate_window(); @@ -11552,12 +11692,23 @@ pub fn open_paths( }); }); - Ok(OpenResult { window: target_window, workspace: target_workspace, opened_items: open_task }) + Ok(OpenResult { + window: target_window, + workspace: target_workspace, + opened_items: open_task, + }) } else { let init = if open_in_dev_container { - Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context| { - workspace.set_open_in_dev_container(true); - }) as Box) + Send>) + Some(Box::new( + |workspace: &mut Workspace, + _window: &mut Window, + _cx: &mut Context| { + workspace.set_open_in_dev_container(true); + }, + ) + as Box< + dyn FnOnce(&mut Workspace, &mut Window, &mut Context) + Send, + >) } else { None }; @@ -11576,7 +11727,8 @@ pub fn open_paths( .await; if let Ok(ref result) = result { - result.window + result + .window .update(cx, |_, window, _cx| { window.activate_window(); }) @@ -11584,40 +11736,7 @@ pub fn open_paths( } result - }; - - #[cfg(target_os = "windows")] - if let Some(util::paths::WslPath{distro, path}) = wsl_path - && let Ok(ref result) = result - { - result.window - .update(cx, move |multi_workspace, _window, cx| { - struct OpenInWsl; - let workspace = multi_workspace.workspace().clone(); - workspace.update(cx, |workspace, cx| { - workspace.show_notification(NotificationId::unique::(), cx, move |cx| { - let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy()); - let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote"); - cx.new(move |cx| { - MessageNotification::new(msg, cx) - .primary_message("Open in WSL") - .primary_icon(IconName::FolderOpen) - .primary_on_click(move |window, cx| { - window.dispatch_action(Box::new(remote::OpenWslPath { - distro: remote::WslConnectionOptions { - distro_name: distro.clone(), - user: None, - }, - paths: vec![path.clone().into()], - }), cx) - }) - }) - }); - }); - }) - .unwrap(); - }; - result + } }) } diff --git a/crates/worktree/src/worktree.rs b/crates/worktree/src/worktree.rs index 311853a7e41..785174ce14e 100644 --- a/crates/worktree/src/worktree.rs +++ b/crates/worktree/src/worktree.rs @@ -3333,6 +3333,15 @@ impl BackgroundScannerState { return Some(removed_entry.id); } + let existing_entry = self.snapshot.entry_for_path(path); + + // An excluded symlink can share this inode without representing a rename + if let Some(entry) = existing_entry + && entry.inode == inode + { + return Some(entry.id); + } + // If an entry with the same inode was removed from the worktree during this scan, // then it *might* represent the same file or directory. But the OS might also have // re-used the inode for a completely different file or directory. @@ -3344,7 +3353,7 @@ impl BackgroundScannerState { (removed_entry.mtime == Some(mtime) || *removed_entry.path == *path) .then_some(removed_entry.id) } else { - Some(self.snapshot.entry_for_path(path)?.id) + Some(existing_entry?.id) } } diff --git a/crates/worktree/tests/integration/worktree_tests.rs b/crates/worktree/tests/integration/worktree_tests.rs index d63a6b2405f..602eb8f75cc 100644 --- a/crates/worktree/tests/integration/worktree_tests.rs +++ b/crates/worktree/tests/integration/worktree_tests.rs @@ -89,6 +89,94 @@ async fn test_traversal(cx: &mut TestAppContext) { }) } +#[gpui::test] +async fn test_entry_id_is_reused_when_rename_overwrites_existing_path(cx: &mut TestAppContext) { + init_test(cx); + let result: Result<()> = async { + let fs = FakeFs::new(cx.background_executor.clone()); + fs.insert_tree( + path!("/root"), + json!({ + "destination.rs": "old destination", + "source.rs": "source", + }), + ) + .await; + let tree = Worktree::local( + Path::new(path!("/root")), + true, + fs.clone(), + Default::default(), + true, + WorktreeId::from_proto(0), + &mut cx.to_async(), + ) + .await?; + cx.run_until_parked(); + let (source_id, destination_id) = tree.read_with(cx, |tree, _| -> Result<_> { + let source = tree + .entry_for_path(rel_path("source.rs")) + .ok_or_else(|| anyhow::anyhow!("expected the source entry"))?; + let destination = tree + .entry_for_path(rel_path("destination.rs")) + .ok_or_else(|| anyhow::anyhow!("expected the destination entry"))?; + assert_ne!(source.inode, destination.inode); + Ok((source.id, destination.id)) + })?; + + // An explicit refresh leaves the overwritten entry in the snapshot until ID selection + fs.pause_events(); + fs.rename( + Path::new(path!("/root/source.rs")), + Path::new(path!("/root/destination.rs")), + fs::RenameOptions { + overwrite: true, + ..Default::default() + }, + ) + .await?; + tree.read_with(cx, |tree, _| -> Result<_> { + Ok(tree + .as_local() + .ok_or_else(|| anyhow::anyhow!("expected a local worktree"))? + .refresh_entries_for_paths(vec![ + rel_path("destination.rs").into(), + rel_path("source.rs").into(), + ])) + })? + .recv() + .await; + + tree.read_with(cx, |tree, _| -> Result<()> { + assert!(tree.entry_for_path(rel_path("source.rs")).is_none()); + assert!(tree.entry_for_id(destination_id).is_none()); + assert_eq!( + tree.entry_for_path(rel_path("destination.rs")) + .map(|entry| entry.id), + Some(source_id), + ); + tree.as_local() + .ok_or_else(|| anyhow::anyhow!("expected a local worktree"))? + .snapshot() + .check_invariants(false); + Ok(()) + })?; + + fs.flush_events(fs.buffered_event_count()); + cx.run_until_parked(); + assert_eq!( + tree.read_with(cx, |tree, _| { + tree.entry_for_path(rel_path("destination.rs")) + .map(|entry| entry.id) + }), + Some(source_id), + ); + Ok(()) + } + .await; + assert!(result.is_ok(), "{result:?}"); +} + #[gpui::test] async fn test_entry_id_is_reused_when_rename_events_are_split(cx: &mut TestAppContext) { init_test(cx); @@ -2644,6 +2732,143 @@ async fn test_file_scan_inclusions_reindexes_on_setting_change(cx: &mut TestAppC }); } +#[gpui::test] +async fn test_symlink_scanner_restart_excluding_external_directory(cx: &mut TestAppContext) { + let result = check_symlink_scanner_restart(cx, "../config/target", true).await; + assert!(result.is_ok(), "{result:?}"); +} + +#[gpui::test] +async fn test_symlink_scanner_restart_excluding_external_file(cx: &mut TestAppContext) { + let result = check_symlink_scanner_restart(cx, "../config/target", false).await; + assert!(result.is_ok(), "{result:?}"); +} + +#[gpui::test] +async fn test_symlink_scanner_restart_excluding_internal_directory(cx: &mut TestAppContext) { + let result = check_symlink_scanner_restart(cx, "config/target", true).await; + assert!(result.is_ok(), "{result:?}"); +} + +#[gpui::test] +async fn test_symlink_scanner_restart_excluding_internal_file(cx: &mut TestAppContext) { + let result = check_symlink_scanner_restart(cx, "config/target", false).await; + assert!(result.is_ok(), "{result:?}"); +} + +async fn check_symlink_scanner_restart( + cx: &mut TestAppContext, + target: &str, + is_directory: bool, +) -> Result<()> { + init_test(cx); + let fs = FakeFs::new(cx.background_executor.clone()); + let contents = if is_directory { + json!({ "child.rs": "" }) + } else { + json!("") + }; + fs.insert_tree( + "/parent", + json!({ + "config": { "target": contents }, + "worktree": { + "config": { "target": contents }, + "file.rs": "", + }, + }), + ) + .await; + fs.create_symlink(Path::new("/parent/worktree/link"), target.into()) + .await?; + + let tree = Worktree::local( + Path::new("/parent/worktree"), + true, + fs, + Default::default(), + true, + WorktreeId::from_proto(0), + &mut cx.to_async(), + ) + .await?; + cx.run_until_parked(); + + let original_entries = tree.read_with(cx, |tree, _| -> Result<_> { + let target = tree + .entry_for_path(rel_path("config/target")) + .ok_or_else(|| anyhow::anyhow!("expected the target entry"))?; + let link = tree + .entry_for_path(rel_path("link")) + .ok_or_else(|| anyhow::anyhow!("expected the symlink entry"))?; + if !link.is_external { + assert_eq!(link.inode, target.inode); + assert_eq!(link.mtime, target.mtime); + } + assert_ne!(link.id, target.id); + assert!(tree.entry_for_path(rel_path("file.rs")).is_some()); + Ok(tree + .entries(true, 0) + .map(|entry| (entry.path.clone(), entry.id)) + .collect::>()) + })?; + + tree.update(cx, |tree, cx| -> Result<()> { + tree.as_local_mut() + .ok_or_else(|| anyhow::anyhow!("expected a local worktree"))? + .share_private_files(cx); + Ok(()) + })?; + cx.run_until_parked(); + tree.read_with(cx, |tree, _| { + assert_eq!( + tree.entries(true, 0) + .map(|entry| (entry.path.clone(), entry.id)) + .collect::>(), + original_entries, + ); + }); + + cx.update(|cx| { + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.project.worktree.file_scan_exclusions = + Some(SplicingVec::from(vec!["**/link".to_string()])); + }); + }); + }); + cx.run_until_parked(); + + tree.read_with(cx, |tree, _| -> Result<()> { + tree.as_local() + .ok_or_else(|| anyhow::anyhow!("expected a local worktree"))? + .snapshot() + .check_invariants(false); + let expected_entries = original_entries + .iter() + .filter(|(path, _)| !path.starts_with(rel_path("link"))) + .cloned() + .collect::>(); + assert_eq!( + tree.entries(true, 0) + .map(|entry| (entry.path.clone(), entry.id)) + .collect::>(), + expected_entries, + ); + for (path, id) in &original_entries { + if path.starts_with(rel_path("link")) { + assert!(tree.entry_for_id(*id).is_none()); + } else { + assert_eq!( + tree.entry_for_id(*id).map(|entry| (&entry.path, entry.id)), + Some((path, *id)), + ); + } + } + Ok(()) + }) +} + #[gpui::test] async fn test_file_scan_exclusions(cx: &mut TestAppContext) { init_test(cx); diff --git a/crates/zed/src/zed.rs b/crates/zed/src/zed.rs index b4333c3922e..739202e348b 100644 --- a/crates/zed/src/zed.rs +++ b/crates/zed/src/zed.rs @@ -99,8 +99,8 @@ use vim_mode_setting::VimModeSetting; use workspace::notifications::{NotificationId, dismiss_app_notification, show_app_notification}; use workspace::{ - AppState, MultiWorkspace, NewFile, NewWindow, OpenLog, Panel, Toast, Workspace, - WorkspaceSettings, create_and_open_local_file, + AppState, MultiWorkspace, NewFile, NewWindow, OpenLog, OpenPathPromptMode, Panel, Toast, + Workspace, WorkspaceSettings, create_and_open_local_file, notifications::simple_message_notification::MessageNotification, open_new, }; use workspace::{CloseProject, CloseWindow, RestoreBanner, with_active_or_new_workspace}; @@ -1088,12 +1088,14 @@ fn register_actions( multiple: true, prompt: None, }, - action.create_new_window.unwrap_or_else(|| { - matches!( - WorkspaceSettings::get_global(cx).default_open_behavior, - DefaultOpenBehavior::NewWindow - ) - }), + if action.create_new_window.unwrap_or_else(|| { + WorkspaceSettings::get_global(cx).default_open_behavior + == DefaultOpenBehavior::NewWindow + }) { + OpenPathPromptMode::NewWindow + } else { + OpenPathPromptMode::CurrentWindow + }, window, cx, ); @@ -1109,7 +1111,13 @@ fn register_actions( multiple: true, prompt: None, }, - true, + if WorkspaceSettings::get_global(cx).default_open_behavior + == DefaultOpenBehavior::NewWindow + { + OpenPathPromptMode::NewWindow + } else { + OpenPathPromptMode::CurrentWindow + }, window, cx, ); @@ -1138,19 +1146,24 @@ fn register_actions( prompt: None, }, DirectoryLister::Project(workspace.project().clone()), + if create_new_window { + OpenPathPromptMode::NewWindow + } else { + OpenPathPromptMode::CurrentWindow + }, window, cx, ); cx.spawn_in(window, async move |this, cx| { - let Some(paths) = paths.await.log_err().flatten() else { + let Some(result) = paths.await.log_err().flatten() else { return; }; if let Some(task) = this .update_in(cx, |this, window, cx| { open_new_ssh_project_from_project( this, - paths, - create_new_window, + result.paths, + result.open_in_new_window, window, cx, ) @@ -2909,8 +2922,8 @@ mod tests { }; use workspace::MultiWorkspace; use workspace::{ - NewFile, OpenOptions, OpenVisible, SERIALIZATION_THROTTLE_TIME, SaveIntent, SplitDirection, - WorkspaceHandle, + NewFile, OpenOptions, OpenPathPromptResult, OpenVisible, SERIALIZATION_THROTTLE_TIME, + SaveIntent, SplitDirection, WorkspaceHandle, item::SaveOptions, item::{Item, ItemHandle}, open_new, open_paths, pane, @@ -3137,10 +3150,13 @@ mod tests { window .update(cx, |multi_workspace, window, cx| { multi_workspace.workspace().update(cx, |workspace, _cx| { - workspace.set_prompt_for_open_path(Box::new(|_, _, _, _| { + workspace.set_prompt_for_open_path(Box::new(|_, _, mode, _, _| { let (sender, receiver) = futures::channel::oneshot::channel(); sender - .send(Some(vec![PathBuf::from(path!("/other-project"))])) + .send(Some(OpenPathPromptResult { + paths: vec![PathBuf::from(path!("/other-project"))], + open_in_new_window: mode == OpenPathPromptMode::NewWindow, + })) .expect("path prompt receiver should be open"); receiver })); @@ -3165,6 +3181,38 @@ mod tests { executor.run_until_parked(); } + #[gpui::test] + async fn test_open_from_no_windows(cx: &mut TestAppContext) { + let app_state = init_test(cx); + app_state + .fs + .as_fake() + .insert_tree(path!("/root"), json!({ "file.txt": "" })) + .await; + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.workspace.use_system_path_prompts = Some(true); + settings.workspace.default_open_behavior = Some(DefaultOpenBehavior::NewWindow); + }); + }); + assert_eq!(cx.windows().len(), 0); + cx.update(|cx| cx.dispatch_action(&workspace::Open::default())); + cx.run_until_parked(); + cx.simulate_path_prompt_response(|_| Some(vec![PathBuf::from(path!("/root/file.txt"))])); + cx.run_until_parked(); + assert_eq!(cx.windows().len(), 1); + cx.windows()[0] + .downcast::() + .unwrap() + .update(cx, |multi_workspace, _, cx| { + assert_eq!( + multi_workspace.workspace().read(cx).open_item_abs_paths(cx), + vec![PathBuf::from(path!("/root/file.txt"))] + ); + }) + .unwrap(); + } + #[gpui::test] async fn test_open_paths_action(cx: &mut TestAppContext) { let app_state = init_test(cx); diff --git a/crates/zed/src/zed/open_listener.rs b/crates/zed/src/zed/open_listener.rs index 177e9538453..b89cd2158a3 100644 --- a/crates/zed/src/zed/open_listener.rs +++ b/crates/zed/src/zed/open_listener.rs @@ -21,6 +21,8 @@ use onboarding::show_onboarding_view; use recent_projects::{RemoteSettings, navigate_to_positions, open_remote_project}; use remote::{RemoteConnectionOptions, WslConnectionOptions}; use settings::Settings; +#[cfg(target_os = "windows")] +use std::path::{Component, Prefix}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::thread; @@ -162,9 +164,9 @@ impl OpenRequest { index: action_index.parse()?, }); } else if let Some(file) = url.strip_prefix("file://") { - this.parse_file_path(file) + this.parse_local_file_path(file) } else if let Some(file) = url.strip_prefix("zed://file") { - this.parse_file_path(file) + this.parse_local_file_path(file) } else if let Some(file) = url.strip_prefix("zed://ssh") { let ssh_url = "ssh:/".to_string() + file; this.parse_ssh_file_path(&ssh_url, cx)? @@ -220,6 +222,23 @@ impl OpenRequest { } } + fn parse_local_file_path(&mut self, file: &str) { + if let Some(decoded) = urlencoding::decode(file).log_err() { + // URL paths keep a `/` before a Windows drive letter (`/C:/x`), which Windows cannot open. + #[cfg(target_os = "windows")] + if let Some(path) = decoded.strip_prefix('/') + && matches!( + Path::new(path).components().next(), + Some(Component::Prefix(prefix)) if matches!(prefix.kind(), Prefix::Disk(_)) + ) + { + self.open_paths.push(path.to_owned()); + return; + } + self.open_paths.push(decoded.into_owned()) + } + } + fn parse_agent_url(&mut self, agent_path: &str) { // Format: "" or "?prompt=". let agent_path = agent_path.strip_prefix('/').unwrap_or(agent_path); @@ -298,8 +317,9 @@ impl OpenRequest { Some(urlencoding::decode(url.username())?.into_owned()) }; let port = url.port(); + // Refuse earlier local paths; earlier ssh paths are left to the connection check below. anyhow::ensure!( - self.open_paths.is_empty(), + self.open_paths.is_empty() || self.remote_connection.is_some(), "cannot open both local and ssh paths" ); let mut connection_options = @@ -967,7 +987,18 @@ async fn open_local_workspace( && !diff_paths.is_empty() && let Some(cwd) = cwd { - workspace_paths.push(cwd.to_string_lossy().to_string()); + // Avoid adding cwd as a root to the focused window with `--add`. + // Without a focused local window, retain cwd for workspace matching. + let add_to_active_window = open_options.workspace_matching + == workspace::WorkspaceMatching::MatchSubdirectory + && cx.update(|cx| { + let active_window = cx.active_window(); + workspace::workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx) + .any(|window| Some(window.into()) == active_window) + }); + if !add_to_active_window { + workspace_paths.push(cwd.to_string_lossy().to_string()); + } } let paths_with_position = @@ -1135,7 +1166,7 @@ mod tests { use session::Session; use std::{path::Path, sync::Arc, task::Poll}; use util::path; - use workspace::{AppState, MultiWorkspace}; + use workspace::{AppState, MultiWorkspace, Workspace}; struct DiscardResponseSink; @@ -1365,6 +1396,32 @@ mod tests { ); } + // The path part of `file://` and `zed://file` URLs starts with `/` before the drive letter, + // `/C:/root/test.txt` should be parsed as `C:/root/test.txt` + #[cfg(target_os = "windows")] + #[gpui::test] + fn test_parse_file_urls_with_drive_letter_on_windows(cx: &mut TestAppContext) { + let _app_state = init_test(cx); + + for (input, expected) in [ + ("zed://file/C:/root/test.txt:10", "C:/root/test.txt:10"), + ("zed://file/C%3A/root/test.txt", "C:/root/test.txt"), + ("file:///C:/root/test.txt", "C:/root/test.txt"), + ] { + let request = cx.update(|cx| { + OpenRequest::parse( + RawOpenRequest { + urls: vec![input.into()], + ..Default::default() + }, + cx, + ) + .unwrap() + }); + assert_eq!(request.open_paths, vec![expected], "{input}"); + } + } + #[gpui::test] fn test_parse_ssh_url_preserves_open_behavior(cx: &mut TestAppContext) { let _app_state = init_test(cx); @@ -1407,6 +1464,76 @@ mod tests { } } + #[gpui::test] + fn test_parse_ssh_urls_of_one_connection(cx: &mut TestAppContext) { + let _app_state = init_test(cx); + + let request = cx.update(|cx| { + OpenRequest::parse( + RawOpenRequest { + urls: vec![ + "ssh://me@host/project".into(), + "ssh://me@host/project/README.md".into(), + ], + ..Default::default() + }, + cx, + ) + .unwrap() + }); + assert_eq!( + request.remote_connection.unwrap(), + RemoteConnectionOptions::Ssh(SshConnectionOptions { + host: "host".into(), + username: Some("me".into()), + ..Default::default() + }) + ); + assert_eq!(request.open_paths, vec!["/project", "/project/README.md"]); + } + + #[gpui::test] + fn test_reject_ssh_urls_with_other_paths(cx: &mut TestAppContext) { + let _app_state = init_test(cx); + + for (wsl, urls, expected) in [ + ( + None, + ["file:///tmp/local", "ssh://me@host/project"], + "cannot open both local and ssh paths", + ), + ( + None, + ["ssh://me@host/project", "ssh://me@other/project"], + "cannot open multiple different remote connections", + ), + ( + None, + ["ssh://me@host/project", "ssh://you@host/project"], + "cannot open multiple different remote connections", + ), + ( + Some("Ubuntu"), + ["file:///home/me/project", "ssh://me@host/project"], + "cannot open multiple different remote connections", + ), + ] { + let error = cx + .update(|cx| { + OpenRequest::parse( + RawOpenRequest { + urls: urls.iter().map(|url| url.to_string()).collect(), + wsl: wsl.map(str::to_string), + ..Default::default() + }, + cx, + ) + }) + .unwrap_err(); + assert_eq!(error.to_string(), expected, "{urls:?}"); + } + } + #[gpui::test] fn test_open_options_for_behavior_always_new(cx: &mut TestAppContext) { let _app_state = init_test(cx); @@ -1938,6 +2065,138 @@ mod tests { .unwrap(); } + #[gpui::test] + async fn test_add_prefers_focused_window_and_active_workspace(cx: &mut TestAppContext) { + let app_state = init_test(cx); + app_state + .fs + .as_fake() + .insert_tree(path!("/root"), json!({ "project": {}, "other": {} })) + .await; + + for _ in 0..2 { + open_workspace_file( + path!("/root/project"), + workspace::OpenOptions { + workspace_matching: workspace::WorkspaceMatching::None, + ..Default::default() + }, + app_state.clone(), + cx, + ) + .await; + } + + let open_options = workspace::OpenOptions { + workspace_matching: workspace::WorkspaceMatching::MatchSubdirectory, + ..Default::default() + }; + assert_eq!(cx.windows().len(), 2); + for window in cx.windows() { + let window = window + .downcast::() + .expect("workspace window"); + let workspaces = window + .update(cx, |multi_workspace, window, cx| { + let original = multi_workspace.workspace().clone(); + multi_workspace.retain_active_workspace(cx); + let project = original.read(cx).project().clone(); + let added = + cx.new(|cx| Workspace::new(None, project, app_state.clone(), window, cx)); + [added, original] + }) + .expect("window exists"); + + for workspace in workspaces { + window + .update(cx, |multi_workspace, window, cx| { + multi_workspace.activate(workspace.clone(), None, window, cx); + window.activate_window(); + }) + .expect("window exists"); + + for paths in [ + vec![PathBuf::from(path!("/root/project"))], + vec![PathBuf::from(path!("/root/other"))], + vec![], + ] { + let target = workspace::find_existing_workspace( + &paths, + &open_options, + &project::ProjectHost::Local, + &mut cx.to_async(), + ) + .expect("existing local workspace"); + assert_eq!(target.window, window); + assert_eq!(target.workspace, workspace); + assert!(matches!(target.visible, workspace::OpenVisible::All)); + } + } + } + } + + #[gpui::test] + async fn test_add_diff_does_not_add_cwd_to_focused_workspace(cx: &mut TestAppContext) { + let app_state = init_test(cx); + app_state + .fs + .as_fake() + .insert_tree( + path!("/root"), + json!({ "project": {}, "cwd": { "before": "old", "after": "new" } }), + ) + .await; + open_workspace_file( + path!("/root/project"), + Default::default(), + app_state.clone(), + cx, + ) + .await; + let window = cx + .windows() + .pop() + .and_then(|window| window.downcast::()) + .expect("workspace window"); + window + .update(cx, |_, window, _| window.activate_window()) + .expect("window exists"); + + let errored = open_local_workspace( + vec![], + vec![[ + path!("/root/cwd/before").into(), + path!("/root/cwd/after").into(), + ]], + false, + workspace::OpenOptions { + workspace_matching: workspace::WorkspaceMatching::MatchSubdirectory, + ..Default::default() + }, + Some(PathBuf::from(path!("/root/cwd"))), + &DiscardResponseSink, + &app_state, + &mut cx.to_async(), + ) + .await; + + assert!(!errored); + assert_eq!(cx.windows().len(), 1); + window + .update(cx, |multi_workspace, _, cx| { + let workspace = multi_workspace.workspace().read(cx); + assert_eq!(workspace.items(cx).count(), 1); + let roots = workspace + .project() + .read(cx) + .visible_worktrees(cx) + .map(|worktree| worktree.read(cx).abs_path().to_path_buf()) + .collect::>(); + assert_eq!(roots, vec![PathBuf::from(path!("/root/project"))]); + }) + .expect("window exists"); + } + async fn open_workspace_file( path: &str, open_options: workspace::OpenOptions, diff --git a/docs/src/languages/javascript.md b/docs/src/languages/javascript.md index 54d320b1a72..16039dedb1b 100644 --- a/docs/src/languages/javascript.md +++ b/docs/src/languages/javascript.md @@ -235,11 +235,11 @@ Zed supports debugging JavaScript code out of the box with `vscode-js-debug`. The following can be debugged without writing additional configuration: - Tasks from `package.json` -- Tests written using several popular frameworks (Jest, Mocha, Vitest, Jasmine, Bun, Node) +- Tests written using several popular frameworks (Jest, Mocha, Vitest, Jasmine, Node) Run {#action debugger::Start} ({#kb debugger::Start}) to see a contextual list of these predefined [debug tasks](../debugger.md). -> **Note:** Bun test is automatically detected when `@types/bun` is present in `package.json`. +> **Note:** Bun test is automatically detected when `@types/bun` is present in `package.json`. Detected Bun tests can be run as tasks but not debugged, because `vscode-js-debug` does not support the WebKit Inspector Protocol that Bun uses. > **Note:** Node test is automatically detected when `@types/node` is present in `package.json` (requires Node.js 20+). diff --git a/docs/src/languages/typescript.md b/docs/src/languages/typescript.md index 0262129a609..9a3601e3954 100644 --- a/docs/src/languages/typescript.md +++ b/docs/src/languages/typescript.md @@ -240,11 +240,11 @@ Zed supports debugging TypeScript code out of the box with `vscode-js-debug`. The following can be debugged without writing additional configuration: - Tasks from `package.json` -- Tests written using several popular frameworks (Jest, Mocha, Vitest, Jasmine, Bun, Node) +- Tests written using several popular frameworks (Jest, Mocha, Vitest, Jasmine, Node) Run {#action debugger::Start} ({#kb debugger::Start}) to see a contextual list of these [predefined debug tasks](../debugger.md). -> **Note:** Bun test is automatically detected when `@types/bun` is present in `package.json`. +> **Note:** Bun test is automatically detected when `@types/bun` is present in `package.json`. Detected Bun tests can be run as tasks but not debugged, because `vscode-js-debug` does not support the WebKit Inspector Protocol that Bun uses. > **Note:** Node test is automatically detected when `@types/node` is present in `package.json` (requires Node.js 20+). diff --git a/docs/src/reference/cli.md b/docs/src/reference/cli.md index c906b46e94d..54fb56a606c 100644 --- a/docs/src/reference/cli.md +++ b/docs/src/reference/cli.md @@ -71,7 +71,9 @@ zed -n ~/projects/myproject ### `-a`, `--add` -Add paths to the currently focused workspace instead of opening a new window. When multiple workspace windows are open, files open in the focused window: +Add paths to an existing project, preferring a matching project and then the +focused window's active local project. Open a new window if no local project is +open: ```sh zed -a newfile.txt