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 let action_binding_text = |action: &dyn gpui::Action| {
151 cx.bindings_for_action(action)
152 .into_iter()
153 .next()
154 .map(|binding| {
155 binding
156 .keystrokes()
157 .into_iter()
158 .map(ToString::to_string)
159 .collect::<Vec<_>>()
160 .join(" ")
161 })
162 .unwrap_or_else(|| format!("{action:?}"))
163 };
164 Arc::from(format!(
165 "{} reuses the window, {} opens a new one",
166 action_binding_text(&menu::Confirm),
167 action_binding_text(&menu::SecondaryConfirm),
168 ))
169 }
170
171 fn match_count(&self) -> usize {
172 self.matches.len()
173 }
174
175 fn selected_index(&self) -> usize {
176 self.selected_match_index
177 }
178
179 fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
180 self.selected_match_index = ix;
181 }
182
183 fn update_matches(
184 &mut self,
185 query: String,
186 cx: &mut ViewContext<Picker<Self>>,
187 ) -> gpui::Task<()> {
188 let query = query.trim_start();
189 let smart_case = query.chars().any(|c| c.is_uppercase());
190 let candidates = self
191 .workspaces
192 .iter()
193 .enumerate()
194 .map(|(id, (_, location))| {
195 let combined_string = location
196 .paths()
197 .iter()
198 .map(|path| path.compact().to_string_lossy().into_owned())
199 .collect::<Vec<_>>()
200 .join("");
201 StringMatchCandidate::new(id, combined_string)
202 })
203 .collect::<Vec<_>>();
204 self.matches = smol::block_on(fuzzy::match_strings(
205 candidates.as_slice(),
206 query,
207 smart_case,
208 100,
209 &Default::default(),
210 cx.background_executor().clone(),
211 ));
212 self.matches.sort_unstable_by_key(|m| m.candidate_id);
213
214 if self.reset_selected_match_index {
215 self.selected_match_index = self
216 .matches
217 .iter()
218 .enumerate()
219 .rev()
220 .max_by_key(|(_, m)| OrderedFloat(m.score))
221 .map(|(ix, _)| ix)
222 .unwrap_or(0);
223 }
224 self.reset_selected_match_index = true;
225 Task::ready(())
226 }
227
228 fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
229 if let Some((selected_match, workspace)) = self
230 .matches
231 .get(self.selected_index())
232 .zip(self.workspace.upgrade())
233 {
234 let (candidate_workspace_id, candidate_workspace_location) =
235 &self.workspaces[selected_match.candidate_id];
236 let replace_current_window = !secondary;
237 workspace
238 .update(cx, |workspace, cx| {
239 if workspace.database_id() != *candidate_workspace_id {
240 workspace.open_workspace_for_paths(
241 replace_current_window,
242 candidate_workspace_location.paths().as_ref().clone(),
243 cx,
244 )
245 } else {
246 Task::ready(Ok(()))
247 }
248 })
249 .detach_and_log_err(cx);
250 cx.emit(DismissEvent);
251 }
252 }
253
254 fn dismissed(&mut self, _: &mut ViewContext<Picker<Self>>) {}
255
256 fn render_match(
257 &self,
258 ix: usize,
259 selected: bool,
260 cx: &mut ViewContext<Picker<Self>>,
261 ) -> Option<Self::ListItem> {
262 let Some(r#match) = self.matches.get(ix) else {
263 return None;
264 };
265
266 let (workspace_id, location) = &self.workspaces[r#match.candidate_id];
267 let highlighted_location: HighlightedWorkspaceLocation =
268 HighlightedWorkspaceLocation::new(&r#match, location);
269 let tooltip_highlighted_location = highlighted_location.clone();
270
271 let is_current_workspace = self.is_current_workspace(*workspace_id, cx);
272 Some(
273 ListItem::new(ix)
274 .inset(true)
275 .spacing(ListItemSpacing::Sparse)
276 .selected(selected)
277 .child(
278 v_flex()
279 .child(highlighted_location.names)
280 .when(self.render_paths, |this| {
281 this.children(highlighted_location.paths.into_iter().map(|path| {
282 HighlightedLabel::new(path.text, path.highlight_positions)
283 .size(LabelSize::Small)
284 .color(Color::Muted)
285 }))
286 }),
287 )
288 .when(!is_current_workspace, |el| {
289 let delete_button = div()
290 .child(
291 IconButton::new("delete", IconName::Close)
292 .icon_size(IconSize::Small)
293 .on_click(cx.listener(move |this, _event, cx| {
294 cx.stop_propagation();
295 cx.prevent_default();
296
297 this.delegate.delete_recent_project(ix, cx)
298 }))
299 .tooltip(|cx| Tooltip::text("Delete From Recent Projects...", cx)),
300 )
301 .into_any_element();
302
303 if self.selected_index() == ix {
304 el.end_slot::<AnyElement>(delete_button)
305 } else {
306 el.end_hover_slot::<AnyElement>(delete_button)
307 }
308 })
309 .tooltip(move |cx| {
310 let tooltip_highlighted_location = tooltip_highlighted_location.clone();
311 cx.new_view(move |_| MatchTooltip {
312 highlighted_location: tooltip_highlighted_location,
313 })
314 .into()
315 }),
316 )
317 }
318}
319
320impl RecentProjectsDelegate {
321 fn delete_recent_project(&self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
322 if let Some(selected_match) = self.matches.get(ix) {
323 let (workspace_id, _) = self.workspaces[selected_match.candidate_id];
324 cx.spawn(move |this, mut cx| async move {
325 let _ = WORKSPACE_DB.delete_workspace_by_id(workspace_id).await;
326 let workspaces = WORKSPACE_DB
327 .recent_workspaces_on_disk()
328 .await
329 .unwrap_or_default();
330 this.update(&mut cx, move |picker, cx| {
331 picker.delegate.workspaces = workspaces;
332 picker.delegate.set_selected_index(ix - 1, cx);
333 picker.delegate.reset_selected_match_index = false;
334 picker.update_matches(picker.query(cx), cx)
335 })
336 })
337 .detach();
338 }
339 }
340
341 fn is_current_workspace(
342 &self,
343 workspace_id: WorkspaceId,
344 cx: &mut ViewContext<Picker<Self>>,
345 ) -> bool {
346 if let Some(workspace) = self.workspace.upgrade() {
347 let workspace = workspace.read(cx);
348 if workspace_id == workspace.database_id() {
349 return true;
350 }
351 }
352
353 false
354 }
355}
356struct MatchTooltip {
357 highlighted_location: HighlightedWorkspaceLocation,
358}
359
360impl Render for MatchTooltip {
361 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
362 tooltip_container(cx, |div, _| {
363 div.children(
364 self.highlighted_location
365 .paths
366 .clone()
367 .into_iter()
368 .map(|path| {
369 HighlightedLabel::new(path.text, path.highlight_positions)
370 .size(LabelSize::Small)
371 .color(Color::Muted)
372 }),
373 )
374 })
375 }
376}