1use anyhow::Context as _;
2use collections::HashSet;
3use fuzzy::StringMatchCandidate;
4
5use git::repository::Worktree as GitWorktree;
6use gpui::{
7 Action, App, AsyncApp, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
8 InteractiveElement, IntoElement, Modifiers, ModifiersChangedEvent, ParentElement,
9 PathPromptOptions, Render, SharedString, Styled, Subscription, Task, WeakEntity, Window,
10 actions, rems,
11};
12use picker::{Picker, PickerDelegate, PickerEditorPosition};
13use project::{
14 DirectoryLister,
15 git_store::Repository,
16 trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees},
17};
18use recent_projects::{RemoteConnectionModal, connect};
19use remote::{RemoteConnectionOptions, remote_client::ConnectionIdentifier};
20use std::{path::PathBuf, sync::Arc};
21use ui::{HighlightedLabel, KeyBinding, ListItem, ListItemSpacing, Tooltip, prelude::*};
22use util::ResultExt;
23use workspace::{ModalView, Workspace, notifications::DetachAndPromptErr};
24
25actions!(git, [WorktreeFromDefault, WorktreeFromDefaultOnWindow]);
26
27pub fn register(workspace: &mut Workspace) {
28 workspace.register_action(open);
29}
30
31pub fn open(
32 workspace: &mut Workspace,
33 _: &zed_actions::git::Worktree,
34 window: &mut Window,
35 cx: &mut Context<Workspace>,
36) {
37 let repository = workspace.project().read(cx).active_repository(cx);
38 let workspace_handle = workspace.weak_handle();
39 workspace.toggle_modal(window, cx, |window, cx| {
40 WorktreeList::new(repository, workspace_handle, rems(34.), window, cx)
41 })
42}
43
44pub struct WorktreeList {
45 width: Rems,
46 pub picker: Entity<Picker<WorktreeListDelegate>>,
47 picker_focus_handle: FocusHandle,
48 _subscription: Subscription,
49}
50
51impl WorktreeList {
52 fn new(
53 repository: Option<Entity<Repository>>,
54 workspace: WeakEntity<Workspace>,
55 width: Rems,
56 window: &mut Window,
57 cx: &mut Context<Self>,
58 ) -> Self {
59 let all_worktrees_request = repository
60 .clone()
61 .map(|repository| repository.update(cx, |repository, _| repository.worktrees()));
62
63 let default_branch_request = repository
64 .clone()
65 .map(|repository| repository.update(cx, |repository, _| repository.default_branch()));
66
67 cx.spawn_in(window, async move |this, cx| {
68 let all_worktrees = all_worktrees_request
69 .context("No active repository")?
70 .await??;
71
72 let default_branch = default_branch_request
73 .context("No active repository")?
74 .await
75 .map(Result::ok)
76 .ok()
77 .flatten()
78 .flatten();
79
80 this.update_in(cx, |this, window, cx| {
81 this.picker.update(cx, |picker, cx| {
82 picker.delegate.all_worktrees = Some(all_worktrees);
83 picker.delegate.default_branch = default_branch;
84 picker.refresh(window, cx);
85 })
86 })?;
87
88 anyhow::Ok(())
89 })
90 .detach_and_log_err(cx);
91
92 let delegate = WorktreeListDelegate::new(workspace, repository, window, cx);
93 let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
94 let picker_focus_handle = picker.focus_handle(cx);
95 picker.update(cx, |picker, _| {
96 picker.delegate.focus_handle = picker_focus_handle.clone();
97 });
98
99 let _subscription = cx.subscribe(&picker, |_, _, _, cx| {
100 cx.emit(DismissEvent);
101 });
102
103 Self {
104 picker,
105 picker_focus_handle,
106 width,
107 _subscription,
108 }
109 }
110
111 fn handle_modifiers_changed(
112 &mut self,
113 ev: &ModifiersChangedEvent,
114 _: &mut Window,
115 cx: &mut Context<Self>,
116 ) {
117 self.picker
118 .update(cx, |picker, _| picker.delegate.modifiers = ev.modifiers)
119 }
120
121 fn handle_new_worktree(
122 &mut self,
123 replace_current_window: bool,
124 window: &mut Window,
125 cx: &mut Context<Self>,
126 ) {
127 self.picker.update(cx, |picker, cx| {
128 let ix = picker.delegate.selected_index();
129 let Some(entry) = picker.delegate.matches.get(ix) else {
130 return;
131 };
132 let Some(default_branch) = picker.delegate.default_branch.clone() else {
133 return;
134 };
135 if !entry.is_new {
136 return;
137 }
138 picker.delegate.create_worktree(
139 entry.worktree.branch(),
140 replace_current_window,
141 Some(default_branch.into()),
142 window,
143 cx,
144 );
145 })
146 }
147}
148impl ModalView for WorktreeList {}
149impl EventEmitter<DismissEvent> for WorktreeList {}
150
151impl Focusable for WorktreeList {
152 fn focus_handle(&self, _: &App) -> FocusHandle {
153 self.picker_focus_handle.clone()
154 }
155}
156
157impl Render for WorktreeList {
158 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
159 v_flex()
160 .key_context("GitWorktreeSelector")
161 .w(self.width)
162 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
163 .on_action(cx.listener(|this, _: &WorktreeFromDefault, w, cx| {
164 this.handle_new_worktree(false, w, cx)
165 }))
166 .on_action(cx.listener(|this, _: &WorktreeFromDefaultOnWindow, w, cx| {
167 this.handle_new_worktree(true, w, cx)
168 }))
169 .child(self.picker.clone())
170 .on_mouse_down_out({
171 cx.listener(move |this, _, window, cx| {
172 this.picker.update(cx, |this, cx| {
173 this.cancel(&Default::default(), window, cx);
174 })
175 })
176 })
177 }
178}
179
180#[derive(Debug, Clone)]
181struct WorktreeEntry {
182 worktree: GitWorktree,
183 positions: Vec<usize>,
184 is_new: bool,
185}
186
187pub struct WorktreeListDelegate {
188 matches: Vec<WorktreeEntry>,
189 all_worktrees: Option<Vec<GitWorktree>>,
190 workspace: WeakEntity<Workspace>,
191 repo: Option<Entity<Repository>>,
192 selected_index: usize,
193 last_query: String,
194 modifiers: Modifiers,
195 focus_handle: FocusHandle,
196 default_branch: Option<SharedString>,
197}
198
199impl WorktreeListDelegate {
200 fn new(
201 workspace: WeakEntity<Workspace>,
202 repo: Option<Entity<Repository>>,
203 _window: &mut Window,
204 cx: &mut Context<WorktreeList>,
205 ) -> Self {
206 Self {
207 matches: vec![],
208 all_worktrees: None,
209 workspace,
210 selected_index: 0,
211 repo,
212 last_query: Default::default(),
213 modifiers: Default::default(),
214 focus_handle: cx.focus_handle(),
215 default_branch: None,
216 }
217 }
218
219 fn create_worktree(
220 &self,
221 worktree_branch: &str,
222 replace_current_window: bool,
223 commit: Option<String>,
224 window: &mut Window,
225 cx: &mut Context<Picker<Self>>,
226 ) {
227 let Some(repo) = self.repo.clone() else {
228 return;
229 };
230
231 let worktree_path = self
232 .workspace
233 .clone()
234 .update(cx, |this, cx| {
235 this.prompt_for_open_path(
236 PathPromptOptions {
237 files: false,
238 directories: true,
239 multiple: false,
240 prompt: Some("Select directory for new worktree".into()),
241 },
242 DirectoryLister::Project(this.project().clone()),
243 window,
244 cx,
245 )
246 })
247 .log_err();
248 let Some(worktree_path) = worktree_path else {
249 return;
250 };
251
252 let branch = worktree_branch.to_string();
253 let window_handle = window.window_handle();
254 let workspace = self.workspace.clone();
255 cx.spawn_in(window, async move |_, cx| {
256 let Some(paths) = worktree_path.await? else {
257 return anyhow::Ok(());
258 };
259 let path = paths.get(0).cloned().context("No path selected")?;
260
261 repo.update(cx, |repo, _| {
262 repo.create_worktree(branch.clone(), path.clone(), commit)
263 })?
264 .await??;
265 let new_worktree_path = path.join(branch);
266
267 workspace.update(cx, |workspace, cx| {
268 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
269 let repo_path = &repo.read(cx).snapshot().work_directory_abs_path;
270 let project = workspace.project();
271 if let Some((parent_worktree, _)) =
272 project.read(cx).find_worktree(repo_path, cx)
273 {
274 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
275 if trusted_worktrees.can_trust(parent_worktree.read(cx).id(), cx) {
276 trusted_worktrees.trust(
277 HashSet::from_iter([PathTrust::AbsPath(
278 new_worktree_path.clone(),
279 )]),
280 project
281 .read(cx)
282 .remote_connection_options(cx)
283 .map(RemoteHostLocation::from),
284 cx,
285 );
286 }
287 });
288 }
289 }
290 })?;
291
292 let (connection_options, app_state, is_local) =
293 workspace.update(cx, |workspace, cx| {
294 let project = workspace.project().clone();
295 let connection_options = project.read(cx).remote_connection_options(cx);
296 let app_state = workspace.app_state().clone();
297 let is_local = project.read(cx).is_local();
298 (connection_options, app_state, is_local)
299 })?;
300
301 if is_local {
302 workspace
303 .update_in(cx, |workspace, window, cx| {
304 workspace.open_workspace_for_paths(
305 replace_current_window,
306 vec![new_worktree_path],
307 window,
308 cx,
309 )
310 })?
311 .await?;
312 } else if let Some(connection_options) = connection_options {
313 open_remote_worktree(
314 connection_options,
315 vec![new_worktree_path],
316 app_state,
317 window_handle,
318 replace_current_window,
319 cx,
320 )
321 .await?;
322 }
323
324 anyhow::Ok(())
325 })
326 .detach_and_prompt_err("Failed to create worktree", window, cx, |e, _, _| {
327 Some(e.to_string())
328 });
329 }
330
331 fn open_worktree(
332 &self,
333 worktree_path: &PathBuf,
334 replace_current_window: bool,
335 window: &mut Window,
336 cx: &mut Context<Picker<Self>>,
337 ) {
338 let workspace = self.workspace.clone();
339 let path = worktree_path.clone();
340
341 let Some((connection_options, app_state, is_local)) = workspace
342 .update(cx, |workspace, cx| {
343 let project = workspace.project().clone();
344 let connection_options = project.read(cx).remote_connection_options(cx);
345 let app_state = workspace.app_state().clone();
346 let is_local = project.read(cx).is_local();
347 (connection_options, app_state, is_local)
348 })
349 .log_err()
350 else {
351 return;
352 };
353
354 if is_local {
355 let open_task = workspace.update(cx, |workspace, cx| {
356 workspace.open_workspace_for_paths(replace_current_window, vec![path], window, cx)
357 });
358 cx.spawn(async move |_, _| {
359 open_task?.await?;
360 anyhow::Ok(())
361 })
362 .detach_and_prompt_err(
363 "Failed to open worktree",
364 window,
365 cx,
366 |e, _, _| Some(e.to_string()),
367 );
368 } else if let Some(connection_options) = connection_options {
369 let window_handle = window.window_handle();
370 cx.spawn_in(window, async move |_, cx| {
371 open_remote_worktree(
372 connection_options,
373 vec![path],
374 app_state,
375 window_handle,
376 replace_current_window,
377 cx,
378 )
379 .await
380 })
381 .detach_and_prompt_err(
382 "Failed to open worktree",
383 window,
384 cx,
385 |e, _, _| Some(e.to_string()),
386 );
387 }
388
389 cx.emit(DismissEvent);
390 }
391
392 fn base_branch<'a>(&'a self, cx: &'a mut Context<Picker<Self>>) -> Option<&'a str> {
393 self.repo
394 .as_ref()
395 .and_then(|repo| repo.read(cx).branch.as_ref().map(|b| b.name()))
396 }
397}
398
399async fn open_remote_worktree(
400 connection_options: RemoteConnectionOptions,
401 paths: Vec<PathBuf>,
402 app_state: Arc<workspace::AppState>,
403 window: gpui::AnyWindowHandle,
404 replace_current_window: bool,
405 cx: &mut AsyncApp,
406) -> anyhow::Result<()> {
407 let workspace_window = window
408 .downcast::<Workspace>()
409 .ok_or_else(|| anyhow::anyhow!("Window is not a Workspace window"))?;
410
411 let connect_task = workspace_window.update(cx, |workspace, window, cx| {
412 workspace.toggle_modal(window, cx, |window, cx| {
413 RemoteConnectionModal::new(&connection_options, Vec::new(), window, cx)
414 });
415
416 let prompt = workspace
417 .active_modal::<RemoteConnectionModal>(cx)
418 .expect("Modal just created")
419 .read(cx)
420 .prompt
421 .clone();
422
423 connect(
424 ConnectionIdentifier::setup(),
425 connection_options.clone(),
426 prompt,
427 window,
428 cx,
429 )
430 .prompt_err("Failed to connect", window, cx, |_, _, _| None)
431 })?;
432
433 let session = connect_task.await;
434
435 workspace_window.update(cx, |workspace, _window, cx| {
436 if let Some(prompt) = workspace.active_modal::<RemoteConnectionModal>(cx) {
437 prompt.update(cx, |prompt, cx| prompt.finished(cx))
438 }
439 })?;
440
441 let Some(Some(session)) = session else {
442 return Ok(());
443 };
444
445 let new_project = cx.update(|cx| {
446 project::Project::remote(
447 session,
448 app_state.client.clone(),
449 app_state.node_runtime.clone(),
450 app_state.user_store.clone(),
451 app_state.languages.clone(),
452 app_state.fs.clone(),
453 true,
454 cx,
455 )
456 })?;
457
458 let window_to_use = if replace_current_window {
459 workspace_window
460 } else {
461 let workspace_position = cx
462 .update(|cx| {
463 workspace::remote_workspace_position_from_db(connection_options.clone(), &paths, cx)
464 })?
465 .await
466 .context("fetching workspace position from db")?;
467
468 let mut options =
469 cx.update(|cx| (app_state.build_window_options)(workspace_position.display, cx))?;
470 options.window_bounds = workspace_position.window_bounds;
471
472 cx.open_window(options, |window, cx| {
473 cx.new(|cx| {
474 let mut workspace =
475 Workspace::new(None, new_project.clone(), app_state.clone(), window, cx);
476 workspace.centered_layout = workspace_position.centered_layout;
477 workspace
478 })
479 })?
480 };
481
482 workspace::open_remote_project_with_existing_connection(
483 connection_options,
484 new_project,
485 paths,
486 app_state,
487 window_to_use,
488 cx,
489 )
490 .await?;
491
492 Ok(())
493}
494
495impl PickerDelegate for WorktreeListDelegate {
496 type ListItem = ListItem;
497
498 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
499 "Select worktree…".into()
500 }
501
502 fn editor_position(&self) -> PickerEditorPosition {
503 PickerEditorPosition::Start
504 }
505
506 fn match_count(&self) -> usize {
507 self.matches.len()
508 }
509
510 fn selected_index(&self) -> usize {
511 self.selected_index
512 }
513
514 fn set_selected_index(
515 &mut self,
516 ix: usize,
517 _window: &mut Window,
518 _: &mut Context<Picker<Self>>,
519 ) {
520 self.selected_index = ix;
521 }
522
523 fn update_matches(
524 &mut self,
525 query: String,
526 window: &mut Window,
527 cx: &mut Context<Picker<Self>>,
528 ) -> Task<()> {
529 let Some(all_worktrees) = self.all_worktrees.clone() else {
530 return Task::ready(());
531 };
532
533 cx.spawn_in(window, async move |picker, cx| {
534 let mut matches: Vec<WorktreeEntry> = if query.is_empty() {
535 all_worktrees
536 .into_iter()
537 .map(|worktree| WorktreeEntry {
538 worktree,
539 positions: Vec::new(),
540 is_new: false,
541 })
542 .collect()
543 } else {
544 let candidates = all_worktrees
545 .iter()
546 .enumerate()
547 .map(|(ix, worktree)| StringMatchCandidate::new(ix, worktree.branch()))
548 .collect::<Vec<StringMatchCandidate>>();
549 fuzzy::match_strings(
550 &candidates,
551 &query,
552 true,
553 true,
554 10000,
555 &Default::default(),
556 cx.background_executor().clone(),
557 )
558 .await
559 .into_iter()
560 .map(|candidate| WorktreeEntry {
561 worktree: all_worktrees[candidate.candidate_id].clone(),
562 positions: candidate.positions,
563 is_new: false,
564 })
565 .collect()
566 };
567 picker
568 .update(cx, |picker, _| {
569 if !query.is_empty()
570 && !matches
571 .first()
572 .is_some_and(|entry| entry.worktree.branch() == query)
573 {
574 let query = query.replace(' ', "-");
575 matches.push(WorktreeEntry {
576 worktree: GitWorktree {
577 path: Default::default(),
578 ref_name: format!("refs/heads/{query}").into(),
579 sha: Default::default(),
580 },
581 positions: Vec::new(),
582 is_new: true,
583 })
584 }
585 let delegate = &mut picker.delegate;
586 delegate.matches = matches;
587 if delegate.matches.is_empty() {
588 delegate.selected_index = 0;
589 } else {
590 delegate.selected_index =
591 core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
592 }
593 delegate.last_query = query;
594 })
595 .log_err();
596 })
597 }
598
599 fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
600 let Some(entry) = self.matches.get(self.selected_index()) else {
601 return;
602 };
603 if entry.is_new {
604 self.create_worktree(&entry.worktree.branch(), secondary, None, window, cx);
605 } else {
606 self.open_worktree(&entry.worktree.path, secondary, window, cx);
607 }
608
609 cx.emit(DismissEvent);
610 }
611
612 fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
613 cx.emit(DismissEvent);
614 }
615
616 fn render_match(
617 &self,
618 ix: usize,
619 selected: bool,
620 _window: &mut Window,
621 cx: &mut Context<Picker<Self>>,
622 ) -> Option<Self::ListItem> {
623 let entry = &self.matches.get(ix)?;
624 let path = entry.worktree.path.to_string_lossy().to_string();
625 let sha = entry
626 .worktree
627 .sha
628 .clone()
629 .chars()
630 .take(7)
631 .collect::<String>();
632
633 let focus_handle = self.focus_handle.clone();
634 let icon = if let Some(default_branch) = self.default_branch.clone()
635 && entry.is_new
636 {
637 Some(
638 IconButton::new("worktree-from-default", IconName::GitBranchAlt)
639 .on_click(|_, window, cx| {
640 window.dispatch_action(WorktreeFromDefault.boxed_clone(), cx)
641 })
642 .on_right_click(|_, window, cx| {
643 window.dispatch_action(WorktreeFromDefaultOnWindow.boxed_clone(), cx)
644 })
645 .tooltip(move |_, cx| {
646 Tooltip::for_action_in(
647 format!("From default branch {default_branch}"),
648 &WorktreeFromDefault,
649 &focus_handle,
650 cx,
651 )
652 }),
653 )
654 } else {
655 None
656 };
657
658 let branch_name = if entry.is_new {
659 h_flex()
660 .gap_1()
661 .child(
662 Icon::new(IconName::Plus)
663 .size(IconSize::Small)
664 .color(Color::Muted),
665 )
666 .child(
667 Label::new(format!("Create worktree \"{}\"…", entry.worktree.branch()))
668 .single_line()
669 .truncate(),
670 )
671 .into_any_element()
672 } else {
673 h_flex()
674 .gap_1()
675 .child(
676 Icon::new(IconName::GitBranch)
677 .size(IconSize::Small)
678 .color(Color::Muted),
679 )
680 .child(HighlightedLabel::new(
681 entry.worktree.branch().to_owned(),
682 entry.positions.clone(),
683 ))
684 .truncate()
685 .into_any_element()
686 };
687
688 let sublabel = if entry.is_new {
689 format!(
690 "based off {}",
691 self.base_branch(cx).unwrap_or("the current branch")
692 )
693 } else {
694 format!("at {}", path)
695 };
696
697 Some(
698 ListItem::new(format!("worktree-menu-{ix}"))
699 .inset(true)
700 .spacing(ListItemSpacing::Sparse)
701 .toggle_state(selected)
702 .child(
703 v_flex()
704 .w_full()
705 .overflow_hidden()
706 .child(
707 h_flex()
708 .gap_6()
709 .justify_between()
710 .overflow_x_hidden()
711 .child(branch_name)
712 .when(!entry.is_new, |el| {
713 el.child(
714 Label::new(sha)
715 .size(LabelSize::Small)
716 .color(Color::Muted)
717 .into_element(),
718 )
719 }),
720 )
721 .child(
722 div().max_w_96().child(
723 Label::new(sublabel)
724 .size(LabelSize::Small)
725 .color(Color::Muted)
726 .truncate()
727 .into_any_element(),
728 ),
729 ),
730 )
731 .end_slot::<IconButton>(icon),
732 )
733 }
734
735 fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
736 Some("No worktrees found".into())
737 }
738
739 fn render_footer(&self, _: &mut Window, cx: &mut Context<Picker<Self>>) -> Option<AnyElement> {
740 let focus_handle = self.focus_handle.clone();
741
742 Some(
743 h_flex()
744 .w_full()
745 .p_1p5()
746 .gap_0p5()
747 .justify_end()
748 .border_t_1()
749 .border_color(cx.theme().colors().border_variant)
750 .child(
751 Button::new("open-in-new-window", "Open in new window")
752 .key_binding(
753 KeyBinding::for_action_in(&menu::Confirm, &focus_handle, cx)
754 .map(|kb| kb.size(rems_from_px(12.))),
755 )
756 .on_click(|_, window, cx| {
757 window.dispatch_action(menu::Confirm.boxed_clone(), cx)
758 }),
759 )
760 .child(
761 Button::new("open-in-window", "Open")
762 .key_binding(
763 KeyBinding::for_action_in(&menu::SecondaryConfirm, &focus_handle, cx)
764 .map(|kb| kb.size(rems_from_px(12.))),
765 )
766 .on_click(|_, window, cx| {
767 window.dispatch_action(menu::SecondaryConfirm.boxed_clone(), cx)
768 }),
769 )
770 .into_any(),
771 )
772 }
773}