outline.rs

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