Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
pickers: Add multi-select support (#59931)
Yash Patodkar94b6d377badf
diff --git a/assets/keymaps/specific-overrides-macos.json b/assets/keymaps/specific-overrides-macos.jsonindex e24dfb20517..f8e4e1fb06b 100644--- a/assets/keymaps/specific-overrides-macos.json+++ b/assets/keymaps/specific-overrides-macos.json@@ -28,6 +28,7 @@"use_key_equivalents": true,"bindings": {"cmd-shift-p": "file_finder::SelectPrevious",+ "tab": "picker::MultiSelectNext","cmd-j": "pane::SplitDown","cmd-k": "pane::SplitUp","cmd-h": "pane::SplitLeft",@@ -39,6 +40,7 @@"use_key_equivalents": true,"bindings": {"alt-cmd-f": "text_finder::ToProjectSearch",+ "tab": "picker::MultiSelectNext","alt-cmd-[": "text_finder::Fold","alt-cmd-]": "text_finder::Unfold","cmd-shift-enter": "text_finder::ToggleFoldAll",diff --git a/assets/keymaps/specific-overrides.json b/assets/keymaps/specific-overrides.jsonindex 2c4191089ab..0f622554f70 100644--- a/assets/keymaps/specific-overrides.json+++ b/assets/keymaps/specific-overrides.json@@ -25,6 +25,7 @@"context": "FileFinder || (FileFinder > Picker > Editor) || (FileFinder > Picker > menu)","bindings": {"ctrl-shift-p": "file_finder::SelectPrevious",+ "tab": "picker::MultiSelectNext","ctrl-j": "pane::SplitDown","ctrl-k": "pane::SplitUp","ctrl-h": "pane::SplitLeft",@@ -35,6 +36,7 @@"context": "TextFinder || (TextFinder > Picker > Editor) || (TextFinder > Picker > menu)","bindings": {"ctrl-alt-f": "text_finder::ToProjectSearch",+ "tab": "picker::MultiSelectNext","ctrl-j": "pane::SplitDown","ctrl-k": "pane::SplitUp","ctrl-h": "pane::SplitLeft",diff --git a/crates/file_finder/src/file_finder.rs b/crates/file_finder/src/file_finder.rsindex 1203e3dde02..f02fb677441 100644--- a/crates/file_finder/src/file_finder.rs+++ b/crates/file_finder/src/file_finder.rs@@ -1,5 +1,7 @@#[cfg(test)]mod file_finder_tests;+#[cfg(test)]+mod multi_select_tests;use futures::future::join_all;pub use open_path_prompt::OpenPathDelegate;@@ -276,6 +278,10 @@ impl FileFinder {) {self.picker.update(cx, |picker, cx| {let delegate = &mut picker.delegate;+ if !delegate.selected_matches.is_empty() {+ delegate.open_selected_in_one_split(split_direction, window, cx);+ return;+ }if let Some(workspace) = delegate.workspace.upgrade()&& let Some(m) = delegate.matches.get(delegate.selected_index()){@@ -361,6 +367,7 @@ pub struct FileFinderDelegate {latest_search_query: Option<FileSearchQuery>,currently_opened_path: Option<FoundPath>,matches: Matches,+ selected_matches: Vec<SelectedMatch>,selected_index: usize,has_changed_selected_index: bool,cancel_flag: Arc<AtomicBool>,@@ -459,6 +466,45 @@ impl Match {}}+/// Wrapper with Eq comparing the worktree-qualified path of file matches+#[derive(Clone)]+struct SelectedMatch(pub Match);++impl SelectedMatch {+ fn new(m: Match) -> Option<Self> {+ match m {+ Match::History { .. } | Match::Search(_) => Some(Self(m)),+ Match::Channel { .. } | Match::CreateNew(_) => None,+ }+ }+}++impl PartialEq for SelectedMatch {+ fn eq(&self, other: &Self) -> bool {+ *self == other.0+ }+}++impl Eq for SelectedMatch {}++impl PartialEq<Match> for SelectedMatch {+ fn eq(&self, other: &Match) -> bool {+ match (&self.0, other) {+ (Match::History { path: a, .. }, Match::History { path: b, .. }) => {+ a.project == b.project+ }+ (Match::Search(a), Match::Search(b)) => {+ a.0.worktree_id == b.0.worktree_id && a.0.path == b.0.path+ }+ (Match::History { path: h, .. }, Match::Search(s))+ | (Match::Search(s), Match::History { path: h, .. }) => {+ h.project.worktree_id.to_usize() == s.0.worktree_id && h.project.path == s.0.path+ }+ _ => false,+ }+ }+}+impl Matches {fn len(&self) -> usize {self.matches.len()@@ -927,6 +973,7 @@ impl FileFinderDelegate {latest_search_query: None,currently_opened_path,matches: Matches::default(),+ selected_matches: Vec::new(),has_changed_selected_index: false,selected_index: 0,cancel_flag: Arc::new(AtomicBool::new(false)),@@ -958,6 +1005,22 @@ impl FileFinderDelegate {.detach();}+ fn prepend_selected_matches(&mut self) {+ if self.selected_matches.is_empty() {+ return;+ }+ self.matches+ .matches+ .retain(|m| !self.selected_matches.iter().any(|selected| selected == m));+ let mut new: Vec<Match> = self+ .selected_matches+ .iter()+ .map(|selected| selected.0.clone())+ .collect();+ new.append(&mut self.matches.matches);+ self.matches.matches = new;+ }+fn spawn_search(&mut self,query: FileSearchQuery,@@ -1160,14 +1223,20 @@ impl FileFinderDelegate {}}- self.selected_index = selected_match.map_or_else(- || self.calculate_selected_index(cx),- |m| {- self.matches- .position(&m, self.currently_opened_path.as_ref())- .unwrap_or(0)- },- );+ self.prepend_selected_matches();++ self.selected_index = if !self.selected_matches.is_empty() {+ 0+ } else {+ selected_match.map_or_else(+ || self.calculate_selected_index(cx),+ |m| {+ self.matches+ .position(&m, self.currently_opened_path.as_ref())+ .unwrap_or(0)+ },+ )+ };self.latest_search_query = Some(query);self.latest_search_did_cancel = did_cancel;@@ -1458,6 +1527,21 @@ impl FileFinderDelegate {let Some(m) = self.matches.get(self.selected_index()).cloned() else {return;};+ let allow_preview = PreviewTabsSettings::get_global(cx).enable_preview_from_file_finder;+ self.open_match(m, secondary, dismiss_after_open, allow_preview, window, cx);+ }++ /// `allow_preview` is forced off for batch opens so every file gets its+ /// own tab instead of consecutive opens reusing one preview tab.+ fn open_match(+ &mut self,+ m: Match,+ secondary: bool,+ dismiss_after_open: bool,+ allow_preview: bool,+ window: &mut Window,+ cx: &mut Context<Picker<FileFinderDelegate>>,+ ) {let Some(workspace) = self.workspace.upgrade() else {return;};@@ -1480,8 +1564,6 @@ impl FileFinderDelegate {project_path,window: &mut Window,cx: &mut Context<Workspace>| {- let allow_preview =- PreviewTabsSettings::get_global(cx).enable_preview_from_file_finder;if secondary {workspace.split_path_preview(project_path, allow_preview, None, window, cx)} else {@@ -1596,6 +1678,59 @@ impl FileFinderDelegate {) {self.open_selected_file(false, false, window, cx);}++ /// Opens every multi-selected file as a tab in a single new split, then+ /// dismisses the finder.+ fn open_selected_in_one_split(+ &mut self,+ split_direction: SplitDirection,+ window: &mut Window,+ cx: &mut Context<Picker<FileFinderDelegate>>,+ ) {+ let Some(workspace) = self.workspace.upgrade() else {+ return;+ };+ let selected = std::mem::take(&mut self.selected_matches);+ let paths: Vec<ProjectPath> = 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() {+ return;+ }+ 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);+ }+ });+ // Deferred because this runs from a `FileFinder` action handler, so+ // the entity is already being updated.+ let finder = self.file_finder.clone();+ cx.defer(move |cx| {+ finder.update(cx, |_, cx| cx.emit(DismissEvent)).log_err();+ });+ }}fn full_path_budget(@@ -1756,6 +1891,7 @@ impl PickerDelegate for FileFinderDelegate {self.first_update = false;self.selected_index = 0;}+ self.prepend_selected_matches();cx.notify();self.search_in_flight.store(false, atomic::Ordering::Release);@@ -1806,6 +1942,64 @@ impl PickerDelegate for FileFinderDelegate {self.open_selected_file(secondary, true, window, cx);}+ fn supports_multi_select(&self) -> bool {+ true+ }++ fn is_item_selected(&self, ix: usize) -> bool {+ let Some(m) = self.matches.get(ix) else {+ return false;+ };+ self.selected_matches.iter().any(|selected| selected == m)+ }++ fn toggle_item_selected(+ &mut self,+ ix: usize,+ _window: &mut Window,+ cx: &mut Context<Picker<FileFinderDelegate>>,+ ) {+ let Some(m) = self.matches.get(ix).cloned() else {+ return;+ };+ // `new` rejects channels and the `create-new` placeholder.+ let Some(selected) = SelectedMatch::new(m) else {+ return;+ };+ if let Some(position) = self+ .selected_matches+ .iter()+ .position(|existing| *existing == selected)+ {+ self.selected_matches.remove(position);+ } else {+ self.selected_matches.push(selected);+ }+ cx.notify();+ }++ fn selected_item_count(&self) -> usize {+ self.selected_matches.len()+ }++ fn clear_selection(&mut self, _cx: &mut Context<Picker<FileFinderDelegate>>) {+ self.selected_matches.clear();+ }++ fn confirm_multi(+ &mut self,+ secondary: bool,+ window: &mut Window,+ cx: &mut Context<Picker<FileFinderDelegate>>,+ ) {+ let selected = std::mem::take(&mut self.selected_matches);+ let count = selected.len();+ for (i, selected_match) in selected.into_iter().enumerate() {+ let is_last = i + 1 == count;+ self.open_match(selected_match.0, secondary, is_last, false, window, cx);+ }+ }+fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<FileFinderDelegate>>) {self.file_finder.update(cx, |_, cx| cx.emit(DismissEvent))@@ -1906,6 +2100,11 @@ impl PickerDelegate for FileFinderDelegate {_window: &mut Window,_cx: &mut Context<Picker<Self>>,) -> Vec<picker::PickerAction> {+ let open_label: SharedString = if self.selected_matches.len() > 1 {+ "Open multiple".into()+ } else {+ "Open File".into()+ };vec![picker::PickerAction::header("Split…"),picker::PickerAction::button("Left", pane::SplitLeft::default().boxed_clone()),@@ -1913,7 +2112,7 @@ impl PickerDelegate for FileFinderDelegate {picker::PickerAction::button("Up", pane::SplitUp::default().boxed_clone()),picker::PickerAction::button("Down", pane::SplitDown::default().boxed_clone()),picker::PickerAction::separator(),- picker::PickerAction::button("Open File", menu::Confirm.boxed_clone()),+ picker::PickerAction::button(open_label, menu::Confirm.boxed_clone()),]}}diff --git a/crates/file_finder/src/file_finder_tests.rs b/crates/file_finder/src/file_finder_tests.rsindex f3d63a09ee6..9dfdf6c08c1 100644--- a/crates/file_finder/src/file_finder_tests.rs+++ b/crates/file_finder/src/file_finder_tests.rs@@ -4477,7 +4477,7 @@ async fn open_queried_buffer(history_items}-fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {+pub(crate) fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {cx.update(|cx| {let state = AppState::test(cx);theme_settings::init(theme::LoadThemes::JustBase, cx);@@ -4507,7 +4507,7 @@ fn build_find_picker(}#[track_caller]-fn open_file_picker(+pub(crate) fn open_file_picker(workspace: &Entity<Workspace>,cx: &mut VisualTestContext,) -> Entity<Picker<FileFinderDelegate>> {@@ -4529,7 +4529,7 @@ fn simulate_input(cx: &mut VisualTestContext, input: &str) {}#[track_caller]-fn active_file_picker(+pub(crate) fn active_file_picker(workspace: &Entity<Workspace>,cx: &mut VisualTestContext,) -> Entity<Picker<FileFinderDelegate>> {diff --git a/crates/file_finder/src/multi_select_tests.rs b/crates/file_finder/src/multi_select_tests.rsnew file mode 100644index 00000000000..d7e39ae7548--- /dev/null+++ b/crates/file_finder/src/multi_select_tests.rs@@ -0,0 +1,294 @@+//! Tests for multi-selecting files in the file finder: toggling items in and+//! out of the selection, pinning the selection to the top across query+//! changes, and the various ways of opening the whole selection.++use gpui::{BorrowAppContext, Entity, TestAppContext, VisualTestContext};+use picker::{MultiSelectNext, Picker, PickerDelegate as _};+use pretty_assertions::assert_eq;+use project::Project;+use serde_json::json;+use settings::SettingsStore;+use util::path;+use workspace::{MultiWorkspace, Workspace, pane};++use crate::file_finder_tests::{self, open_file_picker};+use crate::{FileFinder, FileFinderDelegate, SEARCH_DEBOUNCE};++struct TestContext {+ picker: Entity<Picker<FileFinderDelegate>>,+ workspace: Entity<Workspace>,+ cx: VisualTestContext,+}++impl TestContext {+ /// The test tree is `a.rs`, `b.rs` and `c.rs` in the worktree root.+ /// Preview tabs from the file finder are enabled to verify that batch+ /// opens produce real tabs regardless.+ async fn new(cx: &mut TestAppContext) -> TestContext {+ let app_state = file_finder_tests::init_test(cx);+ cx.update(|cx| {+ cx.update_global::<SettingsStore, _>(|store, cx| {+ store.update_user_settings(cx, |settings| {+ settings+ .preview_tabs+ .get_or_insert_default()+ .enable_preview_from_file_finder = Some(true);+ });+ })+ });+ app_state+ .fs+ .as_fake()+ .insert_tree(+ path!("/root"),+ json!({+ "a.rs": "// a",+ "b.rs": "// b",+ "c.rs": "// c",+ }),+ )+ .await;+ let project = Project::test(app_state.fs.clone(), [path!("/root").as_ref()], cx).await;+ let window =+ cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));+ let workspace = window+ .read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone())+ .unwrap();+ let mut cx = VisualTestContext::from_window(window.into(), cx);+ let picker = open_file_picker(&workspace, &mut cx);+ TestContext {+ picker,+ workspace,+ cx,+ }+ }++ fn reopen_finder(&mut self) {+ self.picker = open_file_picker(&self.workspace, &mut self.cx);+ }++ fn search(&mut self, query: &str) {+ self.picker.update_in(&mut self.cx, |picker, window, cx| {+ picker.set_query(query, window, cx)+ });+ self.cx.executor().advance_clock(SEARCH_DEBOUNCE);+ self.cx.run_until_parked();+ }++ fn select(&mut self, file_name: &str) {+ let index = self.index_of(file_name);+ self.picker.update_in(&mut self.cx, |picker, window, cx| {+ picker.delegate.set_selected_index(index, window, cx);+ });+ self.cx.dispatch_action(MultiSelectNext);+ self.cx.run_until_parked();+ }++ fn deselect(&mut self, file_name: &str) {+ let index = self.index_of(file_name);+ self.picker.update_in(&mut self.cx, |picker, window, cx| {+ picker.delegate.toggle_item_selected(index, window, cx);+ });+ self.cx.run_until_parked();+ }++ fn confirm(&mut self) {+ self.cx.dispatch_action(menu::Confirm);+ self.cx.run_until_parked();+ }++ fn secondary_confirm(&mut self) {+ self.cx.dispatch_action(menu::SecondaryConfirm);+ self.cx.run_until_parked();+ }++ fn split_right(&mut self) {+ self.cx.dispatch_action(pane::SplitRight::default());+ self.cx.run_until_parked();+ }++ fn index_of(&mut self, file_name: &str) -> usize {+ self.picker.update(&mut self.cx, |picker, _| {+ picker+ .delegate+ .matches+ .matches+ .iter()+ .position(|m| {+ m.relative_path()+ .is_some_and(|path| path.file_name() == Some(file_name))+ })+ .unwrap_or_else(|| panic!("{file_name} is not in the match list"))+ })+ }++ fn match_names(&mut self) -> Vec<String> {+ self.picker.update(&mut self.cx, |picker, _| {+ picker+ .delegate+ .matches+ .matches+ .iter()+ .filter_map(|m| Some(m.relative_path()?.file_name()?.to_owned()))+ .collect()+ })+ }++ #[track_caller]+ fn assert_selected(&mut self, expected: &[&str]) {+ let selected: Vec<String> = self.picker.update(&mut self.cx, |picker, _| {+ picker+ .delegate+ .selected_matches+ .iter()+ .filter_map(|selected| Some(selected.0.relative_path()?.file_name()?.to_owned()))+ .collect()+ });+ assert_eq!(selected, expected, "wrong files selected");+ }++ #[track_caller]+ fn assert_finder_closed(&mut self) {+ let finder_open = self.workspace.update(&mut self.cx, |workspace, cx| {+ workspace.active_modal::<FileFinder>(cx).is_some()+ });+ assert!(!finder_open, "the finder should have been dismissed");+ }++ #[track_caller]+ fn assert_active_pane_items(&mut self, expected: &[&str]) {+ let mut items = self.pane_item_names(+ &self+ .workspace+ .read_with(&self.cx, |workspace, _| workspace.active_pane().clone()),+ );+ let mut expected: Vec<String> = expected.iter().map(|name| name.to_string()).collect();+ items.sort();+ expected.sort();+ assert_eq!(items, expected, "wrong items in the active pane");+ }++ fn pane_item_names(&mut self, pane: &Entity<pane::Pane>) -> Vec<String> {+ pane.read_with(&self.cx, |pane, cx| {+ pane.items()+ .filter_map(|item| Some(item.project_path(cx)?.path.file_name()?.to_owned()))+ .collect()+ })+ }++ fn pane_count(&mut self) -> usize {+ self.workspace+ .read_with(&self.cx, |workspace, _| workspace.panes().len())+ }+}++#[gpui::test]+async fn open_selection_as_tabs(cx: &mut TestAppContext) {+ let mut cx = TestContext::new(cx).await;++ cx.search("rs");+ cx.select("b.rs");+ cx.select("c.rs");+ cx.assert_selected(&["b.rs", "c.rs"]);++ cx.confirm();+ cx.assert_finder_closed();+ // Both files must open as real tabs even though preview tabs from the+ // file finder are enabled; a batch open must not reuse one preview tab.+ cx.assert_active_pane_items(&["b.rs", "c.rs"]);+}++#[gpui::test]+async fn tabbing_a_selected_row_deselects_it(cx: &mut TestAppContext) {+ let mut cx = TestContext::new(cx).await;++ cx.search("rs");+ cx.select("b.rs");+ cx.select("c.rs");+ cx.select("b.rs");+ cx.assert_selected(&["c.rs"]);+}++#[gpui::test]+async fn selection_pins_to_top_across_queries(cx: &mut TestAppContext) {+ let mut cx = TestContext::new(cx).await;++ cx.search("c");+ cx.select("c.rs");++ // `c.rs` doesn't match the new query, but stays selected and pinned to+ // the top of the results.+ cx.search("b");+ cx.assert_selected(&["c.rs"]);+ assert_eq!(cx.match_names(), ["c.rs", "b.rs"]);+}++#[gpui::test]+async fn deselecting_survives_queries(cx: &mut TestAppContext) {+ let mut cx = TestContext::new(cx).await;++ cx.search("c");+ cx.select("c.rs");++ cx.search("b");+ cx.deselect("c.rs");+ cx.assert_selected(&[]);++ // A deselected file must not come back selected or pinned on requery.+ cx.search("a");+ cx.assert_selected(&[]);+ assert_eq!(cx.match_names(), ["a.rs"]);+}++#[gpui::test]+async fn create_new_file_row_is_not_selectable(cx: &mut TestAppContext) {+ let mut cx = TestContext::new(cx).await;++ // A query matching nothing produces only the "create new" row.+ cx.search("zzz");+ cx.picker.update_in(&mut cx.cx, |picker, window, cx| {+ picker.delegate.set_selected_index(0, window, cx);+ });+ cx.cx.dispatch_action(MultiSelectNext);+ cx.cx.run_until_parked();+ cx.assert_selected(&[]);+}++#[gpui::test]+async fn open_selection_in_one_split(cx: &mut TestAppContext) {+ let mut cx = TestContext::new(cx).await;++ cx.search("rs");+ cx.select("b.rs");+ cx.select("c.rs");++ cx.split_right();+ cx.assert_finder_closed();+ // One new pane holding both files as tabs, not one pane per file.+ assert_eq!(cx.pane_count(), 2);+ cx.assert_active_pane_items(&["b.rs", "c.rs"]);+}++#[gpui::test]+async fn secondary_confirm_opens_one_split_per_file(cx: &mut TestAppContext) {+ let mut cx = TestContext::new(cx).await;++ // Open a file normally first so the workspace has a non-empty pane to+ // split off from.+ cx.search("a");+ cx.confirm();+ cx.assert_active_pane_items(&["a.rs"]);++ cx.reopen_finder();+ cx.search("rs");+ cx.select("b.rs");+ cx.select("c.rs");++ cx.secondary_confirm();+ cx.assert_finder_closed();+ assert_eq!(+ cx.pane_count(),+ 3,+ "each selected file opens in its own split"+ );+}diff --git a/crates/picker/src/footer.rs b/crates/picker/src/footer.rsindex a91ec6b5b4e..6c0d8c8bb00 100644--- a/crates/picker/src/footer.rs+++ b/crates/picker/src/footer.rs@@ -8,6 +8,7 @@ use crate::PickerDelegate;use crate::SetPreviewBelow;use crate::SetPreviewRight;use crate::ToggleActionsMenu;+use crate::ToggleMultiSelect;use crate::TogglePreview;use crate::preview;@@ -97,7 +98,18 @@ impl<D: PickerDelegate> Picker<D> {window: &mut Window,cx: &mut Context<Self>,) -> Option<AnyElement> {- let actions = self.delegate.actions_menu(window, cx);+ let mut actions = self.delegate.actions_menu(window, cx);+ // The multi-select entry is picker-owned so it can reflect the mode,+ // which delegates don't know about.+ if self.delegate.supports_multi_select() {+ if !actions.is_empty() {+ actions.push(PickerAction::separator());+ }+ actions.push(+ PickerAction::button("Multi Select", ToggleMultiSelect.boxed_clone())+ .toggled(self.select_instead_of_open),+ );+ }if self.preview.is_none() && actions.is_empty() {return None;}diff --git a/crates/picker/src/picker.rs b/crates/picker/src/picker.rsindex c74e78f1e84..dbc8f221607 100644--- a/crates/picker/src/picker.rs+++ b/crates/picker/src/picker.rs@@ -75,6 +75,13 @@ actions!(ToggleActionsMenu,/// Take the picker's content and open it in a multibufferToMultiBuffer,+ /// Toggles multi-select mode, in which clicking items adds them to+ /// the selection instead of opening them+ ToggleMultiSelect,+ /// Toggles the current item in the multi-selection and advances to+ /// the next item, starting multi-select mode if it isn't already+ /// active+ MultiSelectNext,]);@@ -123,6 +130,7 @@ pub struct Picker<D: PickerDelegate> {preview: Option<Preview>,pending_update_matches: Option<PendingUpdateMatches>,confirm_on_update: Option<bool>,+ select_instead_of_open: bool,shape: shape::Shape,/// The size the picker opens at (and resets to). Defaults depend on whether/// the picker has a preview; see [`Picker::initial_width`] / [`Picker::max_height`].@@ -236,6 +244,41 @@ pub trait PickerDelegate: Sized + 'static {None}fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>);+ /// Whether this delegate supports selecting multiple items at once. When+ /// `true`, the delegate owns the multi-selection state; the picker only+ /// drives the generic UX (toggle action, indicator, click routing).+ fn supports_multi_select(&self) -> bool {+ false+ }+ /// Whether the item at `ix` is part of the current multi-selection.+ fn is_item_selected(&self, _ix: usize) -> bool {+ false+ }+ /// Toggle whether the item at `ix` is part of the multi-selection. Items+ /// that cannot participate in multi-selection (e.g. non-file entries)+ /// should leave the selection unchanged.+ fn toggle_item_selected(+ &mut self,+ _ix: usize,+ _window: &mut Window,+ _cx: &mut Context<Picker<Self>>,+ ) {+ }+ /// Number of items currently in the multi-selection.+ fn selected_item_count(&self) -> usize {+ 0+ }+ /// Clear the multi-selection.+ fn clear_selection(&mut self, _cx: &mut Context<Picker<Self>>) {}+ /// Open every item in the multi-selection. Called on confirm when the+ /// selection is non-empty; implementations should clear the selection.+ fn confirm_multi(+ &mut self,+ _secondary: bool,+ _window: &mut Window,+ _cx: &mut Context<Picker<Self>>,+ ) {+ }/// Instead of interacting with currently selected entry, treats editor input literally,/// performing some kind of action on it.fn confirm_input(@@ -528,6 +571,7 @@ impl<D: PickerDelegate> Picker<D> {element_container,pending_update_matches: None,confirm_on_update: None,+ select_instead_of_open: false,preview,shape_loaded_from_persistence: persisted_shape.is_some(),shape: persisted_shape.unwrap_or_else(|| {@@ -864,11 +908,48 @@ impl<D: PickerDelegate> Picker<D> {pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {if self.delegate.should_dismiss() {+ self.select_instead_of_open = false;+ self.delegate.clear_selection(cx);self.delegate.dismissed(window, cx);cx.emit(DismissEvent);}}+ fn toggle_multi_select(+ &mut self,+ _: &ToggleMultiSelect,+ _window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ if !self.delegate.supports_multi_select() {+ return;+ }+ self.select_instead_of_open = !self.select_instead_of_open;+ if !self.select_instead_of_open {+ self.delegate.clear_selection(cx);+ }+ cx.notify();+ }++ fn multi_select_next(+ &mut self,+ _: &MultiSelectNext,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ // Propagate so `tab` retains its other meanings (e.g.+ // `ConfirmCompletion`) in pickers without multi-select.+ if !self.delegate.supports_multi_select() {+ cx.propagate();+ return;+ }+ self.select_instead_of_open = true;+ let ix = self.delegate.selected_index();+ self.delegate.toggle_item_selected(ix, window, cx);+ self.select_next(&menu::SelectNext, window, cx);+ cx.notify();+ }+fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {if self.pending_update_matches.is_some()&& !self.delegate.finalize_update_matches(@@ -971,11 +1052,20 @@ impl<D: PickerDelegate> Picker<D> {return;}self.set_selected_index(ix, None, false, window, cx);- self.do_confirm(secondary, window, cx)+ if self.delegate.supports_multi_select() && (secondary || self.select_instead_of_open) {+ self.select_instead_of_open = true;+ self.delegate.toggle_item_selected(ix, window, cx);+ cx.notify();+ } else {+ self.do_confirm(secondary, window, cx);+ }}fn do_confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Self>) {- if let Some(update_query) = self.delegate.confirm_update_query(window, cx) {+ if self.delegate.supports_multi_select() && self.delegate.selected_item_count() > 0 {+ self.select_instead_of_open = false;+ self.delegate.confirm_multi(secondary, window, cx);+ } else if let Some(update_query) = self.delegate.confirm_update_query(window, cx) {self.set_query(&update_query, window, cx);self.set_selected_index(0, Some(Direction::Down), false, window, cx);} else {@@ -1169,9 +1259,16 @@ impl<D: PickerDelegate> Picker<D> {let selectable =ix < self.delegate.match_count() && self.delegate.can_select(ix, window, cx);+ let supports_multi_select = self.delegate.supports_multi_select();+ let is_multi_selected = supports_multi_select && self.delegate.is_item_selected(ix);+ let multi_select_active = supports_multi_select && self.select_instead_of_open;+div().id(("item", ix)).when(selectable, |this| this.cursor_pointer())+ .when(selectable && multi_select_active, |this| {+ this.hover(|s| s.bg(cx.theme().colors().ghost_element_hover))+ }).child(canvas(move |bounds, _window, _cx| {@@ -1212,12 +1309,35 @@ impl<D: PickerDelegate> Picker<D> {}}))})- .children(self.delegate.render_match(- ix,- ix == self.delegate.selected_index(),- window,- cx,- ))+ .map(|row| {+ // Pickers without multi-select keep their element tree+ // unchanged.+ if supports_multi_select {+ row.child(+ h_flex()+ // Headers and separators cannot be part of the+ // selection, so they get no indicator.+ .when(multi_select_active && selectable, |this| {+ this.child(+ self.render_multi_select_indicator(is_multi_selected, cx),+ )+ })+ .children(self.delegate.render_match(+ ix,+ ix == self.delegate.selected_index(),+ window,+ cx,+ )),+ )+ } else {+ row.children(self.delegate.render_match(+ ix,+ ix == self.delegate.selected_index(),+ window,+ cx,+ ))+ }+ }).when(self.delegate.separators_after_indices().contains(&ix),|picker| {@@ -1229,6 +1349,41 @@ impl<D: PickerDelegate> Picker<D> {)}+ /// The checkbox in front of items while in multi-select mode.+ fn render_multi_select_indicator(+ &self,+ is_selected: bool,+ cx: &mut Context<Self>,+ ) -> impl IntoElement {+ h_flex()+ .w_6()+ .flex_none()+ .justify_center()+ .items_center()+ .child(+ div()+ .size_4()+ .flex_none()+ .rounded_sm()+ .border_1()+ .border_color(if is_selected {+ cx.theme().colors().border_focused+ } else {+ cx.theme().colors().border+ })+ .flex()+ .items_center()+ .justify_center()+ .when(is_selected, |this| {+ this.bg(cx.theme().colors().element_selected).child(+ Icon::new(IconName::Check)+ .size(IconSize::Small)+ .color(Color::Accent),+ )+ }),+ )+ }+fn render_element_container(&self, cx: &mut Context<Self>) -> impl IntoElement {// When the picker shrinks to fit its content, the list infers its size// from its items. When it fills its full height (preview visible), the@@ -1365,6 +1520,9 @@ mod tests {items: Vec<bool>,selected_index: usize,confirmed_index: Rc<Cell<Option<usize>>>,+ supports_multi_select: bool,+ selected_items: Vec<usize>,+ multi_confirmed: Rc<Cell<Option<Vec<usize>>>>,}impl TestDelegate {@@ -1373,8 +1531,16 @@ mod tests {items,selected_index: 0,confirmed_index: Rc::new(Cell::new(None)),+ supports_multi_select: false,+ selected_items: Vec::new(),+ multi_confirmed: Rc::new(Cell::new(None)),}}++ fn with_multi_select(mut self) -> Self {+ self.supports_multi_select = true;+ self+ }}impl PickerDelegate for TestDelegate {@@ -1432,6 +1598,45 @@ mod tests {self.confirmed_index.set(Some(self.selected_index));}+ fn supports_multi_select(&self) -> bool {+ self.supports_multi_select+ }++ fn is_item_selected(&self, ix: usize) -> bool {+ self.selected_items.contains(&ix)+ }++ fn toggle_item_selected(+ &mut self,+ ix: usize,+ _window: &mut Window,+ _cx: &mut Context<Picker<Self>>,+ ) {+ if let Some(position) = self.selected_items.iter().position(|&item| item == ix) {+ self.selected_items.remove(position);+ } else {+ self.selected_items.push(ix);+ }+ }++ fn selected_item_count(&self) -> usize {+ self.selected_items.len()+ }++ fn clear_selection(&mut self, _cx: &mut Context<Picker<Self>>) {+ self.selected_items.clear();+ }++ fn confirm_multi(+ &mut self,+ _secondary: bool,+ _window: &mut Window,+ _cx: &mut Context<Picker<Self>>,+ ) {+ self.multi_confirmed+ .set(Some(std::mem::take(&mut self.selected_items)));+ }+fn dismissed(&mut self, _window: &mut Window, _cx: &mut Context<Picker<Self>>) {}fn render_match(@@ -1526,6 +1731,139 @@ mod tests {);});}++ #[gpui::test]+ async fn test_multi_select_mode_routes_clicks(cx: &mut TestAppContext) {+ init_test(cx);++ let confirmed_index = Rc::new(Cell::new(None));+ let multi_confirmed = Rc::new(Cell::new(None));+ let (picker, cx) = cx.add_window_view(|window, cx| {+ let mut delegate = TestDelegate::new(vec![true, true, true]).with_multi_select();+ delegate.confirmed_index = confirmed_index.clone();+ delegate.multi_confirmed = multi_confirmed.clone();+ Picker::uniform_list(delegate, window, cx)+ });++ // A plain click confirms just like in any picker.+ picker.update_in(cx, |picker, window, cx| {+ picker.handle_click(1, false, window, cx);+ });+ assert_eq!(confirmed_index.take(), Some(1));+ picker.update(cx, |picker, _cx| {+ assert_eq!(picker.delegate.selected_item_count(), 0);+ });++ // A secondary (cmd) click starts multi-select mode and toggles the+ // clicked item into the selection instead of confirming.+ picker.update_in(cx, |picker, window, cx| {+ picker.handle_click(2, true, window, cx);+ });+ assert_eq!(confirmed_index.take(), None, "cmd+click must not confirm");+ picker.update(cx, |picker, _cx| {+ assert!(+ picker.select_instead_of_open,+ "cmd+click should start multi-select mode"+ );+ assert!(picker.delegate.is_item_selected(2));+ });++ // While the mode is on, plain clicks toggle items too.+ picker.update_in(cx, |picker, window, cx| {+ picker.handle_click(0, false, window, cx);+ });+ assert_eq!(+ confirmed_index.take(),+ None,+ "in-mode clicks must not confirm"+ );+ picker.update(cx, |picker, _cx| {+ assert!(picker.delegate.is_item_selected(0));+ assert!(picker.delegate.is_item_selected(2));+ assert!(!picker.delegate.is_item_selected(1));+ });++ // Confirming opens the whole selection and exits the mode.+ picker.update_in(cx, |picker, window, cx| {+ picker.do_confirm(false, window, cx);+ });+ assert_eq!(multi_confirmed.take(), Some(vec![2, 0]));+ picker.update_in(cx, |picker, window, cx| {+ picker.handle_click(1, false, window, cx);+ });+ assert_eq!(+ confirmed_index.take(),+ Some(1),+ "the mode should be off again after confirming"+ );+ }++ #[gpui::test]+ async fn test_multi_select_next_starts_multi_select_mode(cx: &mut TestAppContext) {+ init_test(cx);++ let (picker, cx) = cx.add_window_view(|window, cx| {+ Picker::uniform_list(+ TestDelegate::new(vec![true, true, true]).with_multi_select(),+ window,+ cx,+ )+ });++ picker.update_in(cx, |picker, window, cx| {+ picker.multi_select_next(&MultiSelectNext, window, cx);+ });+ picker.update(cx, |picker, _cx| {+ assert!(+ picker.select_instead_of_open,+ "selecting an item should start multi-select mode"+ );+ assert!(picker.delegate.is_item_selected(0));+ assert_eq!(+ picker.delegate.selected_index(),+ 1,+ "selecting should advance the cursor to the next item"+ );+ });++ // In pickers without multi-select the action does nothing.+ let (plain_picker, cx) = cx.add_window_view(|window, cx| {+ Picker::uniform_list(TestDelegate::new(vec![true, true]), window, cx)+ });+ plain_picker.update_in(cx, |picker, window, cx| {+ picker.multi_select_next(&MultiSelectNext, window, cx);+ });+ plain_picker.update(cx, |picker, _cx| {+ assert!(!picker.select_instead_of_open);+ assert_eq!(picker.delegate.selected_item_count(), 0);+ });+ }++ #[gpui::test]+ async fn test_exiting_multi_select_mode_clears_selection(cx: &mut TestAppContext) {+ init_test(cx);++ let (picker, cx) = cx.add_window_view(|window, cx| {+ Picker::uniform_list(+ TestDelegate::new(vec![true, true]).with_multi_select(),+ window,+ cx,+ )+ });++ picker.update_in(cx, |picker, window, cx| {+ picker.toggle_multi_select(&ToggleMultiSelect, window, cx);+ picker.handle_click(0, false, window, cx);+ picker.toggle_multi_select(&ToggleMultiSelect, window, cx);+ });+ picker.update(cx, |picker, _cx| {+ assert_eq!(+ picker.delegate.selected_item_count(),+ 0,+ "leaving the mode should clear the selection"+ );+ });+ }}impl<D: PickerDelegate> EventEmitter<DismissEvent> for Picker<D> {}diff --git a/crates/picker/src/render.rs b/crates/picker/src/render.rsindex e60b46469c8..499b0982eed 100644--- a/crates/picker/src/render.rs+++ b/crates/picker/src/render.rs@@ -149,6 +149,8 @@ impl<D: PickerDelegate> Picker<D> {.on_action(cx.listener(Self::set_preview_below)).on_action(cx.listener(Self::set_preview_hidden)).on_action(cx.listener(Self::toggle_actions_menu))+ .on_action(cx.listener(Self::toggle_multi_select))+ .on_action(cx.listener(Self::multi_select_next)).children(match &self.head {Head::Editor(editor) => {if editor_position == PickerEditorPosition::Start {diff --git a/crates/search/src/text_finder/delegate.rs b/crates/search/src/text_finder/delegate.rsindex 63068b1a9ed..195223782f6 100644--- a/crates/search/src/text_finder/delegate.rs+++ b/crates/search/src/text_finder/delegate.rs@@ -35,7 +35,7 @@ use gpui::{AnyElement, AppContext, AsyncApp, ClickEvent, DismissEvent, EntityId, HighlightStyle,Modifiers, StyledText, Task, TextStyle, prelude::*,};-use gpui::{Entity, FocusHandle};+use gpui::{Entity, FocusHandle, WeakEntity};use language::{Buffer, LanguageAwareStyling};use picker::{Picker, PickerDelegate};use project::{Project, ProjectPath, Search};@@ -52,6 +52,7 @@ use util::ResultExt;use workspace::SplitDirection;use workspace::Workspace;use workspace::item::ItemSettings;+use workspace::pane::Pane;use super::{Fold, SearchMatch, Unfold};use crate::project_search::{ActiveSettings, ProjectSearch};@@ -85,9 +86,28 @@ pub struct Delegate {/// column so every row's number right-aligns to the widest one. Recomputed in/// [`Delegate::rebuild_entries`].pub(crate) max_line_number: u32,+ pub(crate) selected_matches: Vec<SelectedMatch>,pub(crate) collapsed_paths: HashSet<ProjectPath>,}+/// Wrapper with Eq is path + range equality+#[derive(Clone)]+pub(crate) struct SelectedMatch(pub SearchMatch);++impl PartialEq for SelectedMatch {+ fn eq(&self, other: &Self) -> bool {+ *self == other.0+ }+}++impl Eq for SelectedMatch {}++impl PartialEq<SearchMatch> for SelectedMatch {+ fn eq(&self, other: &SearchMatch) -> bool {+ self.0.path == other.path && self.0.range == other.range+ }+}+pub(crate) enum Entry {Header(ProjectPath),Match(usize),@@ -305,6 +325,7 @@ impl Delegate {in_progress_search,unique_files: HashSet::default(),max_line_number: 0,+ selected_matches: Vec::new(),collapsed_paths: HashSet::default(),});@@ -446,19 +467,100 @@ impl Delegate {}fn selected_search_match(&self) -> Option<&SearchMatch> {- match self.entries.get(self.selected_index)? {+ self.search_match_for_entry(self.selected_index)+ }++ fn search_match_for_entry(&self, ix: usize) -> Option<&SearchMatch> {+ match self.entries.get(ix)? {Entry::Match(match_index) => self.matches.get(*match_index),Entry::Header(_) | Entry::Separator => None,}}+ pub(crate) fn prepend_selected_matches(&mut self) {+ if self.selected_matches.is_empty() {+ return;+ }+ self.matches+ .retain(|m| !self.selected_matches.iter().any(|selected| selected == m));+ let mut matches: Vec<SearchMatch> = self+ .selected_matches+ .iter()+ .map(|selected| selected.0.clone())+ .collect();+ self.unique_files+ .extend(matches.iter().map(|m| m.path.clone()));+ matches.append(&mut self.matches);+ self.matches = matches;+ }++ fn open_match(+ &self,+ search_match: &SearchMatch,+ pane: Option<WeakEntity<Pane>>,+ focus: bool,+ window: &mut Window,+ cx: &mut Context<Picker<Self>>,+ ) {+ let path = search_match.path.clone();+ let row = search_match.line_number.saturating_sub(1);+ let column = search_match.match_start_byte_column;+ let Some(workspace) = self.project_search_view.read(cx).workspace.upgrade() else {+ return;+ };+ let open_task = workspace.update(cx, |workspace, cx| {+ workspace.open_path_preview(path, pane, focus, false, true, window, cx)+ });+ cx.spawn_in(window, async move |_, cx| {+ let item = open_task.await.log_err()?;+ if let Some(active_editor) = item.downcast::<editor::Editor>() {+ active_editor+ .downgrade()+ .update_in(cx, |editor, window, cx| {+ editor.go_to_singleton_buffer_point(+ text::Point::new(row, column),+ window,+ cx,+ );+ })+ .log_err();+ }+ Some(())+ })+ .detach();+ }+/// Opens the selected match in a new split in `direction`, then dismisses.+ /// With a multi-selection, every selected match opens as a tab in a+ /// single new split.pub(crate) fn open_in_split(&mut self,direction: SplitDirection,window: &mut Window,cx: &mut Context<Picker<Self>>,) {+ if !self.selected_matches.is_empty() {+ let Some(workspace) = self.project_search_view.read(cx).workspace.upgrade() else {+ return;+ };+ let selected = std::mem::take(&mut self.selected_matches);+ let new_pane = workspace.update(cx, |workspace, cx| {+ workspace.split_pane(workspace.active_pane().clone(), direction, window, cx)+ });+ let count = selected.len();+ for (i, selected_match) in selected.iter().enumerate() {+ let focus = i + 1 == count;+ self.open_match(+ &selected_match.0,+ Some(new_pane.downgrade()),+ focus,+ window,+ cx,+ );+ }+ cx.emit(DismissEvent);+ return;+ }let Some(selected_match) = self.selected_search_match() else {return;};@@ -668,7 +770,14 @@ impl PickerDelegate for Delegate {workspace::pane::SplitDown::default().boxed_clone(),),picker::PickerAction::separator(),- picker::PickerAction::button("Open File", menu::Confirm.boxed_clone()),+ picker::PickerAction::button(+ if self.selected_matches.len() > 1 {+ "Open multiple"+ } else {+ "Open File"+ },+ menu::Confirm.boxed_clone(),+ ),picker::PickerAction::button("Open as Tab", super::ToProjectSearch.boxed_clone()),]}@@ -733,6 +842,8 @@ impl PickerDelegate for Delegate {self.collapsed_paths.clear();self.selected_index = 0;self.active_query = None;+ self.prepend_selected_matches();+ self.rebuild_entries();cx.notify();return Task::ready(());};@@ -809,41 +920,73 @@ impl PickerDelegate for Delegate {}}- let Some(selected_match) = self.selected_search_match() else {+ let Some(selected_match) = self.selected_search_match().cloned() else {return;};+ self.open_match(&selected_match, None, true, window, cx);- let path = selected_match.path.clone();- let line_number = selected_match.line_number;- let column = selected_match.match_start_byte_column;+ cx.emit(DismissEvent);+ }- let Some(workspace) = self.project_search_view.read(cx).workspace.upgrade() else {+ fn supports_multi_select(&self) -> bool {+ true+ }++ fn is_item_selected(&self, ix: usize) -> bool {+ let Some(search_match) = self.search_match_for_entry(ix) else {+ return false;+ };+ self.selected_matches+ .iter()+ .any(|selected| selected == search_match)+ }++ fn toggle_item_selected(+ &mut self,+ ix: usize,+ _window: &mut Window,+ cx: &mut Context<Picker<Self>>,+ ) {+ // Headers and separators cannot participate in multi-selection.+ let Some(search_match) = self.search_match_for_entry(ix).cloned() else {return;};+ let selected = SelectedMatch(search_match);+ if let Some(position) = self+ .selected_matches+ .iter()+ .position(|existing| *existing == selected)+ {+ self.selected_matches.remove(position);+ } else {+ self.selected_matches.push(selected);+ }+ cx.notify();+ }- let open_task = workspace.update(cx, |workspace, cx| {- workspace.open_path_preview(path, None, true, false, true, window, cx)- });+ fn selected_item_count(&self) -> usize {+ self.selected_matches.len()+ }- let row = line_number.saturating_sub(1);- cx.spawn_in(window, async move |_, cx| {- let item = open_task.await.log_err()?;- if let Some(active_editor) = item.downcast::<editor::Editor>() {- active_editor- .downgrade()- .update_in(cx, |editor, window, cx| {- editor.go_to_singleton_buffer_point(- text::Point::new(row, column),- window,- cx,- );- })- .log_err();- }- Some(())- })- .detach();+ fn clear_selection(&mut self, _cx: &mut Context<Picker<Self>>) {+ self.selected_matches.clear();+ }+ fn confirm_multi(+ &mut self,+ _secondary: bool,+ window: &mut Window,+ cx: &mut Context<Picker<Self>>,+ ) {+ let selected = std::mem::take(&mut self.selected_matches);+ if selected.is_empty() {+ return;+ }+ let count = selected.len();+ for (i, selected_match) in selected.iter().enumerate() {+ let is_last = i + 1 == count;+ self.open_match(&selected_match.0, None, is_last, window, cx);+ }cx.emit(DismissEvent);}@@ -1093,6 +1236,7 @@ async fn stream_results_to_picker(.unique_files.extend(batch_matches.iter().map(|m| &m.path).cloned());delegate.matches.extend(batch_matches);+ delegate.prepend_selected_matches();// Rebuild the grouped view and resnap the selection onto a// selectable row (the header/separator rows are not selectable).delegate.rebuild_entries();