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