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