1pub mod disconnected_overlay;
2mod remote_servers;
3mod ssh_connections;
4pub use ssh_connections::{is_connecting_over_ssh, open_ssh_project};
5
6use disconnected_overlay::DisconnectedOverlay;
7use fuzzy::{StringMatch, StringMatchCandidate};
8use gpui::{
9 Action, AnyElement, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,
10 Subscription, Task, View, ViewContext, WeakView,
11};
12use itertools::Itertools;
13use ordered_float::OrderedFloat;
14use picker::{
15 highlighted_match_with_paths::{HighlightedMatchWithPaths, HighlightedText},
16 Picker, PickerDelegate,
17};
18pub use remote_servers::RemoteServerProjects;
19use settings::Settings;
20pub use ssh_connections::SshSettings;
21use std::{
22 path::{Path, PathBuf},
23 sync::Arc,
24};
25use ui::{prelude::*, tooltip_container, KeyBinding, ListItem, ListItemSpacing, Tooltip};
26use util::{paths::PathExt, ResultExt};
27use workspace::{
28 CloseIntent, ModalView, OpenOptions, SerializedWorkspaceLocation, Workspace, WorkspaceId,
29 WORKSPACE_DB,
30};
31use zed_actions::{OpenRecent, OpenRemote};
32
33pub fn init(cx: &mut AppContext) {
34 SshSettings::register(cx);
35 cx.observe_new_views(RecentProjects::register).detach();
36 cx.observe_new_views(RemoteServerProjects::register)
37 .detach();
38 cx.observe_new_views(DisconnectedOverlay::register).detach();
39}
40
41pub struct RecentProjects {
42 pub picker: View<Picker<RecentProjectsDelegate>>,
43 rem_width: f32,
44 _subscription: Subscription,
45}
46
47impl ModalView for RecentProjects {}
48
49impl RecentProjects {
50 fn new(delegate: RecentProjectsDelegate, rem_width: f32, cx: &mut ViewContext<Self>) -> Self {
51 let picker = cx.new_view(|cx| {
52 // We want to use a list when we render paths, because the items can have different heights (multiple paths).
53 if delegate.render_paths {
54 Picker::list(delegate, cx)
55 } else {
56 Picker::uniform_list(delegate, cx)
57 }
58 });
59 let _subscription = cx.subscribe(&picker, |_, _, _, cx| cx.emit(DismissEvent));
60 // We do not want to block the UI on a potentially lengthy call to DB, so we're gonna swap
61 // out workspace locations once the future runs to completion.
62 cx.spawn(|this, mut cx| async move {
63 let workspaces = WORKSPACE_DB
64 .recent_workspaces_on_disk()
65 .await
66 .log_err()
67 .unwrap_or_default();
68 this.update(&mut cx, move |this, cx| {
69 this.picker.update(cx, move |picker, cx| {
70 picker.delegate.set_workspaces(workspaces);
71 picker.update_matches(picker.query(cx), cx)
72 })
73 })
74 .ok()
75 })
76 .detach();
77 Self {
78 picker,
79 rem_width,
80 _subscription,
81 }
82 }
83
84 fn register(workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>) {
85 workspace.register_action(|workspace, open_recent: &OpenRecent, cx| {
86 let Some(recent_projects) = workspace.active_modal::<Self>(cx) else {
87 Self::open(workspace, open_recent.create_new_window, cx);
88 return;
89 };
90
91 recent_projects.update(cx, |recent_projects, cx| {
92 recent_projects
93 .picker
94 .update(cx, |picker, cx| picker.cycle_selection(cx))
95 });
96 });
97 }
98
99 pub fn open(
100 workspace: &mut Workspace,
101 create_new_window: bool,
102 cx: &mut ViewContext<Workspace>,
103 ) {
104 let weak = cx.view().downgrade();
105 workspace.toggle_modal(cx, |cx| {
106 let delegate = RecentProjectsDelegate::new(weak, create_new_window, true);
107
108 Self::new(delegate, 34., cx)
109 })
110 }
111}
112
113impl EventEmitter<DismissEvent> for RecentProjects {}
114
115impl FocusableView for RecentProjects {
116 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
117 self.picker.focus_handle(cx)
118 }
119}
120
121impl Render for RecentProjects {
122 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
123 v_flex()
124 .w(rems(self.rem_width))
125 .child(self.picker.clone())
126 .on_mouse_down_out(cx.listener(|this, _, cx| {
127 this.picker.update(cx, |this, cx| {
128 this.cancel(&Default::default(), cx);
129 })
130 }))
131 }
132}
133
134pub struct RecentProjectsDelegate {
135 workspace: WeakView<Workspace>,
136 workspaces: Vec<(WorkspaceId, SerializedWorkspaceLocation)>,
137 selected_match_index: usize,
138 matches: Vec<StringMatch>,
139 render_paths: bool,
140 create_new_window: bool,
141 // Flag to reset index when there is a new query vs not reset index when user delete an item
142 reset_selected_match_index: bool,
143 has_any_non_local_projects: bool,
144}
145
146impl RecentProjectsDelegate {
147 fn new(workspace: WeakView<Workspace>, create_new_window: bool, render_paths: bool) -> Self {
148 Self {
149 workspace,
150 workspaces: Vec::new(),
151 selected_match_index: 0,
152 matches: Default::default(),
153 create_new_window,
154 render_paths,
155 reset_selected_match_index: true,
156 has_any_non_local_projects: false,
157 }
158 }
159
160 pub fn set_workspaces(&mut self, workspaces: Vec<(WorkspaceId, SerializedWorkspaceLocation)>) {
161 self.workspaces = workspaces;
162 self.has_any_non_local_projects = !self
163 .workspaces
164 .iter()
165 .all(|(_, location)| matches!(location, SerializedWorkspaceLocation::Local(_, _)));
166 }
167}
168impl EventEmitter<DismissEvent> for RecentProjectsDelegate {}
169impl PickerDelegate for RecentProjectsDelegate {
170 type ListItem = ListItem;
171
172 fn placeholder_text(&self, cx: &mut WindowContext) -> Arc<str> {
173 let (create_window, reuse_window) = if self.create_new_window {
174 (
175 cx.keystroke_text_for(&menu::Confirm),
176 cx.keystroke_text_for(&menu::SecondaryConfirm),
177 )
178 } else {
179 (
180 cx.keystroke_text_for(&menu::SecondaryConfirm),
181 cx.keystroke_text_for(&menu::Confirm),
182 )
183 };
184 Arc::from(format!(
185 "{reuse_window} reuses this window, {create_window} opens a new one",
186 ))
187 }
188
189 fn match_count(&self) -> usize {
190 self.matches.len()
191 }
192
193 fn selected_index(&self) -> usize {
194 self.selected_match_index
195 }
196
197 fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
198 self.selected_match_index = ix;
199 }
200
201 fn update_matches(
202 &mut self,
203 query: String,
204 cx: &mut ViewContext<Picker<Self>>,
205 ) -> gpui::Task<()> {
206 let query = query.trim_start();
207 let smart_case = query.chars().any(|c| c.is_uppercase());
208 let candidates = self
209 .workspaces
210 .iter()
211 .enumerate()
212 .filter(|(_, (id, _))| !self.is_current_workspace(*id, cx))
213 .map(|(id, (_, location))| {
214 let combined_string = match location {
215 SerializedWorkspaceLocation::Local(paths, order) => order
216 .order()
217 .iter()
218 .zip(paths.paths().iter())
219 .sorted_by_key(|(i, _)| *i)
220 .map(|(_, path)| path.compact().to_string_lossy().into_owned())
221 .collect::<Vec<_>>()
222 .join(""),
223 SerializedWorkspaceLocation::Ssh(ssh_project) => ssh_project
224 .ssh_urls()
225 .iter()
226 .map(|path| path.to_string_lossy().to_string())
227 .collect::<Vec<_>>()
228 .join(""),
229 };
230
231 StringMatchCandidate::new(id, combined_string)
232 })
233 .collect::<Vec<_>>();
234 self.matches = smol::block_on(fuzzy::match_strings(
235 candidates.as_slice(),
236 query,
237 smart_case,
238 100,
239 &Default::default(),
240 cx.background_executor().clone(),
241 ));
242 self.matches.sort_unstable_by_key(|m| m.candidate_id);
243
244 if self.reset_selected_match_index {
245 self.selected_match_index = self
246 .matches
247 .iter()
248 .enumerate()
249 .rev()
250 .max_by_key(|(_, m)| OrderedFloat(m.score))
251 .map(|(ix, _)| ix)
252 .unwrap_or(0);
253 }
254 self.reset_selected_match_index = true;
255 Task::ready(())
256 }
257
258 fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
259 if let Some((selected_match, workspace)) = self
260 .matches
261 .get(self.selected_index())
262 .zip(self.workspace.upgrade())
263 {
264 let (candidate_workspace_id, candidate_workspace_location) =
265 &self.workspaces[selected_match.candidate_id];
266 let replace_current_window = if self.create_new_window {
267 secondary
268 } else {
269 !secondary
270 };
271 workspace
272 .update(cx, |workspace, cx| {
273 if workspace.database_id() == Some(*candidate_workspace_id) {
274 Task::ready(Ok(()))
275 } else {
276 match candidate_workspace_location {
277 SerializedWorkspaceLocation::Local(paths, _) => {
278 let paths = paths.paths().to_vec();
279 if replace_current_window {
280 cx.spawn(move |workspace, mut cx| async move {
281 let continue_replacing = workspace
282 .update(&mut cx, |workspace, cx| {
283 workspace.prepare_to_close(
284 CloseIntent::ReplaceWindow,
285 cx,
286 )
287 })?
288 .await?;
289 if continue_replacing {
290 workspace
291 .update(&mut cx, |workspace, cx| {
292 workspace
293 .open_workspace_for_paths(true, paths, cx)
294 })?
295 .await
296 } else {
297 Ok(())
298 }
299 })
300 } else {
301 workspace.open_workspace_for_paths(false, paths, cx)
302 }
303 }
304 SerializedWorkspaceLocation::Ssh(ssh_project) => {
305 let app_state = workspace.app_state().clone();
306
307 let replace_window = if replace_current_window {
308 cx.window_handle().downcast::<Workspace>()
309 } else {
310 None
311 };
312
313 let open_options = OpenOptions {
314 replace_window,
315 ..Default::default()
316 };
317
318 let connection_options = SshSettings::get_global(cx)
319 .connection_options_for(
320 ssh_project.host.clone(),
321 ssh_project.port,
322 ssh_project.user.clone(),
323 );
324
325 let paths = ssh_project.paths.iter().map(PathBuf::from).collect();
326
327 cx.spawn(|_, mut cx| async move {
328 open_ssh_project(
329 connection_options,
330 paths,
331 app_state,
332 open_options,
333 &mut cx,
334 )
335 .await
336 })
337 }
338 }
339 }
340 })
341 .detach_and_log_err(cx);
342 cx.emit(DismissEvent);
343 }
344 }
345
346 fn dismissed(&mut self, _: &mut ViewContext<Picker<Self>>) {}
347
348 fn no_matches_text(&self, _cx: &mut WindowContext) -> SharedString {
349 if self.workspaces.is_empty() {
350 "Recently opened projects will show up here".into()
351 } else {
352 "No matches".into()
353 }
354 }
355
356 fn render_match(
357 &self,
358 ix: usize,
359 selected: bool,
360 cx: &mut ViewContext<Picker<Self>>,
361 ) -> Option<Self::ListItem> {
362 let hit = self.matches.get(ix)?;
363
364 let (_, location) = self.workspaces.get(hit.candidate_id)?;
365
366 let mut path_start_offset = 0;
367 let paths = match location {
368 SerializedWorkspaceLocation::Local(paths, order) => Arc::new(
369 order
370 .order()
371 .iter()
372 .zip(paths.paths().iter())
373 .sorted_by_key(|(i, _)| **i)
374 .map(|(_, path)| path.compact())
375 .collect(),
376 ),
377 SerializedWorkspaceLocation::Ssh(ssh_project) => Arc::new(ssh_project.ssh_urls()),
378 };
379
380 let (match_labels, paths): (Vec<_>, Vec<_>) = paths
381 .iter()
382 .map(|path| {
383 let highlighted_text =
384 highlights_for_path(path.as_ref(), &hit.positions, path_start_offset);
385
386 path_start_offset += highlighted_text.1.char_count;
387 highlighted_text
388 })
389 .unzip();
390
391 let highlighted_match = HighlightedMatchWithPaths {
392 match_label: HighlightedText::join(match_labels.into_iter().flatten(), ", "),
393 paths,
394 };
395
396 Some(
397 ListItem::new(ix)
398 .selected(selected)
399 .inset(true)
400 .spacing(ListItemSpacing::Sparse)
401 .child(
402 h_flex()
403 .flex_grow()
404 .gap_3()
405 .when(self.has_any_non_local_projects, |this| {
406 this.child(match location {
407 SerializedWorkspaceLocation::Local(_, _) => {
408 Icon::new(IconName::Screen)
409 .color(Color::Muted)
410 .into_any_element()
411 }
412 SerializedWorkspaceLocation::Ssh(_) => Icon::new(IconName::Server)
413 .color(Color::Muted)
414 .into_any_element(),
415 })
416 })
417 .child({
418 let mut highlighted = highlighted_match.clone();
419 if !self.render_paths {
420 highlighted.paths.clear();
421 }
422 highlighted.render(cx)
423 }),
424 )
425 .map(|el| {
426 let delete_button = div()
427 .child(
428 IconButton::new("delete", IconName::Close)
429 .icon_size(IconSize::Small)
430 .on_click(cx.listener(move |this, _event, cx| {
431 cx.stop_propagation();
432 cx.prevent_default();
433
434 this.delegate.delete_recent_project(ix, cx)
435 }))
436 .tooltip(|cx| Tooltip::text("Delete from Recent Projects...", cx)),
437 )
438 .into_any_element();
439
440 if self.selected_index() == ix {
441 el.end_slot::<AnyElement>(delete_button)
442 } else {
443 el.end_hover_slot::<AnyElement>(delete_button)
444 }
445 })
446 .tooltip(move |cx| {
447 let tooltip_highlighted_location = highlighted_match.clone();
448 cx.new_view(move |_| MatchTooltip {
449 highlighted_location: tooltip_highlighted_location,
450 })
451 .into()
452 }),
453 )
454 }
455
456 fn render_footer(&self, cx: &mut ViewContext<Picker<Self>>) -> Option<AnyElement> {
457 Some(
458 h_flex()
459 .w_full()
460 .p_2()
461 .gap_2()
462 .justify_end()
463 .border_t_1()
464 .border_color(cx.theme().colors().border_variant)
465 .child(
466 Button::new("remote", "Open Remote Folder")
467 .key_binding(KeyBinding::for_action(&OpenRemote, cx))
468 .on_click(|_, cx| cx.dispatch_action(OpenRemote.boxed_clone())),
469 )
470 .child(
471 Button::new("local", "Open Local Folder")
472 .key_binding(KeyBinding::for_action(&workspace::Open, cx))
473 .on_click(|_, cx| cx.dispatch_action(workspace::Open.boxed_clone())),
474 )
475 .into_any(),
476 )
477 }
478}
479
480// Compute the highlighted text for the name and path
481fn highlights_for_path(
482 path: &Path,
483 match_positions: &Vec<usize>,
484 path_start_offset: usize,
485) -> (Option<HighlightedText>, HighlightedText) {
486 let path_string = path.to_string_lossy();
487 let path_char_count = path_string.chars().count();
488 // Get the subset of match highlight positions that line up with the given path.
489 // Also adjusts them to start at the path start
490 let path_positions = match_positions
491 .iter()
492 .copied()
493 .skip_while(|position| *position < path_start_offset)
494 .take_while(|position| *position < path_start_offset + path_char_count)
495 .map(|position| position - path_start_offset)
496 .collect::<Vec<_>>();
497
498 // Again subset the highlight positions to just those that line up with the file_name
499 // again adjusted to the start of the file_name
500 let file_name_text_and_positions = path.file_name().map(|file_name| {
501 let text = file_name.to_string_lossy();
502 let char_count = text.chars().count();
503 let file_name_start = path_char_count - char_count;
504 let highlight_positions = path_positions
505 .iter()
506 .copied()
507 .skip_while(|position| *position < file_name_start)
508 .take_while(|position| *position < file_name_start + char_count)
509 .map(|position| position - file_name_start)
510 .collect::<Vec<_>>();
511 HighlightedText {
512 text: text.to_string(),
513 highlight_positions,
514 char_count,
515 color: Color::Default,
516 }
517 });
518
519 (
520 file_name_text_and_positions,
521 HighlightedText {
522 text: path_string.to_string(),
523 highlight_positions: path_positions,
524 char_count: path_char_count,
525 color: Color::Default,
526 },
527 )
528}
529impl RecentProjectsDelegate {
530 fn delete_recent_project(&self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
531 if let Some(selected_match) = self.matches.get(ix) {
532 let (workspace_id, _) = self.workspaces[selected_match.candidate_id];
533 cx.spawn(move |this, mut cx| async move {
534 let _ = WORKSPACE_DB.delete_workspace_by_id(workspace_id).await;
535 let workspaces = WORKSPACE_DB
536 .recent_workspaces_on_disk()
537 .await
538 .unwrap_or_default();
539 this.update(&mut cx, move |picker, cx| {
540 picker.delegate.set_workspaces(workspaces);
541 picker.delegate.set_selected_index(ix.saturating_sub(1), cx);
542 picker.delegate.reset_selected_match_index = false;
543 picker.update_matches(picker.query(cx), cx)
544 })
545 })
546 .detach();
547 }
548 }
549
550 fn is_current_workspace(
551 &self,
552 workspace_id: WorkspaceId,
553 cx: &mut ViewContext<Picker<Self>>,
554 ) -> bool {
555 if let Some(workspace) = self.workspace.upgrade() {
556 let workspace = workspace.read(cx);
557 if Some(workspace_id) == workspace.database_id() {
558 return true;
559 }
560 }
561
562 false
563 }
564}
565struct MatchTooltip {
566 highlighted_location: HighlightedMatchWithPaths,
567}
568
569impl Render for MatchTooltip {
570 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
571 tooltip_container(cx, |div, _| {
572 self.highlighted_location.render_paths_children(div)
573 })
574 }
575}
576
577#[cfg(test)]
578mod tests {
579 use std::path::PathBuf;
580
581 use editor::Editor;
582 use gpui::{TestAppContext, UpdateGlobal, WindowHandle};
583 use project::{project_settings::ProjectSettings, Project};
584 use serde_json::json;
585 use settings::SettingsStore;
586 use workspace::{open_paths, AppState};
587
588 use super::*;
589
590 #[gpui::test]
591 async fn test_prompts_on_dirty_before_submit(cx: &mut TestAppContext) {
592 let app_state = init_test(cx);
593
594 cx.update(|cx| {
595 SettingsStore::update_global(cx, |store, cx| {
596 store.update_user_settings::<ProjectSettings>(cx, |settings| {
597 settings.session.restore_unsaved_buffers = false
598 });
599 });
600 });
601
602 app_state
603 .fs
604 .as_fake()
605 .insert_tree(
606 "/dir",
607 json!({
608 "main.ts": "a"
609 }),
610 )
611 .await;
612 cx.update(|cx| {
613 open_paths(
614 &[PathBuf::from("/dir/main.ts")],
615 app_state,
616 workspace::OpenOptions::default(),
617 cx,
618 )
619 })
620 .await
621 .unwrap();
622 assert_eq!(cx.update(|cx| cx.windows().len()), 1);
623
624 let workspace = cx.update(|cx| cx.windows()[0].downcast::<Workspace>().unwrap());
625 workspace
626 .update(cx, |workspace, _| assert!(!workspace.is_edited()))
627 .unwrap();
628
629 let editor = workspace
630 .read_with(cx, |workspace, cx| {
631 workspace
632 .active_item(cx)
633 .unwrap()
634 .downcast::<Editor>()
635 .unwrap()
636 })
637 .unwrap();
638 workspace
639 .update(cx, |_, cx| {
640 editor.update(cx, |editor, cx| editor.insert("EDIT", cx));
641 })
642 .unwrap();
643 workspace
644 .update(cx, |workspace, _| assert!(workspace.is_edited(), "After inserting more text into the editor without saving, we should have a dirty project"))
645 .unwrap();
646
647 let recent_projects_picker = open_recent_projects(&workspace, cx);
648 workspace
649 .update(cx, |_, cx| {
650 recent_projects_picker.update(cx, |picker, cx| {
651 assert_eq!(picker.query(cx), "");
652 let delegate = &mut picker.delegate;
653 delegate.matches = vec![StringMatch {
654 candidate_id: 0,
655 score: 1.0,
656 positions: Vec::new(),
657 string: "fake candidate".to_string(),
658 }];
659 delegate.set_workspaces(vec![(
660 WorkspaceId::default(),
661 SerializedWorkspaceLocation::from_local_paths(vec!["/test/path/"]),
662 )]);
663 });
664 })
665 .unwrap();
666
667 assert!(
668 !cx.has_pending_prompt(),
669 "Should have no pending prompt on dirty project before opening the new recent project"
670 );
671 cx.dispatch_action(*workspace, menu::Confirm);
672 workspace
673 .update(cx, |workspace, cx| {
674 assert!(
675 workspace.active_modal::<RecentProjects>(cx).is_none(),
676 "Should remove the modal after selecting new recent project"
677 )
678 })
679 .unwrap();
680 assert!(
681 cx.has_pending_prompt(),
682 "Dirty workspace should prompt before opening the new recent project"
683 );
684 // Cancel
685 cx.simulate_prompt_answer(0);
686 assert!(
687 !cx.has_pending_prompt(),
688 "Should have no pending prompt after cancelling"
689 );
690 workspace
691 .update(cx, |workspace, _| {
692 assert!(
693 workspace.is_edited(),
694 "Should be in the same dirty project after cancelling"
695 )
696 })
697 .unwrap();
698 }
699
700 fn open_recent_projects(
701 workspace: &WindowHandle<Workspace>,
702 cx: &mut TestAppContext,
703 ) -> View<Picker<RecentProjectsDelegate>> {
704 cx.dispatch_action(
705 (*workspace).into(),
706 OpenRecent {
707 create_new_window: false,
708 },
709 );
710 workspace
711 .update(cx, |workspace, cx| {
712 workspace
713 .active_modal::<RecentProjects>(cx)
714 .unwrap()
715 .read(cx)
716 .picker
717 .clone()
718 })
719 .unwrap()
720 }
721
722 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
723 cx.update(|cx| {
724 let state = AppState::test(cx);
725 language::init(cx);
726 crate::init(cx);
727 editor::init(cx);
728 workspace::init_settings(cx);
729 Project::init_settings(cx);
730 state
731 })
732 }
733}