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