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>) -> bool {
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 let newest_selection = self.newest_selection_with_snapshot::<usize>(&buffer);
253 drop(buffer);
254
255 if newest_selection.head() == offset {
256 false
257 } else {
258 let nav_history = self.nav_history.take();
259 self.select_ranges([offset..offset], Some(Autoscroll::Fit), cx);
260 self.nav_history = nav_history;
261 true
262 }
263 } else {
264 false
265 }
266 }
267
268 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
269 let title = self.title(cx);
270 Label::new(title, style.label.clone()).boxed()
271 }
272
273 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
274 File::from_dyn(self.buffer().read(cx).file(cx)).map(|file| ProjectPath {
275 worktree_id: file.worktree_id(cx),
276 path: file.path().clone(),
277 })
278 }
279
280 fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
281 File::from_dyn(self.buffer().read(cx).file(cx)).and_then(|file| file.project_entry_id(cx))
282 }
283
284 fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
285 where
286 Self: Sized,
287 {
288 Some(self.clone(cx))
289 }
290
291 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
292 self.nav_history = Some(history);
293 }
294
295 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
296 let selection = self.newest_anchor_selection();
297 self.push_to_nav_history(selection.head(), None, cx);
298 }
299
300 fn is_dirty(&self, cx: &AppContext) -> bool {
301 self.buffer().read(cx).read(cx).is_dirty()
302 }
303
304 fn has_conflict(&self, cx: &AppContext) -> bool {
305 self.buffer().read(cx).read(cx).has_conflict()
306 }
307
308 fn can_save(&self, cx: &AppContext) -> bool {
309 !self.buffer().read(cx).is_singleton() || self.project_path(cx).is_some()
310 }
311
312 fn save(
313 &mut self,
314 project: ModelHandle<Project>,
315 cx: &mut ViewContext<Self>,
316 ) -> Task<Result<()>> {
317 let buffer = self.buffer().clone();
318 let buffers = buffer.read(cx).all_buffers();
319 let transaction = project.update(cx, |project, cx| project.format(buffers, true, cx));
320 cx.spawn(|this, mut cx| async move {
321 let transaction = transaction.await.log_err();
322 this.update(&mut cx, |editor, cx| {
323 editor.request_autoscroll(Autoscroll::Fit, cx)
324 });
325 buffer
326 .update(&mut cx, |buffer, cx| {
327 if let Some(transaction) = transaction {
328 if !buffer.is_singleton() {
329 buffer.push_transaction(&transaction.0);
330 }
331 }
332
333 buffer.save(cx)
334 })
335 .await?;
336 Ok(())
337 })
338 }
339
340 fn can_save_as(&self, cx: &AppContext) -> bool {
341 self.buffer().read(cx).is_singleton()
342 }
343
344 fn save_as(
345 &mut self,
346 project: ModelHandle<Project>,
347 abs_path: PathBuf,
348 cx: &mut ViewContext<Self>,
349 ) -> Task<Result<()>> {
350 let buffer = self
351 .buffer()
352 .read(cx)
353 .as_singleton()
354 .expect("cannot call save_as on an excerpt list")
355 .clone();
356
357 project.update(cx, |project, cx| {
358 project.save_buffer_as(buffer, abs_path, cx)
359 })
360 }
361
362 fn should_activate_item_on_event(event: &Event) -> bool {
363 matches!(event, Event::Activate)
364 }
365
366 fn should_close_item_on_event(event: &Event) -> bool {
367 matches!(event, Event::Closed)
368 }
369
370 fn should_update_tab_on_event(event: &Event) -> bool {
371 matches!(event, Event::Saved | Event::Dirtied | Event::TitleChanged)
372 }
373}
374
375impl ProjectItem for Editor {
376 type Item = Buffer;
377
378 fn for_project_item(
379 project: ModelHandle<Project>,
380 buffer: ModelHandle<Buffer>,
381 cx: &mut ViewContext<Self>,
382 ) -> Self {
383 Self::for_buffer(buffer, Some(project), cx)
384 }
385}
386
387pub struct CursorPosition {
388 position: Option<Point>,
389 selected_count: usize,
390 _observe_active_editor: Option<Subscription>,
391}
392
393impl CursorPosition {
394 pub fn new() -> Self {
395 Self {
396 position: None,
397 selected_count: 0,
398 _observe_active_editor: None,
399 }
400 }
401
402 fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
403 let editor = editor.read(cx);
404 let buffer = editor.buffer().read(cx).snapshot(cx);
405
406 self.selected_count = 0;
407 let mut last_selection: Option<Selection<usize>> = None;
408 for selection in editor.local_selections::<usize>(cx) {
409 self.selected_count += selection.end - selection.start;
410 if last_selection
411 .as_ref()
412 .map_or(true, |last_selection| selection.id > last_selection.id)
413 {
414 last_selection = Some(selection);
415 }
416 }
417 self.position = last_selection.map(|s| s.head().to_point(&buffer));
418
419 cx.notify();
420 }
421}
422
423impl Entity for CursorPosition {
424 type Event = ();
425}
426
427impl View for CursorPosition {
428 fn ui_name() -> &'static str {
429 "CursorPosition"
430 }
431
432 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
433 if let Some(position) = self.position {
434 let theme = &cx.global::<Settings>().theme.workspace.status_bar;
435 let mut text = format!("{},{}", position.row + 1, position.column + 1);
436 if self.selected_count > 0 {
437 write!(text, " ({} selected)", self.selected_count).unwrap();
438 }
439 Label::new(text, theme.cursor_position.clone()).boxed()
440 } else {
441 Empty::new().boxed()
442 }
443 }
444}
445
446impl StatusItemView for CursorPosition {
447 fn set_active_pane_item(
448 &mut self,
449 active_pane_item: Option<&dyn ItemHandle>,
450 cx: &mut ViewContext<Self>,
451 ) {
452 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
453 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
454 self.update_position(editor, cx);
455 } else {
456 self.position = None;
457 self._observe_active_editor = None;
458 }
459
460 cx.notify();
461 }
462}
463
464pub struct DiagnosticMessage {
465 diagnostic: Option<Diagnostic>,
466 _observe_active_editor: Option<Subscription>,
467}
468
469impl DiagnosticMessage {
470 pub fn new() -> Self {
471 Self {
472 diagnostic: None,
473 _observe_active_editor: None,
474 }
475 }
476
477 fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
478 let editor = editor.read(cx);
479 let buffer = editor.buffer().read(cx);
480 let cursor_position = editor
481 .newest_selection_with_snapshot::<usize>(&buffer.read(cx))
482 .head();
483 let new_diagnostic = buffer
484 .read(cx)
485 .diagnostics_in_range::<_, usize>(cursor_position..cursor_position, false)
486 .filter(|entry| !entry.range.is_empty())
487 .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
488 .map(|entry| entry.diagnostic);
489 if new_diagnostic != self.diagnostic {
490 self.diagnostic = new_diagnostic;
491 cx.notify();
492 }
493 }
494}
495
496impl Entity for DiagnosticMessage {
497 type Event = ();
498}
499
500impl View for DiagnosticMessage {
501 fn ui_name() -> &'static str {
502 "DiagnosticMessage"
503 }
504
505 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
506 if let Some(diagnostic) = &self.diagnostic {
507 let theme = &cx.global::<Settings>().theme.workspace.status_bar;
508 Label::new(
509 diagnostic.message.split('\n').next().unwrap().to_string(),
510 theme.diagnostic_message.clone(),
511 )
512 .boxed()
513 } else {
514 Empty::new().boxed()
515 }
516 }
517}
518
519impl StatusItemView for DiagnosticMessage {
520 fn set_active_pane_item(
521 &mut self,
522 active_pane_item: Option<&dyn ItemHandle>,
523 cx: &mut ViewContext<Self>,
524 ) {
525 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
526 self._observe_active_editor = Some(cx.observe(&editor, Self::update));
527 self.update(editor, cx);
528 } else {
529 self.diagnostic = Default::default();
530 self._observe_active_editor = None;
531 }
532 cx.notify();
533 }
534}