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