1mod highlighted_workspace_location;
2
3use fuzzy::{StringMatch, StringMatchCandidate};
4use gpui::{
5 AnyElement, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView, Result,
6 Subscription, Task, View, ViewContext, WeakView,
7};
8use highlighted_workspace_location::HighlightedWorkspaceLocation;
9use ordered_float::OrderedFloat;
10use picker::{Picker, PickerDelegate};
11use serde::Deserialize;
12use std::sync::Arc;
13use ui::{prelude::*, tooltip_container, HighlightedLabel, ListItem, ListItemSpacing, Tooltip};
14use util::paths::PathExt;
15use workspace::{ModalView, Workspace, WorkspaceId, WorkspaceLocation, WORKSPACE_DB};
16
17#[derive(PartialEq, Clone, Deserialize, Default)]
18pub struct OpenRecent {
19 #[serde(default)]
20 pub create_new_window: bool,
21}
22
23gpui::impl_actions!(projects, [OpenRecent]);
24
25pub fn init(cx: &mut AppContext) {
26 cx.observe_new_views(RecentProjects::register).detach();
27}
28
29pub struct RecentProjects {
30 pub picker: View<Picker<RecentProjectsDelegate>>,
31 rem_width: f32,
32 _subscription: Subscription,
33}
34
35impl ModalView for RecentProjects {}
36
37impl RecentProjects {
38 fn new(delegate: RecentProjectsDelegate, rem_width: f32, cx: &mut ViewContext<Self>) -> Self {
39 let picker = cx.new_view(|cx| {
40 // We want to use a list when we render paths, because the items can have different heights (multiple paths).
41 if delegate.render_paths {
42 Picker::list(delegate, cx)
43 } else {
44 Picker::uniform_list(delegate, cx)
45 }
46 });
47 let _subscription = cx.subscribe(&picker, |_, _, _, cx| cx.emit(DismissEvent));
48 // We do not want to block the UI on a potentially lengthy call to DB, so we're gonna swap
49 // out workspace locations once the future runs to completion.
50 cx.spawn(|this, mut cx| async move {
51 let workspaces = WORKSPACE_DB
52 .recent_workspaces_on_disk()
53 .await
54 .unwrap_or_default();
55
56 this.update(&mut cx, move |this, cx| {
57 this.picker.update(cx, move |picker, cx| {
58 picker.delegate.workspaces = workspaces;
59 picker.update_matches(picker.query(cx), cx)
60 })
61 })
62 .ok()
63 })
64 .detach();
65 Self {
66 picker,
67 rem_width,
68 _subscription,
69 }
70 }
71
72 fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
73 workspace.register_action(|workspace, open_recent: &OpenRecent, cx| {
74 let Some(recent_projects) = workspace.active_modal::<Self>(cx) else {
75 if let Some(handler) = Self::open(workspace, open_recent.create_new_window, cx) {
76 handler.detach_and_log_err(cx);
77 }
78 return;
79 };
80
81 recent_projects.update(cx, |recent_projects, cx| {
82 recent_projects
83 .picker
84 .update(cx, |picker, cx| picker.cycle_selection(cx))
85 });
86 });
87 }
88
89 fn open(
90 _: &mut Workspace,
91 create_new_window: bool,
92 cx: &mut ViewContext<Workspace>,
93 ) -> Option<Task<Result<()>>> {
94 Some(cx.spawn(|workspace, mut cx| async move {
95 workspace.update(&mut cx, |workspace, cx| {
96 let weak_workspace = cx.view().downgrade();
97 workspace.toggle_modal(cx, |cx| {
98 let delegate =
99 RecentProjectsDelegate::new(weak_workspace, create_new_window, true);
100
101 let modal = Self::new(delegate, 34., cx);
102 modal
103 });
104 })?;
105 Ok(())
106 }))
107 }
108
109 pub fn open_popover(workspace: WeakView<Workspace>, cx: &mut WindowContext<'_>) -> View<Self> {
110 cx.new_view(|cx| {
111 Self::new(
112 RecentProjectsDelegate::new(workspace, false, false),
113 20.,
114 cx,
115 )
116 })
117 }
118}
119
120impl EventEmitter<DismissEvent> for RecentProjects {}
121
122impl FocusableView for RecentProjects {
123 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
124 self.picker.focus_handle(cx)
125 }
126}
127
128impl Render for RecentProjects {
129 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
130 v_flex()
131 .w(rems(self.rem_width))
132 .child(self.picker.clone())
133 .on_mouse_down_out(cx.listener(|this, _, cx| {
134 this.picker.update(cx, |this, cx| {
135 this.cancel(&Default::default(), cx);
136 })
137 }))
138 }
139}
140
141pub struct RecentProjectsDelegate {
142 workspace: WeakView<Workspace>,
143 workspaces: Vec<(WorkspaceId, WorkspaceLocation)>,
144 selected_match_index: usize,
145 matches: Vec<StringMatch>,
146 render_paths: bool,
147 create_new_window: bool,
148 // Flag to reset index when there is a new query vs not reset index when user delete an item
149 reset_selected_match_index: bool,
150}
151
152impl RecentProjectsDelegate {
153 fn new(workspace: WeakView<Workspace>, create_new_window: bool, render_paths: bool) -> Self {
154 Self {
155 workspace,
156 workspaces: vec![],
157 selected_match_index: 0,
158 matches: Default::default(),
159 create_new_window,
160 render_paths,
161 reset_selected_match_index: true,
162 }
163 }
164}
165impl EventEmitter<DismissEvent> for RecentProjectsDelegate {}
166impl PickerDelegate for RecentProjectsDelegate {
167 type ListItem = ListItem;
168
169 fn placeholder_text(&self, cx: &mut WindowContext) -> Arc<str> {
170 let (create_window, reuse_window) = if self.create_new_window {
171 (
172 cx.keystroke_text_for(&menu::Confirm),
173 cx.keystroke_text_for(&menu::SecondaryConfirm),
174 )
175 } else {
176 (
177 cx.keystroke_text_for(&menu::SecondaryConfirm),
178 cx.keystroke_text_for(&menu::Confirm),
179 )
180 };
181 Arc::from(format!(
182 "{reuse_window} reuses the window, {create_window} opens a new one",
183 ))
184 }
185
186 fn match_count(&self) -> usize {
187 self.matches.len()
188 }
189
190 fn selected_index(&self) -> usize {
191 self.selected_match_index
192 }
193
194 fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
195 self.selected_match_index = ix;
196 }
197
198 fn update_matches(
199 &mut self,
200 query: String,
201 cx: &mut ViewContext<Picker<Self>>,
202 ) -> gpui::Task<()> {
203 let query = query.trim_start();
204 let smart_case = query.chars().any(|c| c.is_uppercase());
205 let candidates = self
206 .workspaces
207 .iter()
208 .enumerate()
209 .map(|(id, (_, location))| {
210 let combined_string = location
211 .paths()
212 .iter()
213 .map(|path| path.compact().to_string_lossy().into_owned())
214 .collect::<Vec<_>>()
215 .join("");
216 StringMatchCandidate::new(id, combined_string)
217 })
218 .collect::<Vec<_>>();
219 self.matches = smol::block_on(fuzzy::match_strings(
220 candidates.as_slice(),
221 query,
222 smart_case,
223 100,
224 &Default::default(),
225 cx.background_executor().clone(),
226 ));
227 self.matches.sort_unstable_by_key(|m| m.candidate_id);
228
229 if self.reset_selected_match_index {
230 self.selected_match_index = self
231 .matches
232 .iter()
233 .enumerate()
234 .rev()
235 .max_by_key(|(_, m)| OrderedFloat(m.score))
236 .map(|(ix, _)| ix)
237 .unwrap_or(0);
238 }
239 self.reset_selected_match_index = true;
240 Task::ready(())
241 }
242
243 fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
244 if let Some((selected_match, workspace)) = self
245 .matches
246 .get(self.selected_index())
247 .zip(self.workspace.upgrade())
248 {
249 let (candidate_workspace_id, candidate_workspace_location) =
250 &self.workspaces[selected_match.candidate_id];
251 let replace_current_window = if self.create_new_window {
252 secondary
253 } else {
254 !secondary
255 };
256 workspace
257 .update(cx, |workspace, cx| {
258 if workspace.database_id() != *candidate_workspace_id {
259 let candidate_paths = candidate_workspace_location.paths().as_ref().clone();
260 if replace_current_window {
261 cx.spawn(move |workspace, mut cx| async move {
262 let continue_replacing = workspace
263 .update(&mut cx, |workspace, cx| {
264 workspace.prepare_to_close(true, cx)
265 })?
266 .await?;
267 if continue_replacing {
268 workspace
269 .update(&mut cx, |workspace, cx| {
270 workspace.open_workspace_for_paths(
271 replace_current_window,
272 candidate_paths,
273 cx,
274 )
275 })?
276 .await
277 } else {
278 Ok(())
279 }
280 })
281 } else {
282 workspace.open_workspace_for_paths(
283 replace_current_window,
284 candidate_paths,
285 cx,
286 )
287 }
288 } else {
289 Task::ready(Ok(()))
290 }
291 })
292 .detach_and_log_err(cx);
293 cx.emit(DismissEvent);
294 }
295 }
296
297 fn dismissed(&mut self, _: &mut ViewContext<Picker<Self>>) {}
298
299 fn render_match(
300 &self,
301 ix: usize,
302 selected: bool,
303 cx: &mut ViewContext<Picker<Self>>,
304 ) -> Option<Self::ListItem> {
305 let Some(r#match) = self.matches.get(ix) else {
306 return None;
307 };
308
309 let (workspace_id, location) = &self.workspaces[r#match.candidate_id];
310 let highlighted_location: HighlightedWorkspaceLocation =
311 HighlightedWorkspaceLocation::new(&r#match, location);
312 let tooltip_highlighted_location = highlighted_location.clone();
313
314 let is_current_workspace = self.is_current_workspace(*workspace_id, cx);
315 Some(
316 ListItem::new(ix)
317 .inset(true)
318 .spacing(ListItemSpacing::Sparse)
319 .selected(selected)
320 .child(
321 v_flex()
322 .child(highlighted_location.names)
323 .when(self.render_paths, |this| {
324 this.children(highlighted_location.paths.into_iter().map(|path| {
325 HighlightedLabel::new(path.text, path.highlight_positions)
326 .size(LabelSize::Small)
327 .color(Color::Muted)
328 }))
329 }),
330 )
331 .when(!is_current_workspace, |el| {
332 let delete_button = div()
333 .child(
334 IconButton::new("delete", IconName::Close)
335 .icon_size(IconSize::Small)
336 .on_click(cx.listener(move |this, _event, cx| {
337 cx.stop_propagation();
338 cx.prevent_default();
339
340 this.delegate.delete_recent_project(ix, cx)
341 }))
342 .tooltip(|cx| Tooltip::text("Delete From Recent Projects...", cx)),
343 )
344 .into_any_element();
345
346 if self.selected_index() == ix {
347 el.end_slot::<AnyElement>(delete_button)
348 } else {
349 el.end_hover_slot::<AnyElement>(delete_button)
350 }
351 })
352 .tooltip(move |cx| {
353 let tooltip_highlighted_location = tooltip_highlighted_location.clone();
354 cx.new_view(move |_| MatchTooltip {
355 highlighted_location: tooltip_highlighted_location,
356 })
357 .into()
358 }),
359 )
360 }
361}
362
363impl RecentProjectsDelegate {
364 fn delete_recent_project(&self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
365 if let Some(selected_match) = self.matches.get(ix) {
366 let (workspace_id, _) = self.workspaces[selected_match.candidate_id];
367 cx.spawn(move |this, mut cx| async move {
368 let _ = WORKSPACE_DB.delete_workspace_by_id(workspace_id).await;
369 let workspaces = WORKSPACE_DB
370 .recent_workspaces_on_disk()
371 .await
372 .unwrap_or_default();
373 this.update(&mut cx, move |picker, cx| {
374 picker.delegate.workspaces = workspaces;
375 picker.delegate.set_selected_index(ix - 1, cx);
376 picker.delegate.reset_selected_match_index = false;
377 picker.update_matches(picker.query(cx), cx)
378 })
379 })
380 .detach();
381 }
382 }
383
384 fn is_current_workspace(
385 &self,
386 workspace_id: WorkspaceId,
387 cx: &mut ViewContext<Picker<Self>>,
388 ) -> bool {
389 if let Some(workspace) = self.workspace.upgrade() {
390 let workspace = workspace.read(cx);
391 if workspace_id == workspace.database_id() {
392 return true;
393 }
394 }
395
396 false
397 }
398}
399struct MatchTooltip {
400 highlighted_location: HighlightedWorkspaceLocation,
401}
402
403impl Render for MatchTooltip {
404 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
405 tooltip_container(cx, |div, _| {
406 div.children(
407 self.highlighted_location
408 .paths
409 .clone()
410 .into_iter()
411 .map(|path| {
412 HighlightedLabel::new(path.text, path.highlight_positions)
413 .size(LabelSize::Small)
414 .color(Color::Muted)
415 }),
416 )
417 })
418 }
419}
420
421#[cfg(test)]
422mod tests {
423 use std::path::PathBuf;
424
425 use editor::Editor;
426 use gpui::{TestAppContext, WindowHandle};
427 use project::Project;
428 use serde_json::json;
429 use workspace::{open_paths, AppState};
430
431 use super::*;
432
433 #[gpui::test]
434 async fn test_prompts_on_dirty_before_submit(cx: &mut TestAppContext) {
435 let app_state = init_test(cx);
436 app_state
437 .fs
438 .as_fake()
439 .insert_tree(
440 "/dir",
441 json!({
442 "main.ts": "a"
443 }),
444 )
445 .await;
446 cx.update(|cx| open_paths(&[PathBuf::from("/dir/main.ts")], &app_state, None, cx))
447 .await
448 .unwrap();
449 assert_eq!(cx.update(|cx| cx.windows().len()), 1);
450
451 let workspace = cx.update(|cx| cx.windows()[0].downcast::<Workspace>().unwrap());
452 workspace
453 .update(cx, |workspace, _| assert!(!workspace.is_edited()))
454 .unwrap();
455
456 let editor = workspace
457 .read_with(cx, |workspace, cx| {
458 workspace
459 .active_item(cx)
460 .unwrap()
461 .downcast::<Editor>()
462 .unwrap()
463 })
464 .unwrap();
465 workspace
466 .update(cx, |_, cx| {
467 editor.update(cx, |editor, cx| editor.insert("EDIT", cx));
468 })
469 .unwrap();
470 workspace
471 .update(cx, |workspace, _| assert!(workspace.is_edited(), "After inserting more text into the editor without saving, we should have a dirty project"))
472 .unwrap();
473
474 let recent_projects_picker = open_recent_projects(&workspace, cx);
475 workspace
476 .update(cx, |_, cx| {
477 recent_projects_picker.update(cx, |picker, cx| {
478 assert_eq!(picker.query(cx), "");
479 let delegate = &mut picker.delegate;
480 delegate.matches = vec![StringMatch {
481 candidate_id: 0,
482 score: 1.0,
483 positions: Vec::new(),
484 string: "fake candidate".to_string(),
485 }];
486 delegate.workspaces = vec![(0, WorkspaceLocation::new(vec!["/test/path/"]))];
487 });
488 })
489 .unwrap();
490
491 assert!(
492 !cx.has_pending_prompt(),
493 "Should have no pending prompt on dirty project before opening the new recent project"
494 );
495 cx.dispatch_action((*workspace).into(), menu::Confirm);
496 workspace
497 .update(cx, |workspace, cx| {
498 assert!(
499 workspace.active_modal::<RecentProjects>(cx).is_none(),
500 "Should remove the modal after selecting new recent project"
501 )
502 })
503 .unwrap();
504 assert!(
505 cx.has_pending_prompt(),
506 "Dirty workspace should prompt before opening the new recent project"
507 );
508 // Cancel
509 cx.simulate_prompt_answer(0);
510 assert!(
511 !cx.has_pending_prompt(),
512 "Should have no pending prompt after cancelling"
513 );
514 workspace
515 .update(cx, |workspace, _| {
516 assert!(
517 workspace.is_edited(),
518 "Should be in the same dirty project after cancelling"
519 )
520 })
521 .unwrap();
522 }
523
524 fn open_recent_projects(
525 workspace: &WindowHandle<Workspace>,
526 cx: &mut TestAppContext,
527 ) -> View<Picker<RecentProjectsDelegate>> {
528 cx.dispatch_action(
529 (*workspace).into(),
530 OpenRecent {
531 create_new_window: false,
532 },
533 );
534 workspace
535 .update(cx, |workspace, cx| {
536 workspace
537 .active_modal::<RecentProjects>(cx)
538 .unwrap()
539 .read(cx)
540 .picker
541 .clone()
542 })
543 .unwrap()
544 }
545
546 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
547 cx.update(|cx| {
548 let state = AppState::test(cx);
549 language::init(cx);
550 crate::init(cx);
551 editor::init(cx);
552 workspace::init_settings(cx);
553 Project::init_settings(cx);
554 state
555 })
556 }
557}