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