1use crate::{Autoscroll, Editor, Event, NavigationData, ToOffset, ToPoint as _};
2use anyhow::{anyhow, Result};
3use gpui::{
4 elements::*, AppContext, Entity, ModelHandle, MutableAppContext, RenderContext, Subscription,
5 Task, View, ViewContext, ViewHandle,
6};
7use language::{Bias, Buffer, Diagnostic, File as _};
8use project::{File, Project, ProjectEntryId, ProjectPath};
9use rpc::proto::{self, update_followers::update_view};
10use std::{fmt::Write, path::PathBuf};
11use text::{Point, Selection};
12use util::ResultExt;
13use workspace::{
14 FollowableItem, Item, ItemHandle, ItemNavHistory, ProjectItem, Settings, StatusItemView,
15};
16
17impl FollowableItem for Editor {
18 fn for_state_message(
19 pane: ViewHandle<workspace::Pane>,
20 project: ModelHandle<Project>,
21 state: &mut Option<proto::view::Variant>,
22 cx: &mut MutableAppContext,
23 ) -> Option<Task<Result<ViewHandle<Self>>>> {
24 let state = if matches!(state, Some(proto::view::Variant::Editor(_))) {
25 if let Some(proto::view::Variant::Editor(state)) = state.take() {
26 state
27 } else {
28 unreachable!()
29 }
30 } else {
31 return None;
32 };
33
34 let buffer = project.update(cx, |project, cx| {
35 project.open_buffer_by_id(state.buffer_id, cx)
36 });
37 Some(cx.spawn(|mut cx| async move {
38 let buffer = buffer.await?;
39 Ok(pane
40 .read_with(&cx, |pane, cx| {
41 pane.items_of_type::<Self>().find(|editor| {
42 editor.read(cx).buffer.read(cx).as_singleton().as_ref() == Some(&buffer)
43 })
44 })
45 .unwrap_or_else(|| {
46 cx.add_view(pane.window_id(), |cx| {
47 Editor::for_buffer(buffer, Some(project), cx)
48 })
49 }))
50 }))
51 }
52
53 fn set_following(&mut self, following: bool, cx: &mut ViewContext<Self>) {
54 self.following = following;
55 if self.following {
56 self.show_local_selections = false;
57 self.buffer.update(cx, |buffer, cx| {
58 buffer.remove_active_selections(cx);
59 });
60 } else {
61 self.show_local_selections = true;
62 if self.focused {
63 self.buffer.update(cx, |buffer, cx| {
64 buffer.set_active_selections(&self.selections, cx);
65 });
66 }
67 }
68 cx.notify();
69 }
70
71 fn to_state_message(&self, cx: &AppContext) -> Option<proto::view::Variant> {
72 let buffer_id = self.buffer.read(cx).as_singleton()?.read(cx).remote_id();
73 Some(proto::view::Variant::Editor(proto::view::Editor {
74 buffer_id,
75 scroll_top: self
76 .scroll_top_anchor
77 .as_ref()
78 .map(|anchor| language::proto::serialize_anchor(&anchor.text_anchor)),
79 }))
80 }
81
82 fn to_update_message(
83 &self,
84 event: &Self::Event,
85 _: &AppContext,
86 ) -> Option<update_view::Variant> {
87 match event {
88 Event::ScrollPositionChanged => {
89 Some(update_view::Variant::Editor(update_view::Editor {
90 scroll_top: self
91 .scroll_top_anchor
92 .as_ref()
93 .map(|anchor| language::proto::serialize_anchor(&anchor.text_anchor)),
94 }))
95 }
96 _ => None,
97 }
98 }
99
100 fn apply_update_message(
101 &mut self,
102 message: update_view::Variant,
103 cx: &mut ViewContext<Self>,
104 ) -> Result<()> {
105 match message {
106 update_view::Variant::Editor(message) => {
107 if let Some(anchor) = message.scroll_top {
108 let anchor = language::proto::deserialize_anchor(anchor)
109 .ok_or_else(|| anyhow!("invalid scroll top"))?;
110 let anchor = {
111 let buffer = self.buffer.read(cx);
112 let buffer = buffer.read(cx);
113 let (excerpt_id, _, _) = buffer.as_singleton().unwrap();
114 buffer.anchor_in_excerpt(excerpt_id.clone(), anchor)
115 };
116 self.set_scroll_top_anchor(Some(anchor), cx);
117 } else {
118 self.set_scroll_top_anchor(None, cx);
119 }
120 }
121 }
122 Ok(())
123 }
124}
125
126impl Item for Editor {
127 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) {
128 if let Some(data) = data.downcast_ref::<NavigationData>() {
129 let buffer = self.buffer.read(cx).read(cx);
130 let offset = if buffer.can_resolve(&data.anchor) {
131 data.anchor.to_offset(&buffer)
132 } else {
133 buffer.clip_offset(data.offset, Bias::Left)
134 };
135
136 drop(buffer);
137 let nav_history = self.nav_history.take();
138 self.select_ranges([offset..offset], Some(Autoscroll::Fit), cx);
139 self.nav_history = nav_history;
140 }
141 }
142
143 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
144 let title = self.title(cx);
145 Label::new(title, style.label.clone()).boxed()
146 }
147
148 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
149 File::from_dyn(self.buffer().read(cx).file(cx)).map(|file| ProjectPath {
150 worktree_id: file.worktree_id(cx),
151 path: file.path().clone(),
152 })
153 }
154
155 fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
156 File::from_dyn(self.buffer().read(cx).file(cx)).and_then(|file| file.project_entry_id(cx))
157 }
158
159 fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
160 where
161 Self: Sized,
162 {
163 Some(self.clone(cx))
164 }
165
166 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
167 self.nav_history = Some(history);
168 }
169
170 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
171 let selection = self.newest_anchor_selection();
172 self.push_to_nav_history(selection.head(), None, cx);
173 }
174
175 fn is_dirty(&self, cx: &AppContext) -> bool {
176 self.buffer().read(cx).read(cx).is_dirty()
177 }
178
179 fn has_conflict(&self, cx: &AppContext) -> bool {
180 self.buffer().read(cx).read(cx).has_conflict()
181 }
182
183 fn can_save(&self, cx: &AppContext) -> bool {
184 !self.buffer().read(cx).is_singleton() || self.project_path(cx).is_some()
185 }
186
187 fn save(
188 &mut self,
189 project: ModelHandle<Project>,
190 cx: &mut ViewContext<Self>,
191 ) -> Task<Result<()>> {
192 let buffer = self.buffer().clone();
193 let buffers = buffer.read(cx).all_buffers();
194 let transaction = project.update(cx, |project, cx| project.format(buffers, true, cx));
195 cx.spawn(|this, mut cx| async move {
196 let transaction = transaction.await.log_err();
197 this.update(&mut cx, |editor, cx| {
198 editor.request_autoscroll(Autoscroll::Fit, cx)
199 });
200 buffer
201 .update(&mut cx, |buffer, cx| {
202 if let Some(transaction) = transaction {
203 if !buffer.is_singleton() {
204 buffer.push_transaction(&transaction.0);
205 }
206 }
207
208 buffer.save(cx)
209 })
210 .await?;
211 Ok(())
212 })
213 }
214
215 fn can_save_as(&self, cx: &AppContext) -> bool {
216 self.buffer().read(cx).is_singleton()
217 }
218
219 fn save_as(
220 &mut self,
221 project: ModelHandle<Project>,
222 abs_path: PathBuf,
223 cx: &mut ViewContext<Self>,
224 ) -> Task<Result<()>> {
225 let buffer = self
226 .buffer()
227 .read(cx)
228 .as_singleton()
229 .expect("cannot call save_as on an excerpt list")
230 .clone();
231
232 project.update(cx, |project, cx| {
233 project.save_buffer_as(buffer, abs_path, cx)
234 })
235 }
236
237 fn should_activate_item_on_event(event: &Event) -> bool {
238 matches!(event, Event::Activate)
239 }
240
241 fn should_close_item_on_event(event: &Event) -> bool {
242 matches!(event, Event::Closed)
243 }
244
245 fn should_update_tab_on_event(event: &Event) -> bool {
246 matches!(event, Event::Saved | Event::Dirtied | Event::TitleChanged)
247 }
248}
249
250impl ProjectItem for Editor {
251 type Item = Buffer;
252
253 fn for_project_item(
254 project: ModelHandle<Project>,
255 buffer: ModelHandle<Buffer>,
256 cx: &mut ViewContext<Self>,
257 ) -> Self {
258 Self::for_buffer(buffer, Some(project), cx)
259 }
260}
261
262pub struct CursorPosition {
263 position: Option<Point>,
264 selected_count: usize,
265 _observe_active_editor: Option<Subscription>,
266}
267
268impl CursorPosition {
269 pub fn new() -> Self {
270 Self {
271 position: None,
272 selected_count: 0,
273 _observe_active_editor: None,
274 }
275 }
276
277 fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
278 let editor = editor.read(cx);
279 let buffer = editor.buffer().read(cx).snapshot(cx);
280
281 self.selected_count = 0;
282 let mut last_selection: Option<Selection<usize>> = None;
283 for selection in editor.local_selections::<usize>(cx) {
284 self.selected_count += selection.end - selection.start;
285 if last_selection
286 .as_ref()
287 .map_or(true, |last_selection| selection.id > last_selection.id)
288 {
289 last_selection = Some(selection);
290 }
291 }
292 self.position = last_selection.map(|s| s.head().to_point(&buffer));
293
294 cx.notify();
295 }
296}
297
298impl Entity for CursorPosition {
299 type Event = ();
300}
301
302impl View for CursorPosition {
303 fn ui_name() -> &'static str {
304 "CursorPosition"
305 }
306
307 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
308 if let Some(position) = self.position {
309 let theme = &cx.global::<Settings>().theme.workspace.status_bar;
310 let mut text = format!("{},{}", position.row + 1, position.column + 1);
311 if self.selected_count > 0 {
312 write!(text, " ({} selected)", self.selected_count).unwrap();
313 }
314 Label::new(text, theme.cursor_position.clone()).boxed()
315 } else {
316 Empty::new().boxed()
317 }
318 }
319}
320
321impl StatusItemView for CursorPosition {
322 fn set_active_pane_item(
323 &mut self,
324 active_pane_item: Option<&dyn ItemHandle>,
325 cx: &mut ViewContext<Self>,
326 ) {
327 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
328 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
329 self.update_position(editor, cx);
330 } else {
331 self.position = None;
332 self._observe_active_editor = None;
333 }
334
335 cx.notify();
336 }
337}
338
339pub struct DiagnosticMessage {
340 diagnostic: Option<Diagnostic>,
341 _observe_active_editor: Option<Subscription>,
342}
343
344impl DiagnosticMessage {
345 pub fn new() -> Self {
346 Self {
347 diagnostic: None,
348 _observe_active_editor: None,
349 }
350 }
351
352 fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
353 let editor = editor.read(cx);
354 let buffer = editor.buffer().read(cx);
355 let cursor_position = editor
356 .newest_selection_with_snapshot::<usize>(&buffer.read(cx))
357 .head();
358 let new_diagnostic = buffer
359 .read(cx)
360 .diagnostics_in_range::<_, usize>(cursor_position..cursor_position, false)
361 .filter(|entry| !entry.range.is_empty())
362 .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
363 .map(|entry| entry.diagnostic);
364 if new_diagnostic != self.diagnostic {
365 self.diagnostic = new_diagnostic;
366 cx.notify();
367 }
368 }
369}
370
371impl Entity for DiagnosticMessage {
372 type Event = ();
373}
374
375impl View for DiagnosticMessage {
376 fn ui_name() -> &'static str {
377 "DiagnosticMessage"
378 }
379
380 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
381 if let Some(diagnostic) = &self.diagnostic {
382 let theme = &cx.global::<Settings>().theme.workspace.status_bar;
383 Label::new(
384 diagnostic.message.split('\n').next().unwrap().to_string(),
385 theme.diagnostic_message.clone(),
386 )
387 .boxed()
388 } else {
389 Empty::new().boxed()
390 }
391 }
392}
393
394impl StatusItemView for DiagnosticMessage {
395 fn set_active_pane_item(
396 &mut self,
397 active_pane_item: Option<&dyn ItemHandle>,
398 cx: &mut ViewContext<Self>,
399 ) {
400 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
401 self._observe_active_editor = Some(cx.observe(&editor, Self::update));
402 self.update(editor, cx);
403 } else {
404 self.diagnostic = Default::default();
405 self._observe_active_editor = None;
406 }
407 cx.notify();
408 }
409}