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