project_symbols.rs

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