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    workspaces: Vec<WorkspaceLocation>,
 70    cx: &mut ViewContext<RecentProjects>,
 71) -> RecentProjects {
 72    Picker::new(RecentProjectsDelegate::new(workspace, workspaces), cx)
 73        .with_theme(|theme| theme.picker.clone())
 74}
 75
 76pub type RecentProjects = Picker<RecentProjectsDelegate>;
 77
 78pub struct RecentProjectsDelegate {
 79    workspace: WeakViewHandle<Workspace>,
 80    workspace_locations: Vec<WorkspaceLocation>,
 81    selected_match_index: usize,
 82    matches: Vec<StringMatch>,
 83}
 84
 85impl RecentProjectsDelegate {
 86    fn new(
 87        workspace: WeakViewHandle<Workspace>,
 88        workspace_locations: Vec<WorkspaceLocation>,
 89    ) -> Self {
 90        Self {
 91            workspace,
 92            workspace_locations,
 93            selected_match_index: 0,
 94            matches: Default::default(),
 95        }
 96    }
 97}
 98
 99impl PickerDelegate for RecentProjectsDelegate {
100    fn placeholder_text(&self) -> Arc<str> {
101        "Recent Projects...".into()
102    }
103
104    fn match_count(&self) -> usize {
105        self.matches.len()
106    }
107
108    fn selected_index(&self) -> usize {
109        self.selected_match_index
110    }
111
112    fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<RecentProjects>) {
113        self.selected_match_index = ix;
114    }
115
116    fn update_matches(
117        &mut self,
118        query: String,
119        cx: &mut ViewContext<RecentProjects>,
120    ) -> gpui::Task<()> {
121        let query = query.trim_start();
122        let smart_case = query.chars().any(|c| c.is_uppercase());
123        let candidates = self
124            .workspace_locations
125            .iter()
126            .enumerate()
127            .map(|(id, location)| {
128                let combined_string = location
129                    .paths()
130                    .iter()
131                    .map(|path| path.to_string_lossy().to_owned())
132                    .collect::<Vec<_>>()
133                    .join("");
134                StringMatchCandidate::new(id, combined_string)
135            })
136            .collect::<Vec<_>>();
137        self.matches = smol::block_on(fuzzy::match_strings(
138            candidates.as_slice(),
139            query,
140            smart_case,
141            100,
142            &Default::default(),
143            cx.background().clone(),
144        ));
145        self.matches.sort_unstable_by_key(|m| m.candidate_id);
146
147        self.selected_match_index = self
148            .matches
149            .iter()
150            .enumerate()
151            .rev()
152            .max_by_key(|(_, m)| OrderedFloat(m.score))
153            .map(|(ix, _)| ix)
154            .unwrap_or(0);
155        Task::ready(())
156    }
157
158    fn confirm(&mut self, cx: &mut ViewContext<RecentProjects>) {
159        if let Some((selected_match, workspace)) = self
160            .matches
161            .get(self.selected_index())
162            .zip(self.workspace.upgrade(cx))
163        {
164            let workspace_location = &self.workspace_locations[selected_match.candidate_id];
165            workspace
166                .update(cx, |workspace, cx| {
167                    workspace
168                        .open_workspace_for_paths(workspace_location.paths().as_ref().clone(), cx)
169                })
170                .detach_and_log_err(cx);
171            cx.emit(PickerEvent::Dismiss);
172        }
173    }
174
175    fn dismissed(&mut self, _cx: &mut ViewContext<RecentProjects>) {}
176
177    fn render_match(
178        &self,
179        ix: usize,
180        mouse_state: &mut gpui::MouseState,
181        selected: bool,
182        cx: &gpui::AppContext,
183    ) -> AnyElement<Picker<Self>> {
184        let theme = theme::current(cx);
185        let style = theme.picker.item.in_state(selected).style_for(mouse_state);
186
187        let string_match = &self.matches[ix];
188
189        let highlighted_location = HighlightedWorkspaceLocation::new(
190            &string_match,
191            &self.workspace_locations[string_match.candidate_id],
192        );
193
194        Flex::column()
195            .with_child(highlighted_location.names.render(style.label.clone()))
196            .with_children(
197                highlighted_location
198                    .paths
199                    .into_iter()
200                    .map(|highlighted_path| highlighted_path.render(style.label.clone())),
201            )
202            .flex(1., false)
203            .contained()
204            .with_style(style.container)
205            .into_any_named("match")
206    }
207}