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