recent_projects.rs

  1mod highlighted_workspace_location;
  2
  3use fuzzy::{StringMatch, StringMatchCandidate};
  4use gpui::{
  5    actions,
  6    anyhow::Result,
  7    elements::{Flex, ParentElement},
  8    AnyElement, AppContext, Element, Task, ViewContext, WeakViewHandle,
  9};
 10use highlighted_workspace_location::HighlightedWorkspaceLocation;
 11use ordered_float::OrderedFloat;
 12use picker::{Picker, PickerDelegate, PickerEvent};
 13use std::sync::Arc;
 14use workspace::{
 15    notifications::simple_message_notification::MessageNotification, Workspace, WorkspaceLocation,
 16    WORKSPACE_DB,
 17};
 18
 19actions!(projects, [OpenRecent]);
 20
 21pub fn init(cx: &mut AppContext) {
 22    cx.add_async_action(toggle);
 23    RecentProjects::init(cx);
 24}
 25
 26fn toggle(
 27    _: &mut Workspace,
 28    _: &OpenRecent,
 29    cx: &mut ViewContext<Workspace>,
 30) -> Option<Task<Result<()>>> {
 31    Some(cx.spawn(|workspace, mut cx| async move {
 32        let workspace_locations: Vec<_> = cx
 33            .background()
 34            .spawn(async {
 35                WORKSPACE_DB
 36                    .recent_workspaces_on_disk()
 37                    .await
 38                    .unwrap_or_default()
 39                    .into_iter()
 40                    .map(|(_, location)| location)
 41                    .collect()
 42            })
 43            .await;
 44
 45        workspace.update(&mut cx, |workspace, cx| {
 46            if !workspace_locations.is_empty() {
 47                workspace.toggle_modal(cx, |_, cx| {
 48                    let workspace = cx.weak_handle();
 49                    cx.add_view(|cx| {
 50                        RecentProjects::new(
 51                            RecentProjectsDelegate::new(workspace, workspace_locations),
 52                            cx,
 53                        )
 54                        .with_max_size(800., 1200.)
 55                    })
 56                });
 57            } else {
 58                workspace.show_notification(0, cx, |cx| {
 59                    cx.add_view(|_| MessageNotification::new("No recent projects to open."))
 60                })
 61            }
 62        })?;
 63        Ok(())
 64    }))
 65}
 66
 67pub fn build_recent_projects(
 68    workspace: WeakViewHandle<Workspace>,
 69    cx: &mut ViewContext<RecentProjects>,
 70) -> RecentProjects {
 71    let workspaces = futures::executor::block_on(async {
 72        WORKSPACE_DB
 73            .recent_workspaces_on_disk()
 74            .await
 75            .unwrap_or_default()
 76            .into_iter()
 77            .map(|(_, location)| location)
 78            .collect()
 79    });
 80    Picker::new(RecentProjectsDelegate::new(workspace, workspaces), cx)
 81        .with_theme(|theme| theme.picker.clone())
 82}
 83
 84pub type RecentProjects = Picker<RecentProjectsDelegate>;
 85
 86pub struct RecentProjectsDelegate {
 87    workspace: WeakViewHandle<Workspace>,
 88    workspace_locations: Vec<WorkspaceLocation>,
 89    selected_match_index: usize,
 90    matches: Vec<StringMatch>,
 91}
 92
 93impl RecentProjectsDelegate {
 94    fn new(
 95        workspace: WeakViewHandle<Workspace>,
 96        workspace_locations: Vec<WorkspaceLocation>,
 97    ) -> Self {
 98        Self {
 99            workspace,
100            workspace_locations,
101            selected_match_index: 0,
102            matches: Default::default(),
103        }
104    }
105}
106
107impl PickerDelegate for RecentProjectsDelegate {
108    fn placeholder_text(&self) -> Arc<str> {
109        "Recent Projects...".into()
110    }
111
112    fn match_count(&self) -> usize {
113        self.matches.len()
114    }
115
116    fn selected_index(&self) -> usize {
117        self.selected_match_index
118    }
119
120    fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<RecentProjects>) {
121        self.selected_match_index = ix;
122    }
123
124    fn update_matches(
125        &mut self,
126        query: String,
127        cx: &mut ViewContext<RecentProjects>,
128    ) -> gpui::Task<()> {
129        let query = query.trim_start();
130        let smart_case = query.chars().any(|c| c.is_uppercase());
131        let candidates = self
132            .workspace_locations
133            .iter()
134            .enumerate()
135            .map(|(id, location)| {
136                let combined_string = location
137                    .paths()
138                    .iter()
139                    .map(|path| path.to_string_lossy().to_owned())
140                    .collect::<Vec<_>>()
141                    .join("");
142                StringMatchCandidate::new(id, combined_string)
143            })
144            .collect::<Vec<_>>();
145        self.matches = smol::block_on(fuzzy::match_strings(
146            candidates.as_slice(),
147            query,
148            smart_case,
149            100,
150            &Default::default(),
151            cx.background().clone(),
152        ));
153        self.matches.sort_unstable_by_key(|m| m.candidate_id);
154
155        self.selected_match_index = self
156            .matches
157            .iter()
158            .enumerate()
159            .rev()
160            .max_by_key(|(_, m)| OrderedFloat(m.score))
161            .map(|(ix, _)| ix)
162            .unwrap_or(0);
163        Task::ready(())
164    }
165
166    fn confirm(&mut self, cx: &mut ViewContext<RecentProjects>) {
167        if let Some((selected_match, workspace)) = self
168            .matches
169            .get(self.selected_index())
170            .zip(self.workspace.upgrade(cx))
171        {
172            let workspace_location = &self.workspace_locations[selected_match.candidate_id];
173            workspace
174                .update(cx, |workspace, cx| {
175                    workspace
176                        .open_workspace_for_paths(workspace_location.paths().as_ref().clone(), cx)
177                })
178                .detach_and_log_err(cx);
179            cx.emit(PickerEvent::Dismiss);
180        }
181    }
182
183    fn dismissed(&mut self, _cx: &mut ViewContext<RecentProjects>) {}
184
185    fn render_match(
186        &self,
187        ix: usize,
188        mouse_state: &mut gpui::MouseState,
189        selected: bool,
190        cx: &gpui::AppContext,
191    ) -> AnyElement<Picker<Self>> {
192        let theme = theme::current(cx);
193        let style = theme.picker.item.in_state(selected).style_for(mouse_state);
194
195        let string_match = &self.matches[ix];
196
197        let highlighted_location = HighlightedWorkspaceLocation::new(
198            &string_match,
199            &self.workspace_locations[string_match.candidate_id],
200        );
201
202        Flex::column()
203            .with_child(highlighted_location.names.render(style.label.clone()))
204            .with_children(
205                highlighted_location
206                    .paths
207                    .into_iter()
208                    .map(|highlighted_path| highlighted_path.render(style.label.clone())),
209            )
210            .flex(1., false)
211            .contained()
212            .with_style(style.container)
213            .into_any_named("match")
214    }
215}