1mod highlighted_workspace_location;
2mod projects;
3
4use fuzzy::{StringMatch, StringMatchCandidate};
5use gpui::{
6 AnyElement, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView, Result,
7 Subscription, Task, View, ViewContext, WeakView,
8};
9use highlighted_workspace_location::HighlightedWorkspaceLocation;
10use ordered_float::OrderedFloat;
11use picker::{Picker, PickerDelegate};
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
17pub use projects::OpenRecent;
18
19pub fn init(cx: &mut AppContext) {
20 cx.observe_new_views(RecentProjects::register).detach();
21}
22
23pub struct RecentProjects {
24 pub picker: View<Picker<RecentProjectsDelegate>>,
25 rem_width: f32,
26 _subscription: Subscription,
27}
28
29impl ModalView for RecentProjects {}
30
31impl RecentProjects {
32 fn new(delegate: RecentProjectsDelegate, rem_width: f32, cx: &mut ViewContext<Self>) -> Self {
33 let picker = cx.new_view(|cx| {
34 // We want to use a list when we render paths, because the items can have different heights (multiple paths).
35 if delegate.render_paths {
36 Picker::list(delegate, cx)
37 } else {
38 Picker::uniform_list(delegate, cx)
39 }
40 });
41 let _subscription = cx.subscribe(&picker, |_, _, _, cx| cx.emit(DismissEvent));
42 // We do not want to block the UI on a potentially lengthy call to DB, so we're gonna swap
43 // out workspace locations once the future runs to completion.
44 cx.spawn(|this, mut cx| async move {
45 let workspaces = WORKSPACE_DB
46 .recent_workspaces_on_disk()
47 .await
48 .unwrap_or_default();
49
50 this.update(&mut cx, move |this, cx| {
51 this.picker.update(cx, move |picker, cx| {
52 picker.delegate.workspaces = workspaces;
53 picker.update_matches(picker.query(cx), cx)
54 })
55 })
56 .ok()
57 })
58 .detach();
59 Self {
60 picker,
61 rem_width,
62 _subscription,
63 }
64 }
65
66 fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
67 workspace.register_action(|workspace, _: &OpenRecent, cx| {
68 let Some(recent_projects) = workspace.active_modal::<Self>(cx) else {
69 if let Some(handler) = Self::open(workspace, cx) {
70 handler.detach_and_log_err(cx);
71 }
72 return;
73 };
74
75 recent_projects.update(cx, |recent_projects, cx| {
76 recent_projects
77 .picker
78 .update(cx, |picker, cx| picker.cycle_selection(cx))
79 });
80 });
81 }
82
83 fn open(_: &mut Workspace, cx: &mut ViewContext<Workspace>) -> Option<Task<Result<()>>> {
84 Some(cx.spawn(|workspace, mut cx| async move {
85 workspace.update(&mut cx, |workspace, cx| {
86 let weak_workspace = cx.view().downgrade();
87 workspace.toggle_modal(cx, |cx| {
88 let delegate = RecentProjectsDelegate::new(weak_workspace, true);
89
90 let modal = Self::new(delegate, 34., cx);
91 modal
92 });
93 })?;
94 Ok(())
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) -> Arc<str> {
150 "Search recent projects...".into()
151 }
152
153 fn match_count(&self) -> usize {
154 self.matches.len()
155 }
156
157 fn selected_index(&self) -> usize {
158 self.selected_match_index
159 }
160
161 fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
162 self.selected_match_index = ix;
163 }
164
165 fn update_matches(
166 &mut self,
167 query: String,
168 cx: &mut ViewContext<Picker<Self>>,
169 ) -> gpui::Task<()> {
170 let query = query.trim_start();
171 let smart_case = query.chars().any(|c| c.is_uppercase());
172 let candidates = self
173 .workspaces
174 .iter()
175 .enumerate()
176 .map(|(id, (_, location))| {
177 let combined_string = location
178 .paths()
179 .iter()
180 .map(|path| path.compact().to_string_lossy().into_owned())
181 .collect::<Vec<_>>()
182 .join("");
183 StringMatchCandidate::new(id, combined_string)
184 })
185 .collect::<Vec<_>>();
186 self.matches = smol::block_on(fuzzy::match_strings(
187 candidates.as_slice(),
188 query,
189 smart_case,
190 100,
191 &Default::default(),
192 cx.background_executor().clone(),
193 ));
194 self.matches.sort_unstable_by_key(|m| m.candidate_id);
195
196 if self.reset_selected_match_index {
197 self.selected_match_index = self
198 .matches
199 .iter()
200 .enumerate()
201 .rev()
202 .max_by_key(|(_, m)| OrderedFloat(m.score))
203 .map(|(ix, _)| ix)
204 .unwrap_or(0);
205 }
206 self.reset_selected_match_index = true;
207 Task::ready(())
208 }
209
210 fn confirm(&mut self, _: bool, cx: &mut ViewContext<Picker<Self>>) {
211 if let Some((selected_match, workspace)) = self
212 .matches
213 .get(self.selected_index())
214 .zip(self.workspace.upgrade())
215 {
216 let (_, workspace_location) = &self.workspaces[selected_match.candidate_id];
217 workspace
218 .update(cx, |workspace, cx| {
219 workspace
220 .open_workspace_for_paths(workspace_location.paths().as_ref().clone(), cx)
221 })
222 .detach_and_log_err(cx);
223 cx.emit(DismissEvent);
224 }
225 }
226
227 fn dismissed(&mut self, _: &mut ViewContext<Picker<Self>>) {}
228
229 fn render_match(
230 &self,
231 ix: usize,
232 selected: bool,
233 cx: &mut ViewContext<Picker<Self>>,
234 ) -> Option<Self::ListItem> {
235 let Some(r#match) = self.matches.get(ix) else {
236 return None;
237 };
238
239 let (workspace_id, location) = &self.workspaces[r#match.candidate_id];
240 let highlighted_location: HighlightedWorkspaceLocation =
241 HighlightedWorkspaceLocation::new(&r#match, location);
242 let tooltip_highlighted_location = highlighted_location.clone();
243
244 let is_current_workspace = self.is_current_workspace(*workspace_id, cx);
245 Some(
246 ListItem::new(ix)
247 .inset(true)
248 .spacing(ListItemSpacing::Sparse)
249 .selected(selected)
250 .child(
251 v_flex()
252 .child(highlighted_location.names)
253 .when(self.render_paths, |this| {
254 this.children(highlighted_location.paths.into_iter().map(|path| {
255 HighlightedLabel::new(path.text, path.highlight_positions)
256 .size(LabelSize::Small)
257 .color(Color::Muted)
258 }))
259 }),
260 )
261 .when(!is_current_workspace, |el| {
262 let delete_button = div()
263 .child(
264 IconButton::new("delete", IconName::Close)
265 .icon_size(IconSize::Small)
266 .on_click(cx.listener(move |this, _event, cx| {
267 cx.stop_propagation();
268 cx.prevent_default();
269
270 this.delegate.delete_recent_project(ix, cx)
271 }))
272 .tooltip(|cx| Tooltip::text("Delete From Recent Projects...", cx)),
273 )
274 .into_any_element();
275
276 if self.selected_index() == ix {
277 el.end_slot::<AnyElement>(delete_button)
278 } else {
279 el.end_hover_slot::<AnyElement>(delete_button)
280 }
281 })
282 .tooltip(move |cx| {
283 let tooltip_highlighted_location = tooltip_highlighted_location.clone();
284 cx.new_view(move |_| MatchTooltip {
285 highlighted_location: tooltip_highlighted_location,
286 })
287 .into()
288 }),
289 )
290 }
291}
292
293impl RecentProjectsDelegate {
294 fn delete_recent_project(&self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
295 if let Some(selected_match) = self.matches.get(ix) {
296 let (workspace_id, _) = self.workspaces[selected_match.candidate_id];
297 cx.spawn(move |this, mut cx| async move {
298 let _ = WORKSPACE_DB.delete_workspace_by_id(workspace_id).await;
299 let workspaces = WORKSPACE_DB
300 .recent_workspaces_on_disk()
301 .await
302 .unwrap_or_default();
303 this.update(&mut cx, move |picker, cx| {
304 picker.delegate.workspaces = workspaces;
305 picker.delegate.set_selected_index(ix - 1, cx);
306 picker.delegate.reset_selected_match_index = false;
307 picker.update_matches(picker.query(cx), cx)
308 })
309 })
310 .detach();
311 }
312 }
313
314 fn is_current_workspace(
315 &self,
316 workspace_id: WorkspaceId,
317 cx: &mut ViewContext<Picker<Self>>,
318 ) -> bool {
319 if let Some(workspace) = self.workspace.upgrade() {
320 let workspace = workspace.read(cx);
321 if workspace_id == workspace.database_id() {
322 return true;
323 }
324 }
325
326 false
327 }
328}
329struct MatchTooltip {
330 highlighted_location: HighlightedWorkspaceLocation,
331}
332
333impl Render for MatchTooltip {
334 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
335 tooltip_container(cx, |div, _| {
336 div.children(
337 self.highlighted_location
338 .paths
339 .clone()
340 .into_iter()
341 .map(|path| {
342 HighlightedLabel::new(path.text, path.highlight_positions)
343 .size(LabelSize::Small)
344 .color(Color::Muted)
345 }),
346 )
347 })
348 }
349}