1use editor::{
2 combine_syntax_and_fuzzy_match_highlights, display_map::ToDisplayPoint,
3 scroll::autoscroll::Autoscroll, Anchor, AnchorRangeExt, DisplayPoint, Editor, ToPoint,
4};
5use fuzzy::StringMatch;
6use gpui::{
7 actions, elements::*, geometry::vector::Vector2F, AppContext, MouseState, Task, ViewContext,
8 ViewHandle, WindowContext,
9};
10use language::Outline;
11use ordered_float::OrderedFloat;
12use picker::{Picker, PickerDelegate, PickerEvent};
13use std::{
14 cmp::{self, Reverse},
15 sync::Arc,
16};
17use workspace::Workspace;
18
19actions!(outline, [Toggle]);
20
21pub fn init(cx: &mut AppContext) {
22 cx.add_action(toggle);
23 OutlineView::init(cx);
24}
25
26pub fn toggle(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
27 if let Some(editor) = workspace
28 .active_item(cx)
29 .and_then(|item| item.downcast::<Editor>())
30 {
31 let outline = editor
32 .read(cx)
33 .buffer()
34 .read(cx)
35 .snapshot(cx)
36 .outline(Some(theme::current(cx).editor.syntax.as_ref()));
37 if let Some(outline) = outline {
38 workspace.toggle_modal(cx, |_, cx| {
39 cx.add_view(|cx| {
40 OutlineView::new(OutlineViewDelegate::new(outline, editor, cx), cx)
41 .with_max_size(800., 1200.)
42 })
43 });
44 }
45 }
46}
47
48type OutlineView = Picker<OutlineViewDelegate>;
49
50struct OutlineViewDelegate {
51 active_editor: ViewHandle<Editor>,
52 outline: Outline<Anchor>,
53 selected_match_index: usize,
54 prev_scroll_position: Option<Vector2F>,
55 matches: Vec<StringMatch>,
56 last_query: String,
57}
58
59impl OutlineViewDelegate {
60 fn new(
61 outline: Outline<Anchor>,
62 editor: ViewHandle<Editor>,
63 cx: &mut ViewContext<OutlineView>,
64 ) -> Self {
65 Self {
66 last_query: Default::default(),
67 matches: Default::default(),
68 selected_match_index: 0,
69 prev_scroll_position: Some(editor.update(cx, |editor, cx| editor.scroll_position(cx))),
70 active_editor: editor,
71 outline,
72 }
73 }
74
75 fn restore_active_editor(&mut self, cx: &mut WindowContext) {
76 self.active_editor.update(cx, |editor, cx| {
77 editor.highlight_rows(None);
78 if let Some(scroll_position) = self.prev_scroll_position {
79 editor.set_scroll_position(scroll_position, cx);
80 }
81 })
82 }
83
84 fn set_selected_index(&mut self, ix: usize, navigate: bool, cx: &mut ViewContext<OutlineView>) {
85 self.selected_match_index = ix;
86 if navigate && !self.matches.is_empty() {
87 let selected_match = &self.matches[self.selected_match_index];
88 let outline_item = &self.outline.items[selected_match.candidate_id];
89 self.active_editor.update(cx, |active_editor, cx| {
90 let snapshot = active_editor.snapshot(cx).display_snapshot;
91 let buffer_snapshot = &snapshot.buffer_snapshot;
92 let start = outline_item.range.start.to_point(buffer_snapshot);
93 let end = outline_item.range.end.to_point(buffer_snapshot);
94 let display_rows = start.to_display_point(&snapshot).row()
95 ..end.to_display_point(&snapshot).row() + 1;
96 active_editor.highlight_rows(Some(display_rows));
97 active_editor.request_autoscroll(Autoscroll::center(), cx);
98 });
99 }
100 }
101}
102
103impl PickerDelegate for OutlineViewDelegate {
104 fn placeholder_text(&self) -> Arc<str> {
105 "Search buffer symbols...".into()
106 }
107
108 fn match_count(&self) -> usize {
109 self.matches.len()
110 }
111
112 fn selected_index(&self) -> usize {
113 self.selected_match_index
114 }
115
116 fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<OutlineView>) {
117 self.set_selected_index(ix, true, cx);
118 }
119
120 fn center_selection_after_match_updates(&self) -> bool {
121 true
122 }
123
124 fn update_matches(&mut self, query: String, cx: &mut ViewContext<OutlineView>) -> Task<()> {
125 let selected_index;
126 if query.is_empty() {
127 self.restore_active_editor(cx);
128 self.matches = self
129 .outline
130 .items
131 .iter()
132 .enumerate()
133 .map(|(index, _)| StringMatch {
134 candidate_id: index,
135 score: Default::default(),
136 positions: Default::default(),
137 string: Default::default(),
138 })
139 .collect();
140
141 let editor = self.active_editor.read(cx);
142 let cursor_offset = editor.selections.newest::<usize>(cx).head();
143 let buffer = editor.buffer().read(cx).snapshot(cx);
144 selected_index = self
145 .outline
146 .items
147 .iter()
148 .enumerate()
149 .map(|(ix, item)| {
150 let range = item.range.to_offset(&buffer);
151 let distance_to_closest_endpoint = cmp::min(
152 (range.start as isize - cursor_offset as isize).abs(),
153 (range.end as isize - cursor_offset as isize).abs(),
154 );
155 let depth = if range.contains(&cursor_offset) {
156 Some(item.depth)
157 } else {
158 None
159 };
160 (ix, depth, distance_to_closest_endpoint)
161 })
162 .max_by_key(|(_, depth, distance)| (*depth, Reverse(*distance)))
163 .map(|(ix, _, _)| ix)
164 .unwrap_or(0);
165 } else {
166 self.matches = smol::block_on(self.outline.search(&query, cx.background().clone()));
167 selected_index = self
168 .matches
169 .iter()
170 .enumerate()
171 .max_by_key(|(_, m)| OrderedFloat(m.score))
172 .map(|(ix, _)| ix)
173 .unwrap_or(0);
174 }
175 self.last_query = query;
176 self.set_selected_index(selected_index, !self.last_query.is_empty(), cx);
177 Task::ready(())
178 }
179
180 fn confirm(&mut self, _: bool, cx: &mut ViewContext<OutlineView>) {
181 self.prev_scroll_position.take();
182 self.active_editor.update(cx, |active_editor, cx| {
183 if let Some(rows) = active_editor.highlighted_rows() {
184 let snapshot = active_editor.snapshot(cx).display_snapshot;
185 let position = DisplayPoint::new(rows.start, 0).to_point(&snapshot);
186 active_editor.change_selections(Some(Autoscroll::center()), cx, |s| {
187 s.select_ranges([position..position])
188 });
189 active_editor.highlight_rows(None);
190 }
191 });
192 cx.emit(PickerEvent::Dismiss);
193 }
194
195 fn dismissed(&mut self, cx: &mut ViewContext<OutlineView>) {
196 self.restore_active_editor(cx);
197 }
198
199 fn render_match(
200 &self,
201 ix: usize,
202 mouse_state: &mut MouseState,
203 selected: bool,
204 cx: &AppContext,
205 ) -> AnyElement<Picker<Self>> {
206 let theme = theme::current(cx);
207 let style = theme.picker.item.in_state(selected).style_for(mouse_state);
208 let string_match = &self.matches[ix];
209 let outline_item = &self.outline.items[string_match.candidate_id];
210
211 Text::new(outline_item.text.clone(), style.label.text.clone())
212 .with_soft_wrap(false)
213 .with_highlights(combine_syntax_and_fuzzy_match_highlights(
214 &outline_item.text,
215 style.label.text.clone().into(),
216 outline_item.highlight_ranges.iter().cloned(),
217 &string_match.positions,
218 ))
219 .contained()
220 .with_padding_left(20. * outline_item.depth as f32)
221 .contained()
222 .with_style(style.container)
223 .into_any()
224 }
225}