1use crate::{Anchor, Autoscroll, Editor, Event, ExcerptId, NavigationData, ToPoint as _};
2use anyhow::{anyhow, Result};
3use futures::FutureExt;
4use gpui::{
5 elements::*, geometry::vector::vec2f, AppContext, Entity, ModelHandle, MutableAppContext,
6 RenderContext, Subscription, Task, View, ViewContext, ViewHandle,
7};
8use language::{Bias, Buffer, Diagnostic, File as _, SelectionGoal};
9use project::{File, Project, ProjectEntryId, ProjectPath};
10use rpc::proto::{self, update_view};
11use settings::Settings;
12use std::{fmt::Write, path::PathBuf, time::Duration};
13use text::{Point, Selection};
14use util::TryFutureExt;
15use workspace::{FollowableItem, Item, ItemHandle, ItemNavHistory, ProjectItem, StatusItemView};
16
17pub const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
18
19impl FollowableItem for Editor {
20 fn from_state_proto(
21 pane: ViewHandle<workspace::Pane>,
22 project: ModelHandle<Project>,
23 state: &mut Option<proto::view::Variant>,
24 cx: &mut MutableAppContext,
25 ) -> Option<Task<Result<ViewHandle<Self>>>> {
26 let state = if matches!(state, Some(proto::view::Variant::Editor(_))) {
27 if let Some(proto::view::Variant::Editor(state)) = state.take() {
28 state
29 } else {
30 unreachable!()
31 }
32 } else {
33 return None;
34 };
35
36 let buffer = project.update(cx, |project, cx| {
37 project.open_buffer_by_id(state.buffer_id, cx)
38 });
39 Some(cx.spawn(|mut cx| async move {
40 let buffer = buffer.await?;
41 let editor = pane
42 .read_with(&cx, |pane, cx| {
43 pane.items_of_type::<Self>().find(|editor| {
44 editor.read(cx).buffer.read(cx).as_singleton().as_ref() == Some(&buffer)
45 })
46 })
47 .unwrap_or_else(|| {
48 cx.add_view(pane.window_id(), |cx| {
49 Editor::for_buffer(buffer, Some(project), cx)
50 })
51 });
52 editor.update(&mut cx, |editor, cx| {
53 let excerpt_id;
54 let buffer_id;
55 {
56 let buffer = editor.buffer.read(cx).read(cx);
57 let singleton = buffer.as_singleton().unwrap();
58 excerpt_id = singleton.0.clone();
59 buffer_id = singleton.1;
60 }
61 let selections = state
62 .selections
63 .into_iter()
64 .map(|selection| {
65 deserialize_selection(&excerpt_id, buffer_id, selection)
66 .ok_or_else(|| anyhow!("invalid selection"))
67 })
68 .collect::<Result<Vec<_>>>()?;
69 if !selections.is_empty() {
70 editor.set_selections_from_remote(selections.into(), cx);
71 }
72
73 if let Some(anchor) = state.scroll_top_anchor {
74 editor.set_scroll_top_anchor(
75 Anchor {
76 buffer_id: Some(state.buffer_id as usize),
77 excerpt_id: excerpt_id.clone(),
78 text_anchor: language::proto::deserialize_anchor(anchor)
79 .ok_or_else(|| anyhow!("invalid scroll top"))?,
80 },
81 vec2f(state.scroll_x, state.scroll_y),
82 cx,
83 );
84 }
85
86 Ok::<_, anyhow::Error>(())
87 })?;
88 Ok(editor)
89 }))
90 }
91
92 fn set_leader_replica_id(
93 &mut self,
94 leader_replica_id: Option<u16>,
95 cx: &mut ViewContext<Self>,
96 ) {
97 self.leader_replica_id = leader_replica_id;
98 if self.leader_replica_id.is_some() {
99 self.buffer.update(cx, |buffer, cx| {
100 buffer.remove_active_selections(cx);
101 });
102 } else {
103 self.buffer.update(cx, |buffer, cx| {
104 if self.focused {
105 buffer.set_active_selections(&self.selections, cx);
106 }
107 });
108 }
109 cx.notify();
110 }
111
112 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
113 let buffer_id = self.buffer.read(cx).as_singleton()?.read(cx).remote_id();
114 Some(proto::view::Variant::Editor(proto::view::Editor {
115 buffer_id,
116 scroll_top_anchor: Some(language::proto::serialize_anchor(
117 &self.scroll_top_anchor.text_anchor,
118 )),
119 scroll_x: self.scroll_position.x(),
120 scroll_y: self.scroll_position.y(),
121 selections: self.selections.iter().map(serialize_selection).collect(),
122 }))
123 }
124
125 fn add_event_to_update_proto(
126 &self,
127 event: &Self::Event,
128 update: &mut Option<proto::update_view::Variant>,
129 _: &AppContext,
130 ) -> bool {
131 let update =
132 update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
133
134 match update {
135 proto::update_view::Variant::Editor(update) => match event {
136 Event::ScrollPositionChanged { .. } => {
137 update.scroll_top_anchor = Some(language::proto::serialize_anchor(
138 &self.scroll_top_anchor.text_anchor,
139 ));
140 update.scroll_x = self.scroll_position.x();
141 update.scroll_y = self.scroll_position.y();
142 true
143 }
144 Event::SelectionsChanged { .. } => {
145 update.selections = self
146 .selections
147 .iter()
148 .chain(self.pending_selection.as_ref().map(|p| &p.selection))
149 .map(serialize_selection)
150 .collect();
151 true
152 }
153 _ => false,
154 },
155 }
156 }
157
158 fn apply_update_proto(
159 &mut self,
160 message: update_view::Variant,
161 cx: &mut ViewContext<Self>,
162 ) -> Result<()> {
163 match message {
164 update_view::Variant::Editor(message) => {
165 let buffer = self.buffer.read(cx);
166 let buffer = buffer.read(cx);
167 let (excerpt_id, buffer_id, _) = buffer.as_singleton().unwrap();
168 let excerpt_id = excerpt_id.clone();
169 drop(buffer);
170
171 let selections = message
172 .selections
173 .into_iter()
174 .filter_map(|selection| {
175 deserialize_selection(&excerpt_id, buffer_id, selection)
176 })
177 .collect::<Vec<_>>();
178
179 if !selections.is_empty() {
180 self.set_selections_from_remote(selections, cx);
181 self.request_autoscroll_remotely(Autoscroll::Newest, cx);
182 } else {
183 if let Some(anchor) = message.scroll_top_anchor {
184 self.set_scroll_top_anchor(
185 Anchor {
186 buffer_id: Some(buffer_id),
187 excerpt_id: excerpt_id.clone(),
188 text_anchor: language::proto::deserialize_anchor(anchor)
189 .ok_or_else(|| anyhow!("invalid scroll top"))?,
190 },
191 vec2f(message.scroll_x, message.scroll_y),
192 cx,
193 );
194 }
195 }
196 }
197 }
198 Ok(())
199 }
200
201 fn should_unfollow_on_event(event: &Self::Event, _: &AppContext) -> bool {
202 match event {
203 Event::Edited => true,
204 Event::SelectionsChanged { local } => *local,
205 Event::ScrollPositionChanged { local } => *local,
206 _ => false,
207 }
208 }
209}
210
211fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
212 proto::Selection {
213 id: selection.id as u64,
214 start: Some(language::proto::serialize_anchor(
215 &selection.start.text_anchor,
216 )),
217 end: Some(language::proto::serialize_anchor(
218 &selection.end.text_anchor,
219 )),
220 reversed: selection.reversed,
221 }
222}
223
224fn deserialize_selection(
225 excerpt_id: &ExcerptId,
226 buffer_id: usize,
227 selection: proto::Selection,
228) -> Option<Selection<Anchor>> {
229 Some(Selection {
230 id: selection.id as usize,
231 start: Anchor {
232 buffer_id: Some(buffer_id),
233 excerpt_id: excerpt_id.clone(),
234 text_anchor: language::proto::deserialize_anchor(selection.start?)?,
235 },
236 end: Anchor {
237 buffer_id: Some(buffer_id),
238 excerpt_id: excerpt_id.clone(),
239 text_anchor: language::proto::deserialize_anchor(selection.end?)?,
240 },
241 reversed: selection.reversed,
242 goal: SelectionGoal::None,
243 })
244}
245
246impl Item for Editor {
247 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
248 if let Ok(data) = data.downcast::<NavigationData>() {
249 let buffer = self.buffer.read(cx).read(cx);
250 let offset = if buffer.can_resolve(&data.cursor_anchor) {
251 data.cursor_anchor.to_point(&buffer)
252 } else {
253 buffer.clip_point(data.cursor_position, Bias::Left)
254 };
255 let newest_selection = self.newest_selection_with_snapshot::<Point>(&buffer);
256
257 let scroll_top_anchor = if buffer.can_resolve(&data.scroll_top_anchor) {
258 data.scroll_top_anchor
259 } else {
260 buffer.anchor_before(
261 buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
262 )
263 };
264
265 drop(buffer);
266
267 if newest_selection.head() == offset {
268 false
269 } else {
270 let nav_history = self.nav_history.take();
271 self.scroll_position = data.scroll_position;
272 self.scroll_top_anchor = scroll_top_anchor;
273 self.select_ranges([offset..offset], Some(Autoscroll::Fit), cx);
274 self.nav_history = nav_history;
275 true
276 }
277 } else {
278 false
279 }
280 }
281
282 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
283 let title = self.title(cx);
284 Label::new(title, style.label.clone()).boxed()
285 }
286
287 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
288 File::from_dyn(self.buffer().read(cx).file(cx)).map(|file| ProjectPath {
289 worktree_id: file.worktree_id(cx),
290 path: file.path().clone(),
291 })
292 }
293
294 fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
295 File::from_dyn(self.buffer().read(cx).file(cx)).and_then(|file| file.project_entry_id(cx))
296 }
297
298 fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
299 where
300 Self: Sized,
301 {
302 Some(self.clone(cx))
303 }
304
305 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
306 self.nav_history = Some(history);
307 }
308
309 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
310 let selection = self.newest_anchor_selection();
311 self.push_to_nav_history(selection.head(), None, cx);
312 }
313
314 fn is_dirty(&self, cx: &AppContext) -> bool {
315 self.buffer().read(cx).read(cx).is_dirty()
316 }
317
318 fn has_conflict(&self, cx: &AppContext) -> bool {
319 self.buffer().read(cx).read(cx).has_conflict()
320 }
321
322 fn can_save(&self, cx: &AppContext) -> bool {
323 !self.buffer().read(cx).is_singleton() || self.project_path(cx).is_some()
324 }
325
326 fn save(
327 &mut self,
328 project: ModelHandle<Project>,
329 cx: &mut ViewContext<Self>,
330 ) -> Task<Result<()>> {
331 let buffer = self.buffer().clone();
332 let buffers = buffer.read(cx).all_buffers();
333 let mut timeout = cx.background().timer(FORMAT_TIMEOUT).fuse();
334 let format = project.update(cx, |project, cx| project.format(buffers, true, cx));
335 cx.spawn(|this, mut cx| async move {
336 let transaction = futures::select_biased! {
337 _ = timeout => {
338 log::warn!("timed out waiting for formatting");
339 None
340 }
341 transaction = format.log_err().fuse() => transaction,
342 };
343
344 this.update(&mut cx, |editor, cx| {
345 editor.request_autoscroll(Autoscroll::Fit, cx)
346 });
347 buffer
348 .update(&mut cx, |buffer, cx| {
349 if let Some(transaction) = transaction {
350 if !buffer.is_singleton() {
351 buffer.push_transaction(&transaction.0);
352 }
353 }
354
355 buffer.save(cx)
356 })
357 .await?;
358 Ok(())
359 })
360 }
361
362 fn can_save_as(&self, cx: &AppContext) -> bool {
363 self.buffer().read(cx).is_singleton()
364 }
365
366 fn save_as(
367 &mut self,
368 project: ModelHandle<Project>,
369 abs_path: PathBuf,
370 cx: &mut ViewContext<Self>,
371 ) -> Task<Result<()>> {
372 let buffer = self
373 .buffer()
374 .read(cx)
375 .as_singleton()
376 .expect("cannot call save_as on an excerpt list")
377 .clone();
378
379 project.update(cx, |project, cx| {
380 project.save_buffer_as(buffer, abs_path, cx)
381 })
382 }
383
384 fn reload(
385 &mut self,
386 project: ModelHandle<Project>,
387 cx: &mut ViewContext<Self>,
388 ) -> Task<Result<()>> {
389 let buffer = self.buffer().clone();
390 let buffers = self.buffer.read(cx).all_buffers();
391 let reload_buffers =
392 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
393 cx.spawn(|this, mut cx| async move {
394 let transaction = reload_buffers.log_err().await;
395 this.update(&mut cx, |editor, cx| {
396 editor.request_autoscroll(Autoscroll::Fit, cx)
397 });
398 buffer.update(&mut cx, |buffer, _| {
399 if let Some(transaction) = transaction {
400 if !buffer.is_singleton() {
401 buffer.push_transaction(&transaction.0);
402 }
403 }
404 });
405 Ok(())
406 })
407 }
408
409 fn should_activate_item_on_event(event: &Event) -> bool {
410 matches!(event, Event::Activate)
411 }
412
413 fn should_close_item_on_event(event: &Event) -> bool {
414 matches!(event, Event::Closed)
415 }
416
417 fn should_update_tab_on_event(event: &Event) -> bool {
418 matches!(event, Event::Saved | Event::Dirtied | Event::TitleChanged)
419 }
420}
421
422impl ProjectItem for Editor {
423 type Item = Buffer;
424
425 fn for_project_item(
426 project: ModelHandle<Project>,
427 buffer: ModelHandle<Buffer>,
428 cx: &mut ViewContext<Self>,
429 ) -> Self {
430 Self::for_buffer(buffer, Some(project), cx)
431 }
432}
433
434pub struct CursorPosition {
435 position: Option<Point>,
436 selected_count: usize,
437 _observe_active_editor: Option<Subscription>,
438}
439
440impl CursorPosition {
441 pub fn new() -> Self {
442 Self {
443 position: None,
444 selected_count: 0,
445 _observe_active_editor: None,
446 }
447 }
448
449 fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
450 let editor = editor.read(cx);
451 let buffer = editor.buffer().read(cx).snapshot(cx);
452
453 self.selected_count = 0;
454 let mut last_selection: Option<Selection<usize>> = None;
455 for selection in editor.local_selections::<usize>(cx) {
456 self.selected_count += selection.end - selection.start;
457 if last_selection
458 .as_ref()
459 .map_or(true, |last_selection| selection.id > last_selection.id)
460 {
461 last_selection = Some(selection);
462 }
463 }
464 self.position = last_selection.map(|s| s.head().to_point(&buffer));
465
466 cx.notify();
467 }
468}
469
470impl Entity for CursorPosition {
471 type Event = ();
472}
473
474impl View for CursorPosition {
475 fn ui_name() -> &'static str {
476 "CursorPosition"
477 }
478
479 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
480 if let Some(position) = self.position {
481 let theme = &cx.global::<Settings>().theme.workspace.status_bar;
482 let mut text = format!("{},{}", position.row + 1, position.column + 1);
483 if self.selected_count > 0 {
484 write!(text, " ({} selected)", self.selected_count).unwrap();
485 }
486 Label::new(text, theme.cursor_position.clone()).boxed()
487 } else {
488 Empty::new().boxed()
489 }
490 }
491}
492
493impl StatusItemView for CursorPosition {
494 fn set_active_pane_item(
495 &mut self,
496 active_pane_item: Option<&dyn ItemHandle>,
497 cx: &mut ViewContext<Self>,
498 ) {
499 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
500 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
501 self.update_position(editor, cx);
502 } else {
503 self.position = None;
504 self._observe_active_editor = None;
505 }
506
507 cx.notify();
508 }
509}
510
511pub struct DiagnosticMessage {
512 diagnostic: Option<Diagnostic>,
513 _observe_active_editor: Option<Subscription>,
514}
515
516impl DiagnosticMessage {
517 pub fn new() -> Self {
518 Self {
519 diagnostic: None,
520 _observe_active_editor: None,
521 }
522 }
523
524 fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
525 let editor = editor.read(cx);
526 let buffer = editor.buffer().read(cx);
527 let cursor_position = editor
528 .newest_selection_with_snapshot::<usize>(&buffer.read(cx))
529 .head();
530 let new_diagnostic = buffer
531 .read(cx)
532 .diagnostics_in_range::<_, usize>(cursor_position..cursor_position, false)
533 .filter(|entry| !entry.range.is_empty())
534 .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
535 .map(|entry| entry.diagnostic);
536 if new_diagnostic != self.diagnostic {
537 self.diagnostic = new_diagnostic;
538 cx.notify();
539 }
540 }
541}
542
543impl Entity for DiagnosticMessage {
544 type Event = ();
545}
546
547impl View for DiagnosticMessage {
548 fn ui_name() -> &'static str {
549 "DiagnosticMessage"
550 }
551
552 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
553 if let Some(diagnostic) = &self.diagnostic {
554 let theme = &cx.global::<Settings>().theme.workspace.status_bar;
555 Label::new(
556 diagnostic.message.split('\n').next().unwrap().to_string(),
557 theme.diagnostic_message.clone(),
558 )
559 .boxed()
560 } else {
561 Empty::new().boxed()
562 }
563 }
564}
565
566impl StatusItemView for DiagnosticMessage {
567 fn set_active_pane_item(
568 &mut self,
569 active_pane_item: Option<&dyn ItemHandle>,
570 cx: &mut ViewContext<Self>,
571 ) {
572 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
573 self._observe_active_editor = Some(cx.observe(&editor, Self::update));
574 self.update(editor, cx);
575 } else {
576 self.diagnostic = Default::default();
577 self._observe_active_editor = None;
578 }
579 cx.notify();
580 }
581}