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(selections.into(), None, false, 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 if let Some(anchor) = message.scroll_top_anchor {
170 self.set_scroll_top_anchor(
171 Anchor {
172 buffer_id: Some(buffer_id),
173 excerpt_id: excerpt_id.clone(),
174 text_anchor: language::proto::deserialize_anchor(anchor)
175 .ok_or_else(|| anyhow!("invalid scroll top"))?,
176 },
177 vec2f(message.scroll_x, message.scroll_y),
178 cx,
179 );
180 }
181
182 let selections = message
183 .selections
184 .into_iter()
185 .filter_map(|selection| {
186 deserialize_selection(&excerpt_id, buffer_id, selection)
187 })
188 .collect::<Vec<_>>();
189 if !selections.is_empty() {
190 self.set_selections(selections.into(), None, false, cx);
191 }
192 }
193 }
194 Ok(())
195 }
196
197 fn should_unfollow_on_event(event: &Self::Event, _: &AppContext) -> bool {
198 match event {
199 Event::Edited { local } => *local,
200 Event::SelectionsChanged { local } => *local,
201 Event::ScrollPositionChanged { local } => *local,
202 _ => false,
203 }
204 }
205}
206
207fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
208 proto::Selection {
209 id: selection.id as u64,
210 start: Some(language::proto::serialize_anchor(
211 &selection.start.text_anchor,
212 )),
213 end: Some(language::proto::serialize_anchor(
214 &selection.end.text_anchor,
215 )),
216 reversed: selection.reversed,
217 }
218}
219
220fn deserialize_selection(
221 excerpt_id: &ExcerptId,
222 buffer_id: usize,
223 selection: proto::Selection,
224) -> Option<Selection<Anchor>> {
225 Some(Selection {
226 id: selection.id as usize,
227 start: Anchor {
228 buffer_id: Some(buffer_id),
229 excerpt_id: excerpt_id.clone(),
230 text_anchor: language::proto::deserialize_anchor(selection.start?)?,
231 },
232 end: Anchor {
233 buffer_id: Some(buffer_id),
234 excerpt_id: excerpt_id.clone(),
235 text_anchor: language::proto::deserialize_anchor(selection.end?)?,
236 },
237 reversed: selection.reversed,
238 goal: SelectionGoal::None,
239 })
240}
241
242impl Item for Editor {
243 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) {
244 if let Some(data) = data.downcast_ref::<NavigationData>() {
245 let buffer = self.buffer.read(cx).read(cx);
246 let offset = if buffer.can_resolve(&data.anchor) {
247 data.anchor.to_offset(&buffer)
248 } else {
249 buffer.clip_offset(data.offset, Bias::Left)
250 };
251
252 drop(buffer);
253 let nav_history = self.nav_history.take();
254 self.select_ranges([offset..offset], Some(Autoscroll::Fit), cx);
255 self.nav_history = nav_history;
256 }
257 }
258
259 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
260 let title = self.title(cx);
261 Label::new(title, style.label.clone()).boxed()
262 }
263
264 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
265 File::from_dyn(self.buffer().read(cx).file(cx)).map(|file| ProjectPath {
266 worktree_id: file.worktree_id(cx),
267 path: file.path().clone(),
268 })
269 }
270
271 fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
272 File::from_dyn(self.buffer().read(cx).file(cx)).and_then(|file| file.project_entry_id(cx))
273 }
274
275 fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
276 where
277 Self: Sized,
278 {
279 Some(self.clone(cx))
280 }
281
282 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
283 self.nav_history = Some(history);
284 }
285
286 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
287 let selection = self.newest_anchor_selection();
288 self.push_to_nav_history(selection.head(), None, cx);
289 }
290
291 fn is_dirty(&self, cx: &AppContext) -> bool {
292 self.buffer().read(cx).read(cx).is_dirty()
293 }
294
295 fn has_conflict(&self, cx: &AppContext) -> bool {
296 self.buffer().read(cx).read(cx).has_conflict()
297 }
298
299 fn can_save(&self, cx: &AppContext) -> bool {
300 !self.buffer().read(cx).is_singleton() || self.project_path(cx).is_some()
301 }
302
303 fn save(
304 &mut self,
305 project: ModelHandle<Project>,
306 cx: &mut ViewContext<Self>,
307 ) -> Task<Result<()>> {
308 let buffer = self.buffer().clone();
309 let buffers = buffer.read(cx).all_buffers();
310 let transaction = project.update(cx, |project, cx| project.format(buffers, true, cx));
311 cx.spawn(|this, mut cx| async move {
312 let transaction = transaction.await.log_err();
313 this.update(&mut cx, |editor, cx| {
314 editor.request_autoscroll(Autoscroll::Fit, cx)
315 });
316 buffer
317 .update(&mut cx, |buffer, cx| {
318 if let Some(transaction) = transaction {
319 if !buffer.is_singleton() {
320 buffer.push_transaction(&transaction.0);
321 }
322 }
323
324 buffer.save(cx)
325 })
326 .await?;
327 Ok(())
328 })
329 }
330
331 fn can_save_as(&self, cx: &AppContext) -> bool {
332 self.buffer().read(cx).is_singleton()
333 }
334
335 fn save_as(
336 &mut self,
337 project: ModelHandle<Project>,
338 abs_path: PathBuf,
339 cx: &mut ViewContext<Self>,
340 ) -> Task<Result<()>> {
341 let buffer = self
342 .buffer()
343 .read(cx)
344 .as_singleton()
345 .expect("cannot call save_as on an excerpt list")
346 .clone();
347
348 project.update(cx, |project, cx| {
349 project.save_buffer_as(buffer, abs_path, cx)
350 })
351 }
352
353 fn should_activate_item_on_event(event: &Event) -> bool {
354 matches!(event, Event::Activate)
355 }
356
357 fn should_close_item_on_event(event: &Event) -> bool {
358 matches!(event, Event::Closed)
359 }
360
361 fn should_update_tab_on_event(event: &Event) -> bool {
362 matches!(event, Event::Saved | Event::Dirtied | Event::TitleChanged)
363 }
364}
365
366impl ProjectItem for Editor {
367 type Item = Buffer;
368
369 fn for_project_item(
370 project: ModelHandle<Project>,
371 buffer: ModelHandle<Buffer>,
372 cx: &mut ViewContext<Self>,
373 ) -> Self {
374 Self::for_buffer(buffer, Some(project), cx)
375 }
376}
377
378pub struct CursorPosition {
379 position: Option<Point>,
380 selected_count: usize,
381 _observe_active_editor: Option<Subscription>,
382}
383
384impl CursorPosition {
385 pub fn new() -> Self {
386 Self {
387 position: None,
388 selected_count: 0,
389 _observe_active_editor: None,
390 }
391 }
392
393 fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
394 let editor = editor.read(cx);
395 let buffer = editor.buffer().read(cx).snapshot(cx);
396
397 self.selected_count = 0;
398 let mut last_selection: Option<Selection<usize>> = None;
399 for selection in editor.local_selections::<usize>(cx) {
400 self.selected_count += selection.end - selection.start;
401 if last_selection
402 .as_ref()
403 .map_or(true, |last_selection| selection.id > last_selection.id)
404 {
405 last_selection = Some(selection);
406 }
407 }
408 self.position = last_selection.map(|s| s.head().to_point(&buffer));
409
410 cx.notify();
411 }
412}
413
414impl Entity for CursorPosition {
415 type Event = ();
416}
417
418impl View for CursorPosition {
419 fn ui_name() -> &'static str {
420 "CursorPosition"
421 }
422
423 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
424 if let Some(position) = self.position {
425 let theme = &cx.global::<Settings>().theme.workspace.status_bar;
426 let mut text = format!("{},{}", position.row + 1, position.column + 1);
427 if self.selected_count > 0 {
428 write!(text, " ({} selected)", self.selected_count).unwrap();
429 }
430 Label::new(text, theme.cursor_position.clone()).boxed()
431 } else {
432 Empty::new().boxed()
433 }
434 }
435}
436
437impl StatusItemView for CursorPosition {
438 fn set_active_pane_item(
439 &mut self,
440 active_pane_item: Option<&dyn ItemHandle>,
441 cx: &mut ViewContext<Self>,
442 ) {
443 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
444 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
445 self.update_position(editor, cx);
446 } else {
447 self.position = None;
448 self._observe_active_editor = None;
449 }
450
451 cx.notify();
452 }
453}
454
455pub struct DiagnosticMessage {
456 diagnostic: Option<Diagnostic>,
457 _observe_active_editor: Option<Subscription>,
458}
459
460impl DiagnosticMessage {
461 pub fn new() -> Self {
462 Self {
463 diagnostic: None,
464 _observe_active_editor: None,
465 }
466 }
467
468 fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
469 let editor = editor.read(cx);
470 let buffer = editor.buffer().read(cx);
471 let cursor_position = editor
472 .newest_selection_with_snapshot::<usize>(&buffer.read(cx))
473 .head();
474 let new_diagnostic = buffer
475 .read(cx)
476 .diagnostics_in_range::<_, usize>(cursor_position..cursor_position, false)
477 .filter(|entry| !entry.range.is_empty())
478 .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
479 .map(|entry| entry.diagnostic);
480 if new_diagnostic != self.diagnostic {
481 self.diagnostic = new_diagnostic;
482 cx.notify();
483 }
484 }
485}
486
487impl Entity for DiagnosticMessage {
488 type Event = ();
489}
490
491impl View for DiagnosticMessage {
492 fn ui_name() -> &'static str {
493 "DiagnosticMessage"
494 }
495
496 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
497 if let Some(diagnostic) = &self.diagnostic {
498 let theme = &cx.global::<Settings>().theme.workspace.status_bar;
499 Label::new(
500 diagnostic.message.split('\n').next().unwrap().to_string(),
501 theme.diagnostic_message.clone(),
502 )
503 .boxed()
504 } else {
505 Empty::new().boxed()
506 }
507 }
508}
509
510impl StatusItemView for DiagnosticMessage {
511 fn set_active_pane_item(
512 &mut self,
513 active_pane_item: Option<&dyn ItemHandle>,
514 cx: &mut ViewContext<Self>,
515 ) {
516 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
517 self._observe_active_editor = Some(cx.observe(&editor, Self::update));
518 self.update(editor, cx);
519 } else {
520 self.diagnostic = Default::default();
521 self._observe_active_editor = None;
522 }
523 cx.notify();
524 }
525}