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