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 std::sync::Arc;
12use ui::{prelude::*, tooltip_container, HighlightedLabel, 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 .child(self.picker.clone())
115 .on_mouse_down_out(cx.listener(|this, _, cx| {
116 this.picker.update(cx, |this, cx| {
117 this.cancel(&Default::default(), cx);
118 })
119 }))
120 }
121}
122
123pub struct RecentProjectsDelegate {
124 workspace: WeakView<Workspace>,
125 workspaces: Vec<(WorkspaceId, WorkspaceLocation)>,
126 selected_match_index: usize,
127 matches: Vec<StringMatch>,
128 render_paths: bool,
129 // Flag to reset index when there is a new query vs not reset index when user delete an item
130 reset_selected_match_index: bool,
131}
132
133impl RecentProjectsDelegate {
134 fn new(workspace: WeakView<Workspace>, render_paths: bool) -> Self {
135 Self {
136 workspace,
137 workspaces: vec![],
138 selected_match_index: 0,
139 matches: Default::default(),
140 render_paths,
141 reset_selected_match_index: true,
142 }
143 }
144}
145impl EventEmitter<DismissEvent> for RecentProjectsDelegate {}
146impl PickerDelegate for RecentProjectsDelegate {
147 type ListItem = ListItem;
148
149 fn placeholder_text(&self, cx: &mut WindowContext) -> Arc<str> {
150 Arc::from(format!(
151 "{} reuses the window, {} opens a new one",
152 cx.keystroke_text_for(&menu::Confirm),
153 cx.keystroke_text_for(&menu::SecondaryConfirm),
154 ))
155 }
156
157 fn match_count(&self) -> usize {
158 self.matches.len()
159 }
160
161 fn selected_index(&self) -> usize {
162 self.selected_match_index
163 }
164
165 fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
166 self.selected_match_index = ix;
167 }
168
169 fn update_matches(
170 &mut self,
171 query: String,
172 cx: &mut ViewContext<Picker<Self>>,
173 ) -> gpui::Task<()> {
174 let query = query.trim_start();
175 let smart_case = query.chars().any(|c| c.is_uppercase());
176 let candidates = self
177 .workspaces
178 .iter()
179 .enumerate()
180 .map(|(id, (_, location))| {
181 let combined_string = location
182 .paths()
183 .iter()
184 .map(|path| path.compact().to_string_lossy().into_owned())
185 .collect::<Vec<_>>()
186 .join("");
187 StringMatchCandidate::new(id, combined_string)
188 })
189 .collect::<Vec<_>>();
190 self.matches = smol::block_on(fuzzy::match_strings(
191 candidates.as_slice(),
192 query,
193 smart_case,
194 100,
195 &Default::default(),
196 cx.background_executor().clone(),
197 ));
198 self.matches.sort_unstable_by_key(|m| m.candidate_id);
199
200 if self.reset_selected_match_index {
201 self.selected_match_index = self
202 .matches
203 .iter()
204 .enumerate()
205 .rev()
206 .max_by_key(|(_, m)| OrderedFloat(m.score))
207 .map(|(ix, _)| ix)
208 .unwrap_or(0);
209 }
210 self.reset_selected_match_index = true;
211 Task::ready(())
212 }
213
214 fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
215 if let Some((selected_match, workspace)) = self
216 .matches
217 .get(self.selected_index())
218 .zip(self.workspace.upgrade())
219 {
220 let (candidate_workspace_id, candidate_workspace_location) =
221 &self.workspaces[selected_match.candidate_id];
222 let replace_current_window = !secondary;
223 workspace
224 .update(cx, |workspace, cx| {
225 if workspace.database_id() != *candidate_workspace_id {
226 let candidate_paths = candidate_workspace_location.paths().as_ref().clone();
227 if replace_current_window {
228 cx.spawn(move |workspace, mut cx| async move {
229 let continue_replacing = workspace
230 .update(&mut cx, |workspace, cx| {
231 workspace.prepare_to_close(true, cx)
232 })?
233 .await?;
234 if continue_replacing {
235 workspace
236 .update(&mut cx, |workspace, cx| {
237 workspace.open_workspace_for_paths(
238 replace_current_window,
239 candidate_paths,
240 cx,
241 )
242 })?
243 .await
244 } else {
245 Ok(())
246 }
247 })
248 } else {
249 workspace.open_workspace_for_paths(
250 replace_current_window,
251 candidate_paths,
252 cx,
253 )
254 }
255 } else {
256 Task::ready(Ok(()))
257 }
258 })
259 .detach_and_log_err(cx);
260 cx.emit(DismissEvent);
261 }
262 }
263
264 fn dismissed(&mut self, _: &mut ViewContext<Picker<Self>>) {}
265
266 fn render_match(
267 &self,
268 ix: usize,
269 selected: bool,
270 cx: &mut ViewContext<Picker<Self>>,
271 ) -> Option<Self::ListItem> {
272 let Some(r#match) = self.matches.get(ix) else {
273 return None;
274 };
275
276 let (workspace_id, location) = &self.workspaces[r#match.candidate_id];
277 let highlighted_location: HighlightedWorkspaceLocation =
278 HighlightedWorkspaceLocation::new(&r#match, location);
279 let tooltip_highlighted_location = highlighted_location.clone();
280
281 let is_current_workspace = self.is_current_workspace(*workspace_id, cx);
282 Some(
283 ListItem::new(ix)
284 .inset(true)
285 .spacing(ListItemSpacing::Sparse)
286 .selected(selected)
287 .child(
288 v_flex()
289 .child(highlighted_location.names)
290 .when(self.render_paths, |this| {
291 this.children(highlighted_location.paths.into_iter().map(|path| {
292 HighlightedLabel::new(path.text, path.highlight_positions)
293 .size(LabelSize::Small)
294 .color(Color::Muted)
295 }))
296 }),
297 )
298 .when(!is_current_workspace, |el| {
299 let delete_button = div()
300 .child(
301 IconButton::new("delete", IconName::Close)
302 .icon_size(IconSize::Small)
303 .on_click(cx.listener(move |this, _event, cx| {
304 cx.stop_propagation();
305 cx.prevent_default();
306
307 this.delegate.delete_recent_project(ix, cx)
308 }))
309 .tooltip(|cx| Tooltip::text("Delete From Recent Projects...", cx)),
310 )
311 .into_any_element();
312
313 if self.selected_index() == ix {
314 el.end_slot::<AnyElement>(delete_button)
315 } else {
316 el.end_hover_slot::<AnyElement>(delete_button)
317 }
318 })
319 .tooltip(move |cx| {
320 let tooltip_highlighted_location = tooltip_highlighted_location.clone();
321 cx.new_view(move |_| MatchTooltip {
322 highlighted_location: tooltip_highlighted_location,
323 })
324 .into()
325 }),
326 )
327 }
328}
329
330impl RecentProjectsDelegate {
331 fn delete_recent_project(&self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
332 if let Some(selected_match) = self.matches.get(ix) {
333 let (workspace_id, _) = self.workspaces[selected_match.candidate_id];
334 cx.spawn(move |this, mut cx| async move {
335 let _ = WORKSPACE_DB.delete_workspace_by_id(workspace_id).await;
336 let workspaces = WORKSPACE_DB
337 .recent_workspaces_on_disk()
338 .await
339 .unwrap_or_default();
340 this.update(&mut cx, move |picker, cx| {
341 picker.delegate.workspaces = workspaces;
342 picker.delegate.set_selected_index(ix - 1, cx);
343 picker.delegate.reset_selected_match_index = false;
344 picker.update_matches(picker.query(cx), cx)
345 })
346 })
347 .detach();
348 }
349 }
350
351 fn is_current_workspace(
352 &self,
353 workspace_id: WorkspaceId,
354 cx: &mut ViewContext<Picker<Self>>,
355 ) -> bool {
356 if let Some(workspace) = self.workspace.upgrade() {
357 let workspace = workspace.read(cx);
358 if workspace_id == workspace.database_id() {
359 return true;
360 }
361 }
362
363 false
364 }
365}
366struct MatchTooltip {
367 highlighted_location: HighlightedWorkspaceLocation,
368}
369
370impl Render for MatchTooltip {
371 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
372 tooltip_container(cx, |div, _| {
373 div.children(
374 self.highlighted_location
375 .paths
376 .clone()
377 .into_iter()
378 .map(|path| {
379 HighlightedLabel::new(path.text, path.highlight_positions)
380 .size(LabelSize::Small)
381 .color(Color::Muted)
382 }),
383 )
384 })
385 }
386}
387
388#[cfg(test)]
389mod tests {
390 use std::path::PathBuf;
391
392 use editor::Editor;
393 use gpui::{TestAppContext, WindowHandle};
394 use project::Project;
395 use serde_json::json;
396 use workspace::{open_paths, AppState};
397
398 use super::*;
399
400 #[gpui::test]
401 async fn test_prompts_on_dirty_before_submit(cx: &mut TestAppContext) {
402 let app_state = init_test(cx);
403 app_state
404 .fs
405 .as_fake()
406 .insert_tree(
407 "/dir",
408 json!({
409 "main.ts": "a"
410 }),
411 )
412 .await;
413 cx.update(|cx| open_paths(&[PathBuf::from("/dir/main.ts")], &app_state, None, cx))
414 .await
415 .unwrap();
416 assert_eq!(cx.update(|cx| cx.windows().len()), 1);
417
418 let workspace = cx.update(|cx| cx.windows()[0].downcast::<Workspace>().unwrap());
419 workspace
420 .update(cx, |workspace, _| assert!(!workspace.is_edited()))
421 .unwrap();
422
423 let editor = workspace
424 .read_with(cx, |workspace, cx| {
425 workspace
426 .active_item(cx)
427 .unwrap()
428 .downcast::<Editor>()
429 .unwrap()
430 })
431 .unwrap();
432 workspace
433 .update(cx, |_, cx| {
434 editor.update(cx, |editor, cx| editor.insert("EDIT", cx));
435 })
436 .unwrap();
437 workspace
438 .update(cx, |workspace, _| assert!(workspace.is_edited(), "After inserting more text into the editor without saving, we should have a dirty project"))
439 .unwrap();
440
441 let recent_projects_picker = open_recent_projects(&workspace, cx);
442 workspace
443 .update(cx, |_, cx| {
444 recent_projects_picker.update(cx, |picker, cx| {
445 assert_eq!(picker.query(cx), "");
446 let delegate = &mut picker.delegate;
447 delegate.matches = vec![StringMatch {
448 candidate_id: 0,
449 score: 1.0,
450 positions: Vec::new(),
451 string: "fake candidate".to_string(),
452 }];
453 delegate.workspaces = vec![(0, WorkspaceLocation::new(vec!["/test/path/"]))];
454 });
455 })
456 .unwrap();
457
458 assert!(
459 !cx.has_pending_prompt(),
460 "Should have no pending prompt on dirty project before opening the new recent project"
461 );
462 cx.dispatch_action((*workspace).into(), menu::Confirm);
463 workspace
464 .update(cx, |workspace, cx| {
465 assert!(
466 workspace.active_modal::<RecentProjects>(cx).is_none(),
467 "Should remove the modal after selecting new recent project"
468 )
469 })
470 .unwrap();
471 assert!(
472 cx.has_pending_prompt(),
473 "Dirty workspace should prompt before opening the new recent project"
474 );
475 // Cancel
476 cx.simulate_prompt_answer(0);
477 assert!(
478 !cx.has_pending_prompt(),
479 "Should have no pending prompt after cancelling"
480 );
481 workspace
482 .update(cx, |workspace, _| {
483 assert!(
484 workspace.is_edited(),
485 "Should be in the same dirty project after cancelling"
486 )
487 })
488 .unwrap();
489 }
490
491 fn open_recent_projects(
492 workspace: &WindowHandle<Workspace>,
493 cx: &mut TestAppContext,
494 ) -> View<Picker<RecentProjectsDelegate>> {
495 cx.dispatch_action((*workspace).into(), OpenRecent);
496 workspace
497 .update(cx, |workspace, cx| {
498 workspace
499 .active_modal::<RecentProjects>(cx)
500 .unwrap()
501 .read(cx)
502 .picker
503 .clone()
504 })
505 .unwrap()
506 }
507
508 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
509 cx.update(|cx| {
510 let state = AppState::test(cx);
511 language::init(cx);
512 crate::init(cx);
513 editor::init(cx);
514 workspace::init_settings(cx);
515 Project::init_settings(cx);
516 state
517 })
518 }
519}