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 settings::Settings;
15use std::{
16 borrow::Cow,
17 cmp::{self, Reverse},
18};
19use util::ResultExt;
20use workspace::{
21 menu::{Confirm, SelectFirst, SelectLast, SelectNext, SelectPrev},
22 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.global::<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(
81 FlexItem::new(self.render_matches(cx))
82 .flex(1., false)
83 .boxed(),
84 )
85 .contained()
86 .with_style(settings.theme.selector.container)
87 .constrained()
88 .with_max_width(500.0)
89 .with_max_height(420.0)
90 .aligned()
91 .top()
92 .named("project symbols view")
93 }
94
95 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
96 cx.focus(&self.query_editor);
97 }
98}
99
100impl ProjectSymbolsView {
101 fn new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
102 let query_editor = cx.add_view(|cx| {
103 Editor::single_line(Some(|theme| theme.selector.input_editor.clone()), cx)
104 });
105 cx.subscribe(&query_editor, Self::on_query_editor_event)
106 .detach();
107 let mut this = Self {
108 handle: cx.weak_handle(),
109 project,
110 selected_match_index: 0,
111 list_state: Default::default(),
112 symbols: Default::default(),
113 match_candidates: Default::default(),
114 matches: Default::default(),
115 pending_symbols_task: Task::ready(None),
116 query_editor,
117 };
118 this.update_matches(cx);
119 this
120 }
121
122 fn toggle(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
123 workspace.toggle_modal(cx, |cx, workspace| {
124 let project = workspace.project().clone();
125 let symbols = cx.add_view(|cx| Self::new(project, cx));
126 cx.subscribe(&symbols, Self::on_event).detach();
127 symbols
128 });
129 }
130
131 fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
132 if self.selected_match_index > 0 {
133 self.select(self.selected_match_index - 1, cx);
134 }
135 }
136
137 fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
138 if self.selected_match_index + 1 < self.matches.len() {
139 self.select(self.selected_match_index + 1, cx);
140 }
141 }
142
143 fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
144 self.select(0, cx);
145 }
146
147 fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
148 self.select(self.matches.len().saturating_sub(1), cx);
149 }
150
151 fn select(&mut self, index: usize, cx: &mut ViewContext<Self>) {
152 self.selected_match_index = index;
153 self.list_state.scroll_to(ScrollTarget::Show(index));
154 cx.notify();
155 }
156
157 fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
158 if let Some(symbol) = self
159 .matches
160 .get(self.selected_match_index)
161 .map(|mat| self.symbols[mat.candidate_id].clone())
162 {
163 cx.emit(Event::Selected(symbol));
164 }
165 }
166
167 fn update_matches(&mut self, cx: &mut ViewContext<Self>) {
168 self.filter(cx);
169 let query = self.query_editor.read(cx).text(cx);
170 let symbols = self
171 .project
172 .update(cx, |project, cx| project.symbols(&query, cx));
173 self.pending_symbols_task = cx.spawn_weak(|this, mut cx| async move {
174 let symbols = symbols.await.log_err()?;
175 if let Some(this) = this.upgrade(&cx) {
176 this.update(&mut cx, |this, cx| {
177 this.match_candidates = symbols
178 .iter()
179 .enumerate()
180 .map(|(id, symbol)| {
181 StringMatchCandidate::new(
182 id,
183 symbol.label.text[symbol.label.filter_range.clone()].to_string(),
184 )
185 })
186 .collect();
187 this.symbols = symbols;
188 this.filter(cx);
189 });
190 }
191 None
192 });
193 }
194
195 fn filter(&mut self, cx: &mut ViewContext<Self>) {
196 let query = self.query_editor.read(cx).text(cx);
197 let mut matches = if query.is_empty() {
198 self.match_candidates
199 .iter()
200 .enumerate()
201 .map(|(candidate_id, candidate)| StringMatch {
202 candidate_id,
203 score: Default::default(),
204 positions: Default::default(),
205 string: candidate.string.clone(),
206 })
207 .collect()
208 } else {
209 smol::block_on(fuzzy::match_strings(
210 &self.match_candidates,
211 &query,
212 false,
213 100,
214 &Default::default(),
215 cx.background().clone(),
216 ))
217 };
218
219 matches.sort_unstable_by_key(|mat| {
220 let label = &self.symbols[mat.candidate_id].label;
221 (
222 Reverse(OrderedFloat(mat.score)),
223 &label.text[label.filter_range.clone()],
224 )
225 });
226
227 for mat in &mut matches {
228 let filter_start = self.symbols[mat.candidate_id].label.filter_range.start;
229 for position in &mut mat.positions {
230 *position += filter_start;
231 }
232 }
233
234 self.matches = matches;
235 self.select_first(&SelectFirst, cx);
236 cx.notify();
237 }
238
239 fn render_matches(&self, cx: &AppContext) -> ElementBox {
240 if self.matches.is_empty() {
241 let settings = cx.global::<Settings>();
242 return Container::new(
243 Label::new(
244 "No matches".into(),
245 settings.theme.selector.empty.label.clone(),
246 )
247 .boxed(),
248 )
249 .with_style(settings.theme.selector.empty.container)
250 .named("empty matches");
251 }
252
253 let handle = self.handle.clone();
254 let list = UniformList::new(
255 self.list_state.clone(),
256 self.matches.len(),
257 move |mut range, items, cx| {
258 let cx = cx.as_ref();
259 let view = handle.upgrade(cx).unwrap();
260 let view = view.read(cx);
261 let start = range.start;
262 range.end = cmp::min(range.end, view.matches.len());
263
264 let show_worktree_root_name =
265 view.project.read(cx).visible_worktrees(cx).count() > 1;
266 items.extend(view.matches[range].iter().enumerate().map(move |(ix, m)| {
267 view.render_match(m, start + ix, show_worktree_root_name, cx)
268 }));
269 },
270 );
271
272 Container::new(list.boxed())
273 .with_margin_top(6.0)
274 .named("matches")
275 }
276
277 fn render_match(
278 &self,
279 string_match: &StringMatch,
280 index: usize,
281 show_worktree_root_name: bool,
282 cx: &AppContext,
283 ) -> ElementBox {
284 let settings = cx.global::<Settings>();
285 let style = if index == self.selected_match_index {
286 &settings.theme.selector.active_item
287 } else {
288 &settings.theme.selector.item
289 };
290 let symbol = &self.symbols[string_match.candidate_id];
291 let syntax_runs = styled_runs_for_code_label(&symbol.label, &settings.theme.editor.syntax);
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::BufferEdited { .. } => 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
354 let symbol = symbol.clone();
355 cx.spawn(|workspace, mut cx| async move {
356 let buffer = buffer.await?;
357 workspace.update(&mut cx, |workspace, cx| {
358 let position = buffer
359 .read(cx)
360 .clip_point_utf16(symbol.range.start, Bias::Left);
361
362 let editor = workspace.open_project_item::<Editor>(buffer, cx);
363 editor.update(cx, |editor, cx| {
364 editor.select_ranges(
365 [position..position],
366 Some(Autoscroll::Center),
367 cx,
368 );
369 });
370 });
371 Ok::<_, anyhow::Error>(())
372 })
373 .detach_and_log_err(cx);
374 workspace.dismiss_modal(cx);
375 }
376 }
377 }
378}