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