recent_projects.rs

  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            .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                        workspace.open_workspace_for_paths(
227                            replace_current_window,
228                            candidate_workspace_location.paths().as_ref().clone(),
229                            cx,
230                        )
231                    } else {
232                        Task::ready(Ok(()))
233                    }
234                })
235                .detach_and_log_err(cx);
236            cx.emit(DismissEvent);
237        }
238    }
239
240    fn dismissed(&mut self, _: &mut ViewContext<Picker<Self>>) {}
241
242    fn render_match(
243        &self,
244        ix: usize,
245        selected: bool,
246        cx: &mut ViewContext<Picker<Self>>,
247    ) -> Option<Self::ListItem> {
248        let Some(hit) = self.matches.get(ix) else {
249            return None;
250        };
251
252        let (workspace_id, location) = &self.workspaces[hit.candidate_id];
253        let is_current_workspace = self.is_current_workspace(*workspace_id, cx);
254
255        let mut path_start_offset = 0;
256        let (match_labels, paths): (Vec<_>, Vec<_>) = location
257            .paths()
258            .iter()
259            .map(|path| {
260                let path = path.compact();
261                let highlighted_text =
262                    highlights_for_path(path.as_ref(), &hit.positions, path_start_offset);
263
264                path_start_offset += highlighted_text.1.char_count;
265                highlighted_text
266            })
267            .unzip();
268
269        let highlighted_match = HighlightedMatchWithPaths {
270            match_label: HighlightedText::join(
271                match_labels.into_iter().filter_map(|name| name),
272                ", ",
273            ),
274            paths: if self.render_paths { paths } else { Vec::new() },
275        };
276        Some(
277            ListItem::new(ix)
278                .inset(true)
279                .spacing(ListItemSpacing::Sparse)
280                .selected(selected)
281                .child(highlighted_match.clone().render(cx))
282                .when(!is_current_workspace, |el| {
283                    let delete_button = div()
284                        .child(
285                            IconButton::new("delete", IconName::Close)
286                                .icon_size(IconSize::Small)
287                                .on_click(cx.listener(move |this, _event, cx| {
288                                    cx.stop_propagation();
289                                    cx.prevent_default();
290
291                                    this.delegate.delete_recent_project(ix, cx)
292                                }))
293                                .tooltip(|cx| Tooltip::text("Delete From Recent Projects...", cx)),
294                        )
295                        .into_any_element();
296
297                    if self.selected_index() == ix {
298                        el.end_slot::<AnyElement>(delete_button)
299                    } else {
300                        el.end_hover_slot::<AnyElement>(delete_button)
301                    }
302                })
303                .tooltip(move |cx| {
304                    let tooltip_highlighted_location = highlighted_match.clone();
305                    cx.new_view(move |_| MatchTooltip {
306                        highlighted_location: tooltip_highlighted_location,
307                    })
308                    .into()
309                }),
310        )
311    }
312}
313
314// Compute the highlighted text for the name and path
315fn highlights_for_path(
316    path: &Path,
317    match_positions: &Vec<usize>,
318    path_start_offset: usize,
319) -> (Option<HighlightedText>, HighlightedText) {
320    let path_string = path.to_string_lossy();
321    let path_char_count = path_string.chars().count();
322    // Get the subset of match highlight positions that line up with the given path.
323    // Also adjusts them to start at the path start
324    let path_positions = match_positions
325        .iter()
326        .copied()
327        .skip_while(|position| *position < path_start_offset)
328        .take_while(|position| *position < path_start_offset + path_char_count)
329        .map(|position| position - path_start_offset)
330        .collect::<Vec<_>>();
331
332    // Again subset the highlight positions to just those that line up with the file_name
333    // again adjusted to the start of the file_name
334    let file_name_text_and_positions = path.file_name().map(|file_name| {
335        let text = file_name.to_string_lossy();
336        let char_count = text.chars().count();
337        let file_name_start = path_char_count - char_count;
338        let highlight_positions = path_positions
339            .iter()
340            .copied()
341            .skip_while(|position| *position < file_name_start)
342            .take_while(|position| *position < file_name_start + char_count)
343            .map(|position| position - file_name_start)
344            .collect::<Vec<_>>();
345        HighlightedText {
346            text: text.to_string(),
347            highlight_positions,
348            char_count,
349        }
350    });
351
352    (
353        file_name_text_and_positions,
354        HighlightedText {
355            text: path_string.to_string(),
356            highlight_positions: path_positions,
357            char_count: path_char_count,
358        },
359    )
360}
361
362impl RecentProjectsDelegate {
363    fn delete_recent_project(&self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
364        if let Some(selected_match) = self.matches.get(ix) {
365            let (workspace_id, _) = self.workspaces[selected_match.candidate_id];
366            cx.spawn(move |this, mut cx| async move {
367                let _ = WORKSPACE_DB.delete_workspace_by_id(workspace_id).await;
368                let workspaces = WORKSPACE_DB
369                    .recent_workspaces_on_disk()
370                    .await
371                    .unwrap_or_default();
372                this.update(&mut cx, move |picker, cx| {
373                    picker.delegate.workspaces = workspaces;
374                    picker.delegate.set_selected_index(ix - 1, cx);
375                    picker.delegate.reset_selected_match_index = false;
376                    picker.update_matches(picker.query(cx), cx)
377                })
378            })
379            .detach();
380        }
381    }
382
383    fn is_current_workspace(
384        &self,
385        workspace_id: WorkspaceId,
386        cx: &mut ViewContext<Picker<Self>>,
387    ) -> bool {
388        if let Some(workspace) = self.workspace.upgrade() {
389            let workspace = workspace.read(cx);
390            if workspace_id == workspace.database_id() {
391                return true;
392            }
393        }
394
395        false
396    }
397}
398struct MatchTooltip {
399    highlighted_location: HighlightedMatchWithPaths,
400}
401
402impl Render for MatchTooltip {
403    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
404        tooltip_container(cx, |div, _| {
405            self.highlighted_location.render_paths_children(div)
406        })
407    }
408}