project_symbols.rs

  1use editor::{
  2    combine_syntax_and_fuzzy_match_highlights, styled_runs_for_code_label, Autoscroll, Bias, Editor,
  3};
  4use fuzzy::{StringMatch, StringMatchCandidate};
  5use gpui::{
  6    action,
  7    elements::*,
  8    keymap::{self, Binding},
  9    AppContext, Axis, Entity, ModelHandle, MutableAppContext, RenderContext, Task, View,
 10    ViewContext, ViewHandle, WeakViewHandle,
 11};
 12use ordered_float::OrderedFloat;
 13use project::{Project, Symbol};
 14use std::{
 15    borrow::Cow,
 16    cmp::{self, Reverse},
 17};
 18use util::ResultExt;
 19use workspace::{
 20    menu::{Confirm, SelectFirst, SelectLast, SelectNext, SelectPrev},
 21    Settings, Workspace,
 22};
 23
 24action!(Toggle);
 25
 26pub fn init(cx: &mut MutableAppContext) {
 27    cx.add_bindings([
 28        Binding::new("cmd-t", Toggle, None),
 29        Binding::new("escape", Toggle, Some("ProjectSymbolsView")),
 30    ]);
 31    cx.add_action(ProjectSymbolsView::toggle);
 32    cx.add_action(ProjectSymbolsView::confirm);
 33    cx.add_action(ProjectSymbolsView::select_prev);
 34    cx.add_action(ProjectSymbolsView::select_next);
 35    cx.add_action(ProjectSymbolsView::select_first);
 36    cx.add_action(ProjectSymbolsView::select_last);
 37}
 38
 39pub struct ProjectSymbolsView {
 40    handle: WeakViewHandle<Self>,
 41    project: ModelHandle<Project>,
 42    selected_match_index: usize,
 43    list_state: UniformListState,
 44    symbols: Vec<Symbol>,
 45    match_candidates: Vec<StringMatchCandidate>,
 46    matches: Vec<StringMatch>,
 47    pending_symbols_task: Task<Option<()>>,
 48    query_editor: ViewHandle<Editor>,
 49}
 50
 51pub enum Event {
 52    Dismissed,
 53    Selected(Symbol),
 54}
 55
 56impl Entity for ProjectSymbolsView {
 57    type Event = Event;
 58}
 59
 60impl View for ProjectSymbolsView {
 61    fn ui_name() -> &'static str {
 62        "ProjectSymbolsView"
 63    }
 64
 65    fn keymap_context(&self, _: &AppContext) -> keymap::Context {
 66        let mut cx = Self::default_keymap_context();
 67        cx.set.insert("menu".into());
 68        cx
 69    }
 70
 71    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
 72        let settings = cx.global::<Settings>();
 73        Flex::new(Axis::Vertical)
 74            .with_child(
 75                Container::new(ChildView::new(&self.query_editor).boxed())
 76                    .with_style(settings.theme.selector.input_editor.container)
 77                    .boxed(),
 78            )
 79            .with_child(
 80                FlexItem::new(self.render_matches(cx))
 81                    .flex(1., false)
 82                    .boxed(),
 83            )
 84            .contained()
 85            .with_style(settings.theme.selector.container)
 86            .constrained()
 87            .with_max_width(500.0)
 88            .with_max_height(420.0)
 89            .aligned()
 90            .top()
 91            .named("project symbols view")
 92    }
 93
 94    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
 95        cx.focus(&self.query_editor);
 96    }
 97}
 98
 99impl ProjectSymbolsView {
100    fn new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
101        let query_editor = cx.add_view(|cx| {
102            Editor::single_line(Some(|theme| theme.selector.input_editor.clone()), cx)
103        });
104        cx.subscribe(&query_editor, Self::on_query_editor_event)
105            .detach();
106        let mut this = Self {
107            handle: cx.weak_handle(),
108            project,
109            selected_match_index: 0,
110            list_state: Default::default(),
111            symbols: Default::default(),
112            match_candidates: Default::default(),
113            matches: Default::default(),
114            pending_symbols_task: Task::ready(None),
115            query_editor,
116        };
117        this.update_matches(cx);
118        this
119    }
120
121    fn toggle(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
122        workspace.toggle_modal(cx, |cx, workspace| {
123            let project = workspace.project().clone();
124            let symbols = cx.add_view(|cx| Self::new(project, cx));
125            cx.subscribe(&symbols, Self::on_event).detach();
126            symbols
127        });
128    }
129
130    fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
131        if self.selected_match_index > 0 {
132            self.select(self.selected_match_index - 1, cx);
133        }
134    }
135
136    fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
137        if self.selected_match_index + 1 < self.matches.len() {
138            self.select(self.selected_match_index + 1, cx);
139        }
140    }
141
142    fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
143        self.select(0, cx);
144    }
145
146    fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
147        self.select(self.matches.len().saturating_sub(1), cx);
148    }
149
150    fn select(&mut self, index: usize, cx: &mut ViewContext<Self>) {
151        self.selected_match_index = index;
152        self.list_state.scroll_to(ScrollTarget::Show(index));
153        cx.notify();
154    }
155
156    fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
157        if let Some(symbol) = self
158            .matches
159            .get(self.selected_match_index)
160            .map(|mat| self.symbols[mat.candidate_id].clone())
161        {
162            cx.emit(Event::Selected(symbol));
163        }
164    }
165
166    fn update_matches(&mut self, cx: &mut ViewContext<Self>) {
167        self.filter(cx);
168        let query = self.query_editor.read(cx).text(cx);
169        let symbols = self
170            .project
171            .update(cx, |project, cx| project.symbols(&query, cx));
172        self.pending_symbols_task = cx.spawn_weak(|this, mut cx| async move {
173            let symbols = symbols.await.log_err()?;
174            if let Some(this) = this.upgrade(&cx) {
175                this.update(&mut cx, |this, cx| {
176                    this.match_candidates = symbols
177                        .iter()
178                        .enumerate()
179                        .map(|(id, symbol)| {
180                            StringMatchCandidate::new(
181                                id,
182                                symbol.label.text[symbol.label.filter_range.clone()].to_string(),
183                            )
184                        })
185                        .collect();
186                    this.symbols = symbols;
187                    this.filter(cx);
188                });
189            }
190            None
191        });
192    }
193
194    fn filter(&mut self, cx: &mut ViewContext<Self>) {
195        let query = self.query_editor.read(cx).text(cx);
196        let mut matches = if query.is_empty() {
197            self.match_candidates
198                .iter()
199                .enumerate()
200                .map(|(candidate_id, candidate)| StringMatch {
201                    candidate_id,
202                    score: Default::default(),
203                    positions: Default::default(),
204                    string: candidate.string.clone(),
205                })
206                .collect()
207        } else {
208            smol::block_on(fuzzy::match_strings(
209                &self.match_candidates,
210                &query,
211                false,
212                100,
213                &Default::default(),
214                cx.background().clone(),
215            ))
216        };
217
218        matches.sort_unstable_by_key(|mat| {
219            let label = &self.symbols[mat.candidate_id].label;
220            (
221                Reverse(OrderedFloat(mat.score)),
222                &label.text[label.filter_range.clone()],
223            )
224        });
225
226        for mat in &mut matches {
227            let filter_start = self.symbols[mat.candidate_id].label.filter_range.start;
228            for position in &mut mat.positions {
229                *position += filter_start;
230            }
231        }
232
233        self.matches = matches;
234        self.select_first(&SelectFirst, cx);
235        cx.notify();
236    }
237
238    fn render_matches(&self, cx: &AppContext) -> ElementBox {
239        if self.matches.is_empty() {
240            let settings = cx.global::<Settings>();
241            return Container::new(
242                Label::new(
243                    "No matches".into(),
244                    settings.theme.selector.empty.label.clone(),
245                )
246                .boxed(),
247            )
248            .with_style(settings.theme.selector.empty.container)
249            .named("empty matches");
250        }
251
252        let handle = self.handle.clone();
253        let list = UniformList::new(
254            self.list_state.clone(),
255            self.matches.len(),
256            move |mut range, items, cx| {
257                let cx = cx.as_ref();
258                let view = handle.upgrade(cx).unwrap();
259                let view = view.read(cx);
260                let start = range.start;
261                range.end = cmp::min(range.end, view.matches.len());
262
263                let show_worktree_root_name =
264                    view.project.read(cx).visible_worktrees(cx).count() > 1;
265                items.extend(view.matches[range].iter().enumerate().map(move |(ix, m)| {
266                    view.render_match(m, start + ix, show_worktree_root_name, cx)
267                }));
268            },
269        );
270
271        Container::new(list.boxed())
272            .with_margin_top(6.0)
273            .named("matches")
274    }
275
276    fn render_match(
277        &self,
278        string_match: &StringMatch,
279        index: usize,
280        show_worktree_root_name: bool,
281        cx: &AppContext,
282    ) -> ElementBox {
283        let settings = cx.global::<Settings>();
284        let style = if index == self.selected_match_index {
285            &settings.theme.selector.active_item
286        } else {
287            &settings.theme.selector.item
288        };
289        let symbol = &self.symbols[string_match.candidate_id];
290        let syntax_runs = styled_runs_for_code_label(&symbol.label, &settings.theme.editor.syntax);
291
292        let mut path = symbol.path.to_string_lossy();
293        if show_worktree_root_name {
294            let project = self.project.read(cx);
295            if let Some(worktree) = project.worktree_for_id(symbol.worktree_id, cx) {
296                path = Cow::Owned(format!(
297                    "{}{}{}",
298                    worktree.read(cx).root_name(),
299                    std::path::MAIN_SEPARATOR,
300                    path.as_ref()
301                ));
302            }
303        }
304
305        Flex::column()
306            .with_child(
307                Text::new(symbol.label.text.clone(), style.label.text.clone())
308                    .with_soft_wrap(false)
309                    .with_highlights(combine_syntax_and_fuzzy_match_highlights(
310                        &symbol.label.text,
311                        style.label.text.clone().into(),
312                        syntax_runs,
313                        &string_match.positions,
314                    ))
315                    .boxed(),
316            )
317            .with_child(
318                // Avoid styling the path differently when it is selected, since
319                // the symbol's syntax highlighting doesn't change when selected.
320                Label::new(path.to_string(), settings.theme.selector.item.label.clone()).boxed(),
321            )
322            .contained()
323            .with_style(style.container)
324            .boxed()
325    }
326
327    fn on_query_editor_event(
328        &mut self,
329        _: ViewHandle<Editor>,
330        event: &editor::Event,
331        cx: &mut ViewContext<Self>,
332    ) {
333        match event {
334            editor::Event::Blurred => cx.emit(Event::Dismissed),
335            editor::Event::BufferEdited { .. } => self.update_matches(cx),
336            _ => {}
337        }
338    }
339
340    fn on_event(
341        workspace: &mut Workspace,
342        _: ViewHandle<Self>,
343        event: &Event,
344        cx: &mut ViewContext<Workspace>,
345    ) {
346        match event {
347            Event::Dismissed => workspace.dismiss_modal(cx),
348            Event::Selected(symbol) => {
349                let buffer = workspace
350                    .project()
351                    .update(cx, |project, cx| project.open_buffer_for_symbol(symbol, cx));
352
353                let symbol = symbol.clone();
354                cx.spawn(|workspace, mut cx| async move {
355                    let buffer = buffer.await?;
356                    workspace.update(&mut cx, |workspace, cx| {
357                        let position = buffer
358                            .read(cx)
359                            .clip_point_utf16(symbol.range.start, Bias::Left);
360
361                        let editor = workspace.open_project_item::<Editor>(buffer, cx);
362                        editor.update(cx, |editor, cx| {
363                            editor.select_ranges(
364                                [position..position],
365                                Some(Autoscroll::Center),
366                                cx,
367                            );
368                        });
369                    });
370                    Ok::<_, anyhow::Error>(())
371                })
372                .detach_and_log_err(cx);
373                workspace.dismiss_modal(cx);
374            }
375        }
376    }
377}