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