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, MutableAppContext,
8 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 .read(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 buffer = editor.buffer().read(cx).read(cx);
175 let cursor_offset = editor
176 .newest_selection_with_snapshot::<usize>(&buffer)
177 .head();
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() as usize,
187 (range.end as isize - cursor_offset as isize).abs() as usize,
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.select_ranges([position..position], Some(Autoscroll::Center), cx);
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(&self, ix: usize, selected: bool, cx: &AppContext) -> ElementBox {
232 let settings = cx.global::<Settings>();
233 let string_match = &self.matches[ix];
234 let style = if selected {
235 &settings.theme.selector.active_item
236 } else {
237 &settings.theme.selector.item
238 };
239 let outline_item = &self.outline.items[string_match.candidate_id];
240
241 Text::new(outline_item.text.clone(), style.label.text.clone())
242 .with_soft_wrap(false)
243 .with_highlights(combine_syntax_and_fuzzy_match_highlights(
244 &outline_item.text,
245 style.label.text.clone().into(),
246 outline_item.highlight_ranges.iter().cloned(),
247 &string_match.positions,
248 ))
249 .contained()
250 .with_padding_left(20. * outline_item.depth as f32)
251 .contained()
252 .with_style(style.container)
253 .boxed()
254 }
255}