1use editor::{
2 combine_syntax_and_fuzzy_match_highlights, display_map::ToDisplayPoint, Anchor, AnchorRangeExt,
3 Autoscroll, DisplayPoint, Editor, ToPoint,
4};
5use fuzzy::StringMatch;
6use gpui::{
7 actions, elements::*, geometry::vector::Vector2F, AnyViewHandle, AppContext, Entity,
8 MouseState, MutableAppContext, 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 MutableAppContext) {
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 MutableAppContext) {
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.clone(), 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| Picker::new(handle, cx).with_max_size(800., 1200.)),
71 last_query: Default::default(),
72 matches: Default::default(),
73 selected_match_index: 0,
74 prev_scroll_position: Some(editor.update(cx, |editor, cx| editor.scroll_position(cx))),
75 active_editor: editor,
76 outline,
77 }
78 }
79
80 fn toggle(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
81 if let Some(editor) = workspace
82 .active_item(cx)
83 .and_then(|item| item.downcast::<Editor>())
84 {
85 let buffer = editor
86 .read(cx)
87 .buffer()
88 .read(cx)
89 .snapshot(cx)
90 .outline(Some(cx.global::<Settings>().theme.editor.syntax.as_ref()));
91 if let Some(outline) = buffer {
92 workspace.toggle_modal(cx, |_, cx| {
93 let view = cx.add_view(|cx| OutlineView::new(outline, editor, cx));
94 cx.subscribe(&view, Self::on_event).detach();
95 view
96 });
97 }
98 }
99 }
100
101 fn restore_active_editor(&mut self, cx: &mut MutableAppContext) {
102 self.active_editor.update(cx, |editor, cx| {
103 editor.highlight_rows(None);
104 if let Some(scroll_position) = self.prev_scroll_position {
105 editor.set_scroll_position(scroll_position, cx);
106 }
107 })
108 }
109
110 fn set_selected_index(&mut self, ix: usize, navigate: bool, cx: &mut ViewContext<Self>) {
111 self.selected_match_index = ix;
112 if navigate && !self.matches.is_empty() {
113 let selected_match = &self.matches[self.selected_match_index];
114 let outline_item = &self.outline.items[selected_match.candidate_id];
115 self.active_editor.update(cx, |active_editor, cx| {
116 let snapshot = active_editor.snapshot(cx).display_snapshot;
117 let buffer_snapshot = &snapshot.buffer_snapshot;
118 let start = outline_item.range.start.to_point(buffer_snapshot);
119 let end = outline_item.range.end.to_point(buffer_snapshot);
120 let display_rows = start.to_display_point(&snapshot).row()
121 ..end.to_display_point(&snapshot).row() + 1;
122 active_editor.highlight_rows(Some(display_rows));
123 active_editor.request_autoscroll(Autoscroll::Center, cx);
124 });
125 }
126 cx.notify();
127 }
128
129 fn on_event(
130 workspace: &mut Workspace,
131 _: ViewHandle<Self>,
132 event: &Event,
133 cx: &mut ViewContext<Workspace>,
134 ) {
135 match event {
136 Event::Dismissed => workspace.dismiss_modal(cx),
137 }
138 }
139}
140
141impl PickerDelegate for OutlineView {
142 fn match_count(&self) -> usize {
143 self.matches.len()
144 }
145
146 fn selected_index(&self) -> usize {
147 self.selected_match_index
148 }
149
150 fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Self>) {
151 self.set_selected_index(ix, true, cx);
152 }
153
154 fn center_selection_after_match_updates(&self) -> bool {
155 true
156 }
157
158 fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) -> Task<()> {
159 let selected_index;
160 if query.is_empty() {
161 self.restore_active_editor(cx);
162 self.matches = self
163 .outline
164 .items
165 .iter()
166 .enumerate()
167 .map(|(index, _)| StringMatch {
168 candidate_id: index,
169 score: Default::default(),
170 positions: Default::default(),
171 string: Default::default(),
172 })
173 .collect();
174
175 let editor = self.active_editor.read(cx);
176 let cursor_offset = editor.selections.newest::<usize>(cx).head();
177 let buffer = editor.buffer().read(cx).snapshot(cx);
178 selected_index = self
179 .outline
180 .items
181 .iter()
182 .enumerate()
183 .map(|(ix, item)| {
184 let range = item.range.to_offset(&buffer);
185 let distance_to_closest_endpoint = cmp::min(
186 (range.start as isize - cursor_offset as isize).abs(),
187 (range.end as isize - cursor_offset as isize).abs(),
188 );
189 let depth = if range.contains(&cursor_offset) {
190 Some(item.depth)
191 } else {
192 None
193 };
194 (ix, depth, distance_to_closest_endpoint)
195 })
196 .max_by_key(|(_, depth, distance)| (*depth, Reverse(*distance)))
197 .map(|(ix, _, _)| ix)
198 .unwrap_or(0);
199 } else {
200 self.matches = smol::block_on(self.outline.search(&query, cx.background().clone()));
201 selected_index = self
202 .matches
203 .iter()
204 .enumerate()
205 .max_by_key(|(_, m)| OrderedFloat(m.score))
206 .map(|(ix, _)| ix)
207 .unwrap_or(0);
208 }
209 self.last_query = query;
210 self.set_selected_index(selected_index, !self.last_query.is_empty(), cx);
211 Task::ready(())
212 }
213
214 fn confirm(&mut self, cx: &mut ViewContext<Self>) {
215 self.prev_scroll_position.take();
216 self.active_editor.update(cx, |active_editor, cx| {
217 if let Some(rows) = active_editor.highlighted_rows() {
218 let snapshot = active_editor.snapshot(cx).display_snapshot;
219 let position = DisplayPoint::new(rows.start, 0).to_point(&snapshot);
220 active_editor.change_selections(Some(Autoscroll::Center), cx, |s| {
221 s.select_ranges([position..position])
222 });
223 }
224 });
225 cx.emit(Event::Dismissed);
226 }
227
228 fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
229 self.restore_active_editor(cx);
230 cx.emit(Event::Dismissed);
231 }
232
233 fn render_match(
234 &self,
235 ix: usize,
236 mouse_state: &mut MouseState,
237 selected: bool,
238 cx: &AppContext,
239 ) -> ElementBox {
240 let settings = cx.global::<Settings>();
241 let string_match = &self.matches[ix];
242 let style = settings.theme.picker.item.style_for(mouse_state, selected);
243 let outline_item = &self.outline.items[string_match.candidate_id];
244
245 Text::new(outline_item.text.clone(), style.label.text.clone())
246 .with_soft_wrap(false)
247 .with_highlights(combine_syntax_and_fuzzy_match_highlights(
248 &outline_item.text,
249 style.label.text.clone().into(),
250 outline_item.highlight_ranges.iter().cloned(),
251 &string_match.positions,
252 ))
253 .contained()
254 .with_padding_left(20. * outline_item.depth as f32)
255 .contained()
256 .with_style(style.container)
257 .boxed()
258 }
259}