1use editor::{
2 display_map::ToDisplayPoint, scroll::Autoscroll, Anchor, AnchorRangeExt, DisplayPoint, Editor,
3 EditorMode, ToPoint,
4};
5use fuzzy::StringMatch;
6use gpui::{
7 actions, div, rems, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,
8 FontStyle, FontWeight, HighlightStyle, ParentElement, Point, Render, Styled, StyledText, Task,
9 TextStyle, View, ViewContext, VisualContext, WeakView, WhiteSpace, WindowContext,
10};
11use language::Outline;
12use ordered_float::OrderedFloat;
13use picker::{Picker, PickerDelegate};
14use settings::Settings;
15use std::{
16 cmp::{self, Reverse},
17 sync::Arc,
18};
19
20use theme::{color_alpha, ActiveTheme, ThemeSettings};
21use ui::{prelude::*, ListItem, ListItemSpacing};
22use util::ResultExt;
23use workspace::ModalView;
24
25actions!(outline, [Toggle]);
26
27pub fn init(cx: &mut AppContext) {
28 cx.observe_new_views(OutlineView::register).detach();
29}
30
31pub fn toggle(editor: View<Editor>, _: &Toggle, cx: &mut WindowContext) {
32 let outline = editor
33 .read(cx)
34 .buffer()
35 .read(cx)
36 .snapshot(cx)
37 .outline(Some(&cx.theme().syntax()));
38
39 if let Some((workspace, outline)) = editor.read(cx).workspace().zip(outline) {
40 workspace.update(cx, |workspace, cx| {
41 workspace.toggle_modal(cx, |cx| OutlineView::new(outline, editor, cx));
42 })
43 }
44}
45
46pub struct OutlineView {
47 picker: View<Picker<OutlineViewDelegate>>,
48}
49
50impl FocusableView for OutlineView {
51 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
52 self.picker.focus_handle(cx)
53 }
54}
55
56impl EventEmitter<DismissEvent> for OutlineView {}
57impl ModalView for OutlineView {
58 fn on_before_dismiss(&mut self, cx: &mut ViewContext<Self>) -> bool {
59 self.picker
60 .update(cx, |picker, cx| picker.delegate.restore_active_editor(cx));
61 true
62 }
63}
64
65impl Render for OutlineView {
66 fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
67 v_flex().w(rems(34.)).child(self.picker.clone())
68 }
69}
70
71impl OutlineView {
72 fn register(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
73 if editor.mode() == EditorMode::Full {
74 let handle = cx.view().downgrade();
75 editor.register_action(move |action, cx| {
76 if let Some(editor) = handle.upgrade() {
77 toggle(editor, action, cx);
78 }
79 });
80 }
81 }
82
83 fn new(
84 outline: Outline<Anchor>,
85 editor: View<Editor>,
86 cx: &mut ViewContext<Self>,
87 ) -> OutlineView {
88 let delegate = OutlineViewDelegate::new(cx.view().downgrade(), outline, editor, cx);
89 let picker = cx.new_view(|cx| Picker::new(delegate, cx).max_height(vh(0.75, cx)));
90 OutlineView { picker }
91 }
92}
93
94struct OutlineViewDelegate {
95 outline_view: WeakView<OutlineView>,
96 active_editor: View<Editor>,
97 outline: Outline<Anchor>,
98 selected_match_index: usize,
99 prev_scroll_position: Option<Point<f32>>,
100 matches: Vec<StringMatch>,
101 last_query: String,
102}
103
104impl OutlineViewDelegate {
105 fn new(
106 outline_view: WeakView<OutlineView>,
107 outline: Outline<Anchor>,
108 editor: View<Editor>,
109 cx: &mut ViewContext<OutlineView>,
110 ) -> Self {
111 Self {
112 outline_view,
113 last_query: Default::default(),
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 }
120 }
121
122 fn restore_active_editor(&mut self, cx: &mut WindowContext) {
123 self.active_editor.update(cx, |editor, cx| {
124 editor.highlight_rows(None);
125 if let Some(scroll_position) = self.prev_scroll_position {
126 editor.set_scroll_position(scroll_position, cx);
127 }
128 })
129 }
130
131 fn set_selected_index(
132 &mut self,
133 ix: usize,
134 navigate: bool,
135 cx: &mut ViewContext<Picker<OutlineViewDelegate>>,
136 ) {
137 self.selected_match_index = ix;
138
139 if navigate && !self.matches.is_empty() {
140 let selected_match = &self.matches[self.selected_match_index];
141 let outline_item = &self.outline.items[selected_match.candidate_id];
142
143 self.active_editor.update(cx, |active_editor, cx| {
144 let snapshot = active_editor.snapshot(cx).display_snapshot;
145 let buffer_snapshot = &snapshot.buffer_snapshot;
146 let start = outline_item.range.start.to_point(buffer_snapshot);
147 let end = outline_item.range.end.to_point(buffer_snapshot);
148 let display_rows = start.to_display_point(&snapshot).row()
149 ..end.to_display_point(&snapshot).row() + 1;
150 active_editor.highlight_rows(Some(display_rows));
151 active_editor.request_autoscroll(Autoscroll::center(), cx);
152 });
153 }
154 }
155}
156
157impl PickerDelegate for OutlineViewDelegate {
158 type ListItem = ListItem;
159
160 fn placeholder_text(&self) -> Arc<str> {
161 "Search buffer symbols...".into()
162 }
163
164 fn match_count(&self) -> usize {
165 self.matches.len()
166 }
167
168 fn selected_index(&self) -> usize {
169 self.selected_match_index
170 }
171
172 fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<OutlineViewDelegate>>) {
173 self.set_selected_index(ix, true, cx);
174 }
175
176 fn update_matches(
177 &mut self,
178 query: String,
179 cx: &mut ViewContext<Picker<OutlineViewDelegate>>,
180 ) -> Task<()> {
181 let selected_index;
182 if query.is_empty() {
183 self.restore_active_editor(cx);
184 self.matches = self
185 .outline
186 .items
187 .iter()
188 .enumerate()
189 .map(|(index, _)| StringMatch {
190 candidate_id: index,
191 score: Default::default(),
192 positions: Default::default(),
193 string: Default::default(),
194 })
195 .collect();
196
197 let editor = self.active_editor.read(cx);
198 let cursor_offset = editor.selections.newest::<usize>(cx).head();
199 let buffer = editor.buffer().read(cx).snapshot(cx);
200 selected_index = self
201 .outline
202 .items
203 .iter()
204 .enumerate()
205 .map(|(ix, item)| {
206 let range = item.range.to_offset(&buffer);
207 let distance_to_closest_endpoint = cmp::min(
208 (range.start as isize - cursor_offset as isize).abs(),
209 (range.end as isize - cursor_offset as isize).abs(),
210 );
211 let depth = if range.contains(&cursor_offset) {
212 Some(item.depth)
213 } else {
214 None
215 };
216 (ix, depth, distance_to_closest_endpoint)
217 })
218 .max_by_key(|(_, depth, distance)| (*depth, Reverse(*distance)))
219 .map(|(ix, _, _)| ix)
220 .unwrap_or(0);
221 } else {
222 self.matches = smol::block_on(
223 self.outline
224 .search(&query, cx.background_executor().clone()),
225 );
226 selected_index = self
227 .matches
228 .iter()
229 .enumerate()
230 .max_by_key(|(_, m)| OrderedFloat(m.score))
231 .map(|(ix, _)| ix)
232 .unwrap_or(0);
233 }
234 self.last_query = query;
235 self.set_selected_index(selected_index, !self.last_query.is_empty(), cx);
236 Task::ready(())
237 }
238
239 fn confirm(&mut self, _: bool, cx: &mut ViewContext<Picker<OutlineViewDelegate>>) {
240 self.prev_scroll_position.take();
241
242 self.active_editor.update(cx, |active_editor, cx| {
243 if let Some(rows) = active_editor.highlighted_rows() {
244 let snapshot = active_editor.snapshot(cx).display_snapshot;
245 let position = DisplayPoint::new(rows.start, 0).to_point(&snapshot);
246 active_editor.change_selections(Some(Autoscroll::center()), cx, |s| {
247 s.select_ranges([position..position])
248 });
249 active_editor.highlight_rows(None);
250 active_editor.focus(cx);
251 }
252 });
253
254 self.dismissed(cx);
255 }
256
257 fn dismissed(&mut self, cx: &mut ViewContext<Picker<OutlineViewDelegate>>) {
258 self.outline_view
259 .update(cx, |_, cx| cx.emit(DismissEvent))
260 .log_err();
261 self.restore_active_editor(cx);
262 }
263
264 fn render_match(
265 &self,
266 ix: usize,
267 selected: bool,
268 cx: &mut ViewContext<Picker<Self>>,
269 ) -> Option<Self::ListItem> {
270 let settings = ThemeSettings::get_global(cx);
271
272 // TODO: We probably shouldn't need to build a whole new text style here
273 // but I'm not sure how to get the current one and modify it.
274 // Before this change TextStyle::default() was used here, which was giving us the wrong font and text color.
275 let text_style = TextStyle {
276 color: cx.theme().colors().text,
277 font_family: settings.buffer_font.family.clone(),
278 font_features: settings.buffer_font.features,
279 font_size: settings.buffer_font_size(cx).into(),
280 font_weight: FontWeight::NORMAL,
281 font_style: FontStyle::Normal,
282 line_height: relative(1.).into(),
283 background_color: None,
284 underline: None,
285 white_space: WhiteSpace::Normal,
286 };
287
288 let mut highlight_style = HighlightStyle::default();
289 highlight_style.background_color = Some(color_alpha(cx.theme().colors().text_accent, 0.3));
290
291 let mat = &self.matches[ix];
292 let outline_item = &self.outline.items[mat.candidate_id];
293
294 let highlights = gpui::combine_highlights(
295 mat.ranges().map(|range| (range, highlight_style)),
296 outline_item.highlight_ranges.iter().cloned(),
297 );
298
299 let styled_text =
300 StyledText::new(outline_item.text.clone()).with_highlights(&text_style, highlights);
301
302 Some(
303 ListItem::new(ix)
304 .inset(true)
305 .spacing(ListItemSpacing::Sparse)
306 .selected(selected)
307 .child(
308 div()
309 .text_ui()
310 .pl(rems(outline_item.depth as f32))
311 .child(styled_text),
312 ),
313 )
314 }
315}