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