outline.rs

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