recent_projects.rs

  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) -> Arc<str> {
150        Arc::from(format!(
151            "`{:?}` reuses the window, `{:?}` opens in new",
152            menu::Confirm,
153            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(r#match) = self.matches.get(ix) else {
249            return None;
250        };
251
252        let (workspace_id, location) = &self.workspaces[r#match.candidate_id];
253        let highlighted_location: HighlightedWorkspaceLocation =
254            HighlightedWorkspaceLocation::new(&r#match, location);
255        let tooltip_highlighted_location = highlighted_location.clone();
256
257        let is_current_workspace = self.is_current_workspace(*workspace_id, cx);
258        Some(
259            ListItem::new(ix)
260                .inset(true)
261                .spacing(ListItemSpacing::Sparse)
262                .selected(selected)
263                .child(
264                    v_flex()
265                        .child(highlighted_location.names)
266                        .when(self.render_paths, |this| {
267                            this.children(highlighted_location.paths.into_iter().map(|path| {
268                                HighlightedLabel::new(path.text, path.highlight_positions)
269                                    .size(LabelSize::Small)
270                                    .color(Color::Muted)
271                            }))
272                        }),
273                )
274                .when(!is_current_workspace, |el| {
275                    let delete_button = div()
276                        .child(
277                            IconButton::new("delete", IconName::Close)
278                                .icon_size(IconSize::Small)
279                                .on_click(cx.listener(move |this, _event, cx| {
280                                    cx.stop_propagation();
281                                    cx.prevent_default();
282
283                                    this.delegate.delete_recent_project(ix, cx)
284                                }))
285                                .tooltip(|cx| Tooltip::text("Delete From Recent Projects...", cx)),
286                        )
287                        .into_any_element();
288
289                    if self.selected_index() == ix {
290                        el.end_slot::<AnyElement>(delete_button)
291                    } else {
292                        el.end_hover_slot::<AnyElement>(delete_button)
293                    }
294                })
295                .tooltip(move |cx| {
296                    let tooltip_highlighted_location = tooltip_highlighted_location.clone();
297                    cx.new_view(move |_| MatchTooltip {
298                        highlighted_location: tooltip_highlighted_location,
299                    })
300                    .into()
301                }),
302        )
303    }
304}
305
306impl RecentProjectsDelegate {
307    fn delete_recent_project(&self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
308        if let Some(selected_match) = self.matches.get(ix) {
309            let (workspace_id, _) = self.workspaces[selected_match.candidate_id];
310            cx.spawn(move |this, mut cx| async move {
311                let _ = WORKSPACE_DB.delete_workspace_by_id(workspace_id).await;
312                let workspaces = WORKSPACE_DB
313                    .recent_workspaces_on_disk()
314                    .await
315                    .unwrap_or_default();
316                this.update(&mut cx, move |picker, cx| {
317                    picker.delegate.workspaces = workspaces;
318                    picker.delegate.set_selected_index(ix - 1, cx);
319                    picker.delegate.reset_selected_match_index = false;
320                    picker.update_matches(picker.query(cx), cx)
321                })
322            })
323            .detach();
324        }
325    }
326
327    fn is_current_workspace(
328        &self,
329        workspace_id: WorkspaceId,
330        cx: &mut ViewContext<Picker<Self>>,
331    ) -> bool {
332        if let Some(workspace) = self.workspace.upgrade() {
333            let workspace = workspace.read(cx);
334            if workspace_id == workspace.database_id() {
335                return true;
336            }
337        }
338
339        false
340    }
341}
342struct MatchTooltip {
343    highlighted_location: HighlightedWorkspaceLocation,
344}
345
346impl Render for MatchTooltip {
347    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
348        tooltip_container(cx, |div, _| {
349            div.children(
350                self.highlighted_location
351                    .paths
352                    .clone()
353                    .into_iter()
354                    .map(|path| {
355                        HighlightedLabel::new(path.text, path.highlight_positions)
356                            .size(LabelSize::Small)
357                            .color(Color::Muted)
358                    }),
359            )
360        })
361    }
362}