diff --git a/Cargo.lock b/Cargo.lock index 37566884278..93c8d57e7a7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12201,6 +12201,7 @@ dependencies = [ "futures 0.3.34", "fuzzy", "gpui", + "menu", "picker", "project", "serde", 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/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/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/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/workspace.rs b/crates/workspace/src/workspace.rs index 437aea67289..bf1e482ae94 100644 --- a/crates/workspace/src/workspace.rs +++ b/crates/workspace/src/workspace.rs @@ -903,7 +903,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 +934,7 @@ fn prompt_and_open_paths( workspace, app_state, options, - create_new_window, + OpenPathPromptMode::SelectPath, window, cx, ); @@ -946,40 +950,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 +1081,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, ); }); @@ -1535,6 +1591,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 +1625,10 @@ type PromptForOpenPath = Box< dyn Fn( &mut Workspace, DirectoryLister, + OpenPathPromptMode, &mut Window, &mut Context, - ) -> oneshot::Receiver>>, + ) -> oneshot::Receiver>, >; #[derive(Default)] @@ -2166,6 +2236,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 +2435,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 +3548,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 +3581,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 +4213,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 +4449,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() @@ -7824,6 +7924,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, .. }) => { @@ -11447,10 +11571,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 = @@ -11523,11 +11643,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(); @@ -11561,12 +11682,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 }; @@ -11585,7 +11717,8 @@ pub fn open_paths( .await; if let Ok(ref result) = result { - result.window + result + .window .update(cx, |_, window, _cx| { window.activate_window(); }) @@ -11593,40 +11726,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/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);