Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

project_panel: Preserve clipboard contents when duplicating entries (#60894)

$H!NDGEKYUME340c703bb281
diff --git a/crates/project_panel/src/project_panel.rs b/crates/project_panel/src/project_panel.rs
index fbdbf628e49..cc8b23d2a0e 100644
--- a/crates/project_panel/src/project_panel.rs
+++ b/crates/project_panel/src/project_panel.rs
@@ -263,6 +263,12 @@ enum ClipboardEntry {
Cut(BTreeSet<SelectedEntry>),
}
+#[derive(Clone, Copy)]
+enum EntryTransferOperation {
+ Copy,
+ Move,
+}
+
#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
struct DiagnosticCount {
error_count: usize,
@@ -3615,8 +3621,8 @@ impl ProjectPanel {
.worktree_for_entry(source.entry_id, cx)?;
let source_entry = source_worktree.read(cx).entry_for_id(source.entry_id)?;
- let clipboard_entry_file_name = source_entry.path.file_name()?.to_string();
- new_path.push(RelPath::from_unix_str(&clipboard_entry_file_name).unwrap());
+ let source_file_name = source_entry.path.file_name()?.to_string();
+ new_path.push(RelPath::from_unix_str(&source_file_name).unwrap());
let (extension, file_name_without_extension) = if source_entry.is_file() {
(
@@ -3624,7 +3630,7 @@ impl ProjectPanel {
new_path.file_stem()?.to_string(),
)
} else {
- (None, clipboard_entry_file_name.clone())
+ (None, source_file_name)
};
let file_name_len = file_name_without_extension.len();
@@ -3673,16 +3679,45 @@ impl ProjectPanel {
return;
}
+ self.paste_from_internal_clipboard(window, cx);
+ }
+
+ fn paste_from_internal_clipboard(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let Some(clipboard_entry) = self
+ .clipboard
+ .clone()
+ .filter(|clipboard_entry| !clipboard_entry.items().is_empty())
+ else {
+ return;
+ };
+
+ let (entries, operation) = match clipboard_entry {
+ ClipboardEntry::Copied(entries) => (entries, EntryTransferOperation::Copy),
+ ClipboardEntry::Cut(entries) => (entries, EntryTransferOperation::Move),
+ };
+ if self
+ .transfer_entries(entries, operation, window, cx)
+ .is_some()
+ && matches!(operation, EntryTransferOperation::Move)
+ {
+ // Convert the clipboard cut entry to a copy entry after the first paste.
+ self.clipboard = self.clipboard.take().map(ClipboardEntry::into_copy_entry);
+ }
+ }
+
+ fn transfer_entries(
+ &mut self,
+ entries: BTreeSet<SelectedEntry>,
+ operation: EntryTransferOperation,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> Option<()> {
maybe!({
let (worktree, entry) = self.selected_entry_handle(cx)?;
let entry = entry.clone();
let worktree_id = worktree.read(cx).id();
- let clipboard_entries = self
- .clipboard
- .as_ref()
- .filter(|clipboard| !clipboard.items().is_empty())?;
- enum PasteTask {
+ enum EntryTransferTask {
Rename {
task: Task<Result<CreatedEntry>>,
from: ProjectPath,
@@ -3694,44 +3729,47 @@ impl ProjectPanel {
},
}
- let mut paste_tasks = Vec::new();
+ let mut transfer_tasks = Vec::new();
let mut disambiguation_range = None;
- let clip_is_cut = clipboard_entries.is_cut();
- for clipboard_entry in clipboard_entries.items() {
+ for source_entry in &entries {
let (new_path, new_disambiguation_range) =
- self.create_paste_path(clipboard_entry, self.selected_sub_entry(cx)?, cx)?;
- let clip_entry_id = clipboard_entry.entry_id;
+ self.create_paste_path(source_entry, self.selected_sub_entry(cx)?, cx)?;
+ let source_entry_id = source_entry.entry_id;
let destination: ProjectPath = (worktree_id, new_path).into();
- let task = if clipboard_entries.is_cut() {
- let original_path = self.project.read(cx).path_for_entry(clip_entry_id, cx)?;
- let task = self.project.update(cx, |project, cx| {
- project.rename_entry(clip_entry_id, destination.clone(), cx)
- });
- PasteTask::Rename {
- task,
- from: original_path,
- to: destination,
+ let task = match operation {
+ EntryTransferOperation::Copy => {
+ let task = self.project.update(cx, |project, cx| {
+ project.copy_entry(source_entry_id, destination.clone(), cx)
+ });
+ EntryTransferTask::Copy { task, destination }
+ }
+ EntryTransferOperation::Move => {
+ let original_path =
+ self.project.read(cx).path_for_entry(source_entry_id, cx)?;
+ let task = self.project.update(cx, |project, cx| {
+ project.rename_entry(source_entry_id, destination.clone(), cx)
+ });
+ EntryTransferTask::Rename {
+ task,
+ from: original_path,
+ to: destination,
+ }
}
- } else {
- let task = self.project.update(cx, |project, cx| {
- project.copy_entry(clip_entry_id, destination.clone(), cx)
- });
- PasteTask::Copy { task, destination }
};
- paste_tasks.push(task);
+ transfer_tasks.push(task);
disambiguation_range = new_disambiguation_range.or(disambiguation_range);
}
- let item_count = paste_tasks.len();
+ let item_count = transfer_tasks.len();
let workspace = self.workspace.clone();
cx.spawn_in(window, async move |project_panel, mut cx| {
let mut last_succeed = None;
let mut changes = Vec::new();
- for task in paste_tasks {
+ for task in transfer_tasks {
match task {
- PasteTask::Rename { task, from, to } => {
+ EntryTransferTask::Rename { task, from, to } => {
if let Some(CreatedEntry::Included(entry)) = task
.await
.notify_workspace_async_err(workspace.clone(), &mut cx)
@@ -3740,7 +3778,7 @@ impl ProjectPanel {
last_succeed = Some(entry);
}
}
- PasteTask::Copy { task, destination } => {
+ EntryTransferTask::Copy { task, destination } => {
if let Some(Some(entry)) = task
.await
.notify_workspace_async_err(workspace.clone(), &mut cx)
@@ -3781,7 +3819,6 @@ impl ProjectPanel {
}
}
- // if only one entry was pasted and it was disambiguated, open the rename editor
if disambiguation_range.is_some() {
cx.defer_in(window, |this, window, cx| {
this.rename_impl(disambiguation_range, window, cx);
@@ -3796,14 +3833,9 @@ impl ProjectPanel {
})
.detach_and_log_err(cx);
- if clip_is_cut {
- // Convert the clipboard cut entry to a copy entry after the first paste.
- self.clipboard = self.clipboard.take().map(ClipboardEntry::into_copy_entry);
- }
-
self.expand_entry(worktree_id, entry.id, cx);
Some(())
- });
+ })
}
fn download_from_remote(
@@ -3979,8 +4011,12 @@ impl ProjectPanel {
}
fn duplicate(&mut self, _: &Duplicate, window: &mut Window, cx: &mut Context<Self>) {
- self.copy(&Copy {}, window, cx);
- self.paste(&Paste {}, window, cx);
+ let entries = self.disjoint_effective_entries_excluding_roots(cx);
+ if entries.is_empty() {
+ return;
+ }
+
+ self.transfer_entries(entries, EntryTransferOperation::Copy, window, cx);
}
fn copy_path(
diff --git a/crates/project_panel/src/project_panel_tests.rs b/crates/project_panel/src/project_panel_tests.rs
index d168f8a93d0..a2bd6567831 100644
--- a/crates/project_panel/src/project_panel_tests.rs
+++ b/crates/project_panel/src/project_panel_tests.rs
@@ -2531,6 +2531,160 @@ async fn test_open_svg_preview_for_single_file_worktree(cx: &mut gpui::TestAppCo
});
}
+#[gpui::test]
+async fn test_duplicate_preserves_clipboards(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/root"),
+ json!({
+ "cut.txt": "",
+ "destination": {},
+ "folder": {
+ "nested.txt": ""
+ }
+ }),
+ )
+ .await;
+ fs.insert_tree(
+ path!("/external"),
+ json!({
+ "external.txt": ""
+ }),
+ )
+ .await;
+
+ let project = Project::test(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, |mw, _| mw.workspace().clone())
+ .unwrap();
+ let cx = &mut VisualTestContext::from_window(window.into(), cx);
+ let panel = workspace.update_in(cx, ProjectPanel::new);
+ cx.run_until_parked();
+
+ select_path(&panel, "root/cut.txt", cx);
+ panel.update_in(cx, |panel, window, cx| {
+ panel.cut(&Cut, window, cx);
+ });
+
+ let system_clipboard = ClipboardItem {
+ entries: vec![GpuiClipboardEntry::ExternalPaths(ExternalPaths(smallvec![
+ PathBuf::from(path!("/external/external.txt"))
+ ]))],
+ };
+ cx.write_to_clipboard(system_clipboard.clone());
+
+ select_path(&panel, "root/folder", cx);
+ panel.update_in(cx, |panel, window, cx| {
+ panel.duplicate(&Duplicate, window, cx);
+ });
+ cx.run_until_parked();
+
+ assert_eq!(
+ cx.read_from_clipboard(),
+ Some(system_clipboard),
+ "Duplicate should not modify the system clipboard"
+ );
+ assert!(
+ find_project_entry(&panel, "root/folder copy", cx).is_some(),
+ "Duplicate should copy the selected project entry"
+ );
+ assert!(
+ find_project_entry(&panel, "root/folder copy/nested.txt", cx).is_some(),
+ "Duplicate should recursively copy directories"
+ );
+ assert!(
+ find_project_entry(&panel, "root/external.txt", cx).is_none(),
+ "Duplicate should not paste external clipboard entries"
+ );
+
+ panel.update_in(cx, |panel, window, cx| {
+ assert!(panel.confirm_edit(true, window, cx).is_none());
+ });
+ // Paste prefers external paths on the system clipboard over the panel's pending cut.
+ cx.write_to_clipboard(ClipboardItem::new_string("unrelated".into()));
+
+ select_path(&panel, "root/destination", cx);
+ panel.update_in(cx, |panel, window, cx| {
+ panel.paste(&Paste, window, cx);
+ });
+ cx.run_until_parked();
+
+ assert!(
+ find_project_entry(&panel, "root/destination/cut.txt", cx).is_some(),
+ "Duplicate should preserve entries cut within the project panel"
+ );
+ assert!(
+ find_project_entry(&panel, "root/cut.txt", cx).is_none(),
+ "Duplicate should preserve the pending cut operation"
+ );
+}
+
+#[gpui::test]
+async fn test_duplicate_with_only_root_selected_does_nothing(cx: &mut gpui::TestAppContext) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/root"),
+ json!({
+ "folder": {
+ "cut.txt": ""
+ }
+ }),
+ )
+ .await;
+ fs.insert_tree(
+ path!("/external"),
+ json!({
+ "external.txt": ""
+ }),
+ )
+ .await;
+
+ let project = Project::test(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, |mw, _| mw.workspace().clone())
+ .unwrap();
+ let cx = &mut VisualTestContext::from_window(window.into(), cx);
+ let panel = workspace.update_in(cx, ProjectPanel::new);
+ cx.run_until_parked();
+
+ select_path(&panel, "root/folder/cut.txt", cx);
+ panel.update_in(cx, |panel, window, cx| {
+ panel.cut(&Cut, window, cx);
+ });
+
+ select_path(&panel, "root", cx);
+ panel.update_in(cx, |panel, window, cx| {
+ panel.duplicate(&Duplicate, window, cx);
+ });
+ cx.run_until_parked();
+
+ assert!(
+ find_project_entry(&panel, "root/folder/cut.txt", cx).is_some(),
+ "Duplicate on a worktree root should not consume a pending cut"
+ );
+
+ cx.write_to_clipboard(ClipboardItem {
+ entries: vec![GpuiClipboardEntry::ExternalPaths(ExternalPaths(smallvec![
+ PathBuf::from(path!("/external/external.txt"))
+ ]))],
+ });
+ panel.update_in(cx, |panel, window, cx| {
+ panel.duplicate(&Duplicate, window, cx);
+ });
+ cx.run_until_parked();
+
+ assert!(
+ find_project_entry(&panel, "root/external.txt", cx).is_none(),
+ "Duplicate on a worktree root should not paste external clipboard entries"
+ );
+}
+
#[gpui::test]
async fn test_remove_opened_file(cx: &mut gpui::TestAppContext) {
init_test_with_editor(cx);
diff --git a/docs/src/project-panel.md b/docs/src/project-panel.md
index 9fbe29ee4d5..f3baa468e73 100644
--- a/docs/src/project-panel.md
+++ b/docs/src/project-panel.md
@@ -104,8 +104,8 @@ suffix, the rename editor opens automatically so you can adjust the name.
### Duplicate
-{#action project_panel::Duplicate} ({#kb project_panel::Duplicate}) copies and
-pastes the selected entries in one step.
+{#action project_panel::Duplicate} ({#kb project_panel::Duplicate}) duplicates
+the selected entries without changing the clipboard.
### Trash and Delete