recent_projects.rs

  1mod highlighted_workspace_location;
  2mod projects;
  3
  4use fuzzy::{StringMatch, StringMatchCandidate};
  5use gpui::{
  6    AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView, Result, Subscription, Task,
  7    View, ViewContext, WeakView,
  8};
  9use highlighted_workspace_location::HighlightedWorkspaceLocation;
 10use ordered_float::OrderedFloat;
 11use picker::{Picker, PickerDelegate};
 12use std::sync::Arc;
 13use ui::{prelude::*, ListItem, ListItemSpacing};
 14use util::paths::PathExt;
 15use workspace::{ModalView, Workspace, 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| Picker::new(delegate, cx));
 34        let _subscription = cx.subscribe(&picker, |_, _, _, cx| cx.emit(DismissEvent));
 35        // We do not want to block the UI on a potentially lengthy call to DB, so we're gonna swap
 36        // out workspace locations once the future runs to completion.
 37        cx.spawn(|this, mut cx| async move {
 38            let workspaces = WORKSPACE_DB
 39                .recent_workspaces_on_disk()
 40                .await
 41                .unwrap_or_default()
 42                .into_iter()
 43                .map(|(_, location)| location)
 44                .collect();
 45            this.update(&mut cx, move |this, cx| {
 46                this.picker.update(cx, move |picker, cx| {
 47                    picker.delegate.workspace_locations = workspaces;
 48                    picker.update_matches(picker.query(cx), cx)
 49                })
 50            })
 51            .ok()
 52        })
 53        .detach();
 54        Self {
 55            picker,
 56            rem_width,
 57            _subscription,
 58        }
 59    }
 60
 61    fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
 62        workspace.register_action(|workspace, _: &OpenRecent, cx| {
 63            let Some(recent_projects) = workspace.active_modal::<Self>(cx) else {
 64                if let Some(handler) = Self::open(workspace, cx) {
 65                    handler.detach_and_log_err(cx);
 66                }
 67                return;
 68            };
 69
 70            recent_projects.update(cx, |recent_projects, cx| {
 71                recent_projects
 72                    .picker
 73                    .update(cx, |picker, cx| picker.cycle_selection(cx))
 74            });
 75        });
 76    }
 77
 78    fn open(_: &mut Workspace, cx: &mut ViewContext<Workspace>) -> Option<Task<Result<()>>> {
 79        Some(cx.spawn(|workspace, mut cx| async move {
 80            workspace.update(&mut cx, |workspace, cx| {
 81                let weak_workspace = cx.view().downgrade();
 82                workspace.toggle_modal(cx, |cx| {
 83                    let delegate = RecentProjectsDelegate::new(weak_workspace, true);
 84
 85                    let modal = RecentProjects::new(delegate, 34., cx);
 86                    modal
 87                });
 88            })?;
 89            Ok(())
 90        }))
 91    }
 92    pub fn open_popover(workspace: WeakView<Workspace>, cx: &mut WindowContext<'_>) -> View<Self> {
 93        cx.new_view(|cx| Self::new(RecentProjectsDelegate::new(workspace, false), 20., cx))
 94    }
 95}
 96
 97impl EventEmitter<DismissEvent> for RecentProjects {}
 98
 99impl FocusableView for RecentProjects {
100    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
101        self.picker.focus_handle(cx)
102    }
103}
104
105impl Render for RecentProjects {
106    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
107        v_flex()
108            .w(rems(self.rem_width))
109            .child(self.picker.clone())
110            .on_mouse_down_out(cx.listener(|this, _, cx| {
111                this.picker.update(cx, |this, cx| {
112                    this.cancel(&Default::default(), cx);
113                })
114            }))
115    }
116}
117
118pub struct RecentProjectsDelegate {
119    workspace: WeakView<Workspace>,
120    workspace_locations: Vec<WorkspaceLocation>,
121    selected_match_index: usize,
122    matches: Vec<StringMatch>,
123    render_paths: bool,
124}
125
126impl RecentProjectsDelegate {
127    fn new(workspace: WeakView<Workspace>, render_paths: bool) -> Self {
128        Self {
129            workspace,
130            workspace_locations: vec![],
131            selected_match_index: 0,
132            matches: Default::default(),
133            render_paths,
134        }
135    }
136}
137impl EventEmitter<DismissEvent> for RecentProjectsDelegate {}
138impl PickerDelegate for RecentProjectsDelegate {
139    type ListItem = ListItem;
140
141    fn placeholder_text(&self) -> Arc<str> {
142        "Recent Projects...".into()
143    }
144
145    fn match_count(&self) -> usize {
146        self.matches.len()
147    }
148
149    fn selected_index(&self) -> usize {
150        self.selected_match_index
151    }
152
153    fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
154        self.selected_match_index = ix;
155    }
156
157    fn update_matches(
158        &mut self,
159        query: String,
160        cx: &mut ViewContext<Picker<Self>>,
161    ) -> gpui::Task<()> {
162        let query = query.trim_start();
163        let smart_case = query.chars().any(|c| c.is_uppercase());
164        let candidates = self
165            .workspace_locations
166            .iter()
167            .enumerate()
168            .map(|(id, location)| {
169                let combined_string = location
170                    .paths()
171                    .iter()
172                    .map(|path| path.compact().to_string_lossy().into_owned())
173                    .collect::<Vec<_>>()
174                    .join("");
175                StringMatchCandidate::new(id, combined_string)
176            })
177            .collect::<Vec<_>>();
178        self.matches = smol::block_on(fuzzy::match_strings(
179            candidates.as_slice(),
180            query,
181            smart_case,
182            100,
183            &Default::default(),
184            cx.background_executor().clone(),
185        ));
186        self.matches.sort_unstable_by_key(|m| m.candidate_id);
187
188        self.selected_match_index = self
189            .matches
190            .iter()
191            .enumerate()
192            .rev()
193            .max_by_key(|(_, m)| OrderedFloat(m.score))
194            .map(|(ix, _)| ix)
195            .unwrap_or(0);
196        Task::ready(())
197    }
198
199    fn confirm(&mut self, _: bool, cx: &mut ViewContext<Picker<Self>>) {
200        if let Some((selected_match, workspace)) = self
201            .matches
202            .get(self.selected_index())
203            .zip(self.workspace.upgrade())
204        {
205            let workspace_location = &self.workspace_locations[selected_match.candidate_id];
206            workspace
207                .update(cx, |workspace, cx| {
208                    workspace
209                        .open_workspace_for_paths(workspace_location.paths().as_ref().clone(), cx)
210                })
211                .detach_and_log_err(cx);
212            cx.emit(DismissEvent);
213        }
214    }
215
216    fn dismissed(&mut self, _: &mut ViewContext<Picker<Self>>) {}
217
218    fn render_match(
219        &self,
220        ix: usize,
221        selected: bool,
222        _cx: &mut ViewContext<Picker<Self>>,
223    ) -> Option<Self::ListItem> {
224        let Some(r#match) = self.matches.get(ix) else {
225            return None;
226        };
227
228        let highlighted_location = HighlightedWorkspaceLocation::new(
229            &r#match,
230            &self.workspace_locations[r#match.candidate_id],
231        );
232
233        Some(
234            ListItem::new(ix)
235                .inset(true)
236                .spacing(ListItemSpacing::Sparse)
237                .selected(selected)
238                .child(
239                    v_flex()
240                        .child(highlighted_location.names)
241                        .when(self.render_paths, |this| {
242                            this.children(highlighted_location.paths)
243                        }),
244                ),
245        )
246    }
247}