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