1use editor::{
2 combine_syntax_and_fuzzy_match_highlights, display_map::ToDisplayPoint, Anchor, AnchorRangeExt,
3 Autoscroll, DisplayPoint, Editor, ToPoint,
4};
5use fuzzy::StringMatch;
6use gpui::{
7 action,
8 elements::*,
9 geometry::vector::Vector2F,
10 keymap::{self, Binding},
11 AppContext, Axis, Entity, MutableAppContext, RenderContext, View, ViewContext, ViewHandle,
12 WeakViewHandle,
13};
14use language::Outline;
15use ordered_float::OrderedFloat;
16use std::cmp::{self, Reverse};
17use workspace::{
18 menu::{Confirm, SelectFirst, SelectLast, SelectNext, SelectPrev},
19 Settings, Workspace,
20};
21
22action!(Toggle);
23
24pub fn init(cx: &mut MutableAppContext) {
25 cx.add_bindings([
26 Binding::new("cmd-shift-O", Toggle, Some("Editor")),
27 Binding::new("escape", Toggle, Some("OutlineView")),
28 ]);
29 cx.add_action(OutlineView::toggle);
30 cx.add_action(OutlineView::confirm);
31 cx.add_action(OutlineView::select_prev);
32 cx.add_action(OutlineView::select_next);
33 cx.add_action(OutlineView::select_first);
34 cx.add_action(OutlineView::select_last);
35}
36
37struct OutlineView {
38 handle: WeakViewHandle<Self>,
39 active_editor: ViewHandle<Editor>,
40 outline: Outline<Anchor>,
41 selected_match_index: usize,
42 prev_scroll_position: Option<Vector2F>,
43 matches: Vec<StringMatch>,
44 query_editor: ViewHandle<Editor>,
45 list_state: UniformListState,
46}
47
48pub enum Event {
49 Dismissed,
50}
51
52impl Entity for OutlineView {
53 type Event = Event;
54
55 fn release(&mut self, cx: &mut MutableAppContext) {
56 self.restore_active_editor(cx);
57 }
58}
59
60impl View for OutlineView {
61 fn ui_name() -> &'static str {
62 "OutlineView"
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
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.0, false)
83 .boxed(),
84 )
85 .contained()
86 .with_style(settings.theme.selector.container)
87 .constrained()
88 .with_max_width(800.0)
89 .with_max_height(1200.0)
90 .aligned()
91 .top()
92 .named("outline view")
93 }
94
95 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
96 cx.focus(&self.query_editor);
97 }
98}
99
100impl OutlineView {
101 fn new(
102 outline: Outline<Anchor>,
103 editor: ViewHandle<Editor>,
104 cx: &mut ViewContext<Self>,
105 ) -> Self {
106 let query_editor = cx.add_view(|cx| {
107 Editor::single_line(Some(|theme| theme.selector.input_editor.clone()), cx)
108 });
109 cx.subscribe(&query_editor, Self::on_query_editor_event)
110 .detach();
111
112 let mut this = Self {
113 handle: cx.weak_handle(),
114 matches: Default::default(),
115 selected_match_index: 0,
116 prev_scroll_position: Some(editor.update(cx, |editor, cx| editor.scroll_position(cx))),
117 active_editor: editor,
118 outline,
119 query_editor,
120 list_state: Default::default(),
121 };
122 this.update_matches(cx);
123 this
124 }
125
126 fn toggle(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
127 if let Some(editor) = workspace
128 .active_item(cx)
129 .and_then(|item| item.downcast::<Editor>())
130 {
131 let buffer = editor
132 .read(cx)
133 .buffer()
134 .read(cx)
135 .read(cx)
136 .outline(Some(cx.global::<Settings>().theme.editor.syntax.as_ref()));
137 if let Some(outline) = buffer {
138 workspace.toggle_modal(cx, |cx, _| {
139 let view = cx.add_view(|cx| OutlineView::new(outline, editor, cx));
140 cx.subscribe(&view, Self::on_event).detach();
141 view
142 });
143 }
144 }
145 }
146
147 fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
148 if self.selected_match_index > 0 {
149 self.select(self.selected_match_index - 1, true, false, cx);
150 }
151 }
152
153 fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
154 if self.selected_match_index + 1 < self.matches.len() {
155 self.select(self.selected_match_index + 1, true, false, cx);
156 }
157 }
158
159 fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
160 self.select(0, true, false, cx);
161 }
162
163 fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
164 self.select(self.matches.len().saturating_sub(1), true, false, cx);
165 }
166
167 fn select(&mut self, index: usize, navigate: bool, center: bool, cx: &mut ViewContext<Self>) {
168 self.selected_match_index = index;
169 self.list_state.scroll_to(if center {
170 ScrollTarget::Center(index)
171 } else {
172 ScrollTarget::Show(index)
173 });
174 if navigate {
175 let selected_match = &self.matches[self.selected_match_index];
176 let outline_item = &self.outline.items[selected_match.candidate_id];
177 self.active_editor.update(cx, |active_editor, cx| {
178 let snapshot = active_editor.snapshot(cx).display_snapshot;
179 let buffer_snapshot = &snapshot.buffer_snapshot;
180 let start = outline_item.range.start.to_point(&buffer_snapshot);
181 let end = outline_item.range.end.to_point(&buffer_snapshot);
182 let display_rows = start.to_display_point(&snapshot).row()
183 ..end.to_display_point(&snapshot).row() + 1;
184 active_editor.highlight_rows(Some(display_rows));
185 active_editor.request_autoscroll(Autoscroll::Center, cx);
186 });
187 }
188 cx.notify();
189 }
190
191 fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
192 self.prev_scroll_position.take();
193 self.active_editor.update(cx, |active_editor, cx| {
194 if let Some(rows) = active_editor.highlighted_rows() {
195 let snapshot = active_editor.snapshot(cx).display_snapshot;
196 let position = DisplayPoint::new(rows.start, 0).to_point(&snapshot);
197 active_editor.select_ranges([position..position], Some(Autoscroll::Center), cx);
198 }
199 });
200 cx.emit(Event::Dismissed);
201 }
202
203 fn restore_active_editor(&mut self, cx: &mut MutableAppContext) {
204 self.active_editor.update(cx, |editor, cx| {
205 editor.highlight_rows(None);
206 if let Some(scroll_position) = self.prev_scroll_position {
207 editor.set_scroll_position(scroll_position, cx);
208 }
209 })
210 }
211
212 fn on_event(
213 workspace: &mut Workspace,
214 _: ViewHandle<Self>,
215 event: &Event,
216 cx: &mut ViewContext<Workspace>,
217 ) {
218 match event {
219 Event::Dismissed => workspace.dismiss_modal(cx),
220 }
221 }
222
223 fn on_query_editor_event(
224 &mut self,
225 _: ViewHandle<Editor>,
226 event: &editor::Event,
227 cx: &mut ViewContext<Self>,
228 ) {
229 match event {
230 editor::Event::Blurred => cx.emit(Event::Dismissed),
231 editor::Event::BufferEdited { .. } => self.update_matches(cx),
232 _ => {}
233 }
234 }
235
236 fn update_matches(&mut self, cx: &mut ViewContext<Self>) {
237 let selected_index;
238 let navigate_to_selected_index;
239 let query = self.query_editor.update(cx, |buffer, cx| buffer.text(cx));
240 if query.is_empty() {
241 self.restore_active_editor(cx);
242 self.matches = self
243 .outline
244 .items
245 .iter()
246 .enumerate()
247 .map(|(index, _)| StringMatch {
248 candidate_id: index,
249 score: Default::default(),
250 positions: Default::default(),
251 string: Default::default(),
252 })
253 .collect();
254
255 let editor = self.active_editor.read(cx);
256 let buffer = editor.buffer().read(cx).read(cx);
257 let cursor_offset = editor
258 .newest_selection_with_snapshot::<usize>(&buffer)
259 .head();
260 selected_index = self
261 .outline
262 .items
263 .iter()
264 .enumerate()
265 .map(|(ix, item)| {
266 let range = item.range.to_offset(&buffer);
267 let distance_to_closest_endpoint = cmp::min(
268 (range.start as isize - cursor_offset as isize).abs() as usize,
269 (range.end as isize - cursor_offset as isize).abs() as usize,
270 );
271 let depth = if range.contains(&cursor_offset) {
272 Some(item.depth)
273 } else {
274 None
275 };
276 (ix, depth, distance_to_closest_endpoint)
277 })
278 .max_by_key(|(_, depth, distance)| (*depth, Reverse(*distance)))
279 .unwrap()
280 .0;
281 navigate_to_selected_index = false;
282 } else {
283 self.matches = smol::block_on(self.outline.search(&query, cx.background().clone()));
284 selected_index = self
285 .matches
286 .iter()
287 .enumerate()
288 .max_by_key(|(_, m)| OrderedFloat(m.score))
289 .map(|(ix, _)| ix)
290 .unwrap_or(0);
291 navigate_to_selected_index = !self.matches.is_empty();
292 }
293 self.select(selected_index, navigate_to_selected_index, true, cx);
294 }
295
296 fn render_matches(&self, cx: &AppContext) -> ElementBox {
297 if self.matches.is_empty() {
298 let settings = cx.global::<Settings>();
299 return Container::new(
300 Label::new(
301 "No matches".into(),
302 settings.theme.selector.empty.label.clone(),
303 )
304 .boxed(),
305 )
306 .with_style(settings.theme.selector.empty.container)
307 .named("empty matches");
308 }
309
310 let handle = self.handle.clone();
311 let list = UniformList::new(
312 self.list_state.clone(),
313 self.matches.len(),
314 move |mut range, items, cx| {
315 let cx = cx.as_ref();
316 let view = handle.upgrade(cx).unwrap();
317 let view = view.read(cx);
318 let start = range.start;
319 range.end = cmp::min(range.end, view.matches.len());
320 items.extend(
321 view.matches[range]
322 .iter()
323 .enumerate()
324 .map(move |(ix, m)| view.render_match(m, start + ix, cx)),
325 );
326 },
327 );
328
329 Container::new(list.boxed())
330 .with_margin_top(6.0)
331 .named("matches")
332 }
333
334 fn render_match(
335 &self,
336 string_match: &StringMatch,
337 index: usize,
338 cx: &AppContext,
339 ) -> ElementBox {
340 let settings = cx.global::<Settings>();
341 let style = if index == self.selected_match_index {
342 &settings.theme.selector.active_item
343 } else {
344 &settings.theme.selector.item
345 };
346 let outline_item = &self.outline.items[string_match.candidate_id];
347
348 Text::new(outline_item.text.clone(), style.label.text.clone())
349 .with_soft_wrap(false)
350 .with_highlights(combine_syntax_and_fuzzy_match_highlights(
351 &outline_item.text,
352 style.label.text.clone().into(),
353 outline_item.highlight_ranges.iter().cloned(),
354 &string_match.positions,
355 ))
356 .contained()
357 .with_padding_left(20. * outline_item.depth as f32)
358 .contained()
359 .with_style(style.container)
360 .boxed()
361 }
362}