1use crate::{
2 Anchor, Autoscroll, Editor, Event, ExcerptId, MultiBuffer, NavigationData, ToPoint as _,
3};
4use anyhow::{anyhow, Result};
5use futures::FutureExt;
6use gpui::{
7 elements::*, geometry::vector::vec2f, AppContext, Entity, ModelHandle, MutableAppContext,
8 RenderContext, Subscription, Task, View, ViewContext, ViewHandle,
9};
10use language::{Bias, Buffer, File as _, SelectionGoal};
11use project::{File, Project, ProjectEntryId, ProjectPath};
12use rpc::proto::{self, update_view};
13use settings::Settings;
14use smallvec::SmallVec;
15use std::{
16 borrow::Cow,
17 fmt::Write,
18 path::{Path, PathBuf},
19 time::Duration,
20};
21use text::{Point, Selection};
22use util::TryFutureExt;
23use workspace::{FollowableItem, Item, ItemHandle, ItemNavHistory, ProjectItem, StatusItemView};
24
25pub const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
26pub const MAX_TAB_TITLE_LEN: usize = 24;
27
28impl FollowableItem for Editor {
29 fn from_state_proto(
30 pane: ViewHandle<workspace::Pane>,
31 project: ModelHandle<Project>,
32 state: &mut Option<proto::view::Variant>,
33 cx: &mut MutableAppContext,
34 ) -> Option<Task<Result<ViewHandle<Self>>>> {
35 let state = if matches!(state, Some(proto::view::Variant::Editor(_))) {
36 if let Some(proto::view::Variant::Editor(state)) = state.take() {
37 state
38 } else {
39 unreachable!()
40 }
41 } else {
42 return None;
43 };
44
45 let buffer = project.update(cx, |project, cx| {
46 project.open_buffer_by_id(state.buffer_id, cx)
47 });
48 Some(cx.spawn(|mut cx| async move {
49 let buffer = buffer.await?;
50 let editor = pane
51 .read_with(&cx, |pane, cx| {
52 pane.items_of_type::<Self>().find(|editor| {
53 editor.read(cx).buffer.read(cx).as_singleton().as_ref() == Some(&buffer)
54 })
55 })
56 .unwrap_or_else(|| {
57 pane.update(&mut cx, |_, cx| {
58 cx.add_view(|cx| Editor::for_buffer(buffer, Some(project), cx))
59 })
60 });
61 editor.update(&mut cx, |editor, cx| {
62 let excerpt_id;
63 let buffer_id;
64 {
65 let buffer = editor.buffer.read(cx).read(cx);
66 let singleton = buffer.as_singleton().unwrap();
67 excerpt_id = singleton.0.clone();
68 buffer_id = singleton.1;
69 }
70 let selections = state
71 .selections
72 .into_iter()
73 .map(|selection| {
74 deserialize_selection(&excerpt_id, buffer_id, selection)
75 .ok_or_else(|| anyhow!("invalid selection"))
76 })
77 .collect::<Result<Vec<_>>>()?;
78 if !selections.is_empty() {
79 editor.set_selections_from_remote(selections, cx);
80 }
81
82 if let Some(anchor) = state.scroll_top_anchor {
83 editor.set_scroll_top_anchor(
84 Anchor {
85 buffer_id: Some(state.buffer_id as usize),
86 excerpt_id,
87 text_anchor: language::proto::deserialize_anchor(anchor)
88 .ok_or_else(|| anyhow!("invalid scroll top"))?,
89 },
90 vec2f(state.scroll_x, state.scroll_y),
91 cx,
92 );
93 }
94
95 Ok::<_, anyhow::Error>(())
96 })?;
97 Ok(editor)
98 }))
99 }
100
101 fn set_leader_replica_id(
102 &mut self,
103 leader_replica_id: Option<u16>,
104 cx: &mut ViewContext<Self>,
105 ) {
106 self.leader_replica_id = leader_replica_id;
107 if self.leader_replica_id.is_some() {
108 self.buffer.update(cx, |buffer, cx| {
109 buffer.remove_active_selections(cx);
110 });
111 } else {
112 self.buffer.update(cx, |buffer, cx| {
113 if self.focused {
114 buffer.set_active_selections(
115 &self.selections.disjoint_anchors(),
116 self.selections.line_mode,
117 cx,
118 );
119 }
120 });
121 }
122 cx.notify();
123 }
124
125 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
126 let buffer_id = self.buffer.read(cx).as_singleton()?.read(cx).remote_id();
127 Some(proto::view::Variant::Editor(proto::view::Editor {
128 buffer_id,
129 scroll_top_anchor: Some(language::proto::serialize_anchor(
130 &self.scroll_top_anchor.text_anchor,
131 )),
132 scroll_x: self.scroll_position.x(),
133 scroll_y: self.scroll_position.y(),
134 selections: self
135 .selections
136 .disjoint_anchors()
137 .iter()
138 .map(serialize_selection)
139 .collect(),
140 }))
141 }
142
143 fn add_event_to_update_proto(
144 &self,
145 event: &Self::Event,
146 update: &mut Option<proto::update_view::Variant>,
147 _: &AppContext,
148 ) -> bool {
149 let update =
150 update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
151
152 match update {
153 proto::update_view::Variant::Editor(update) => match event {
154 Event::ScrollPositionChanged { .. } => {
155 update.scroll_top_anchor = Some(language::proto::serialize_anchor(
156 &self.scroll_top_anchor.text_anchor,
157 ));
158 update.scroll_x = self.scroll_position.x();
159 update.scroll_y = self.scroll_position.y();
160 true
161 }
162 Event::SelectionsChanged { .. } => {
163 update.selections = self
164 .selections
165 .disjoint_anchors()
166 .iter()
167 .chain(self.selections.pending_anchor().as_ref())
168 .map(serialize_selection)
169 .collect();
170 true
171 }
172 _ => false,
173 },
174 }
175 }
176
177 fn apply_update_proto(
178 &mut self,
179 message: update_view::Variant,
180 cx: &mut ViewContext<Self>,
181 ) -> Result<()> {
182 match message {
183 update_view::Variant::Editor(message) => {
184 let buffer = self.buffer.read(cx);
185 let buffer = buffer.read(cx);
186 let (excerpt_id, buffer_id, _) = buffer.as_singleton().unwrap();
187 let excerpt_id = excerpt_id.clone();
188 drop(buffer);
189
190 let selections = message
191 .selections
192 .into_iter()
193 .filter_map(|selection| {
194 deserialize_selection(&excerpt_id, buffer_id, selection)
195 })
196 .collect::<Vec<_>>();
197
198 if !selections.is_empty() {
199 self.set_selections_from_remote(selections, cx);
200 self.request_autoscroll_remotely(Autoscroll::Newest, cx);
201 } else if let Some(anchor) = message.scroll_top_anchor {
202 self.set_scroll_top_anchor(
203 Anchor {
204 buffer_id: Some(buffer_id),
205 excerpt_id,
206 text_anchor: language::proto::deserialize_anchor(anchor)
207 .ok_or_else(|| anyhow!("invalid scroll top"))?,
208 },
209 vec2f(message.scroll_x, message.scroll_y),
210 cx,
211 );
212 }
213 }
214 }
215 Ok(())
216 }
217
218 fn should_unfollow_on_event(event: &Self::Event, _: &AppContext) -> bool {
219 match event {
220 Event::Edited => true,
221 Event::SelectionsChanged { local } => *local,
222 Event::ScrollPositionChanged { local } => *local,
223 _ => false,
224 }
225 }
226}
227
228fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
229 proto::Selection {
230 id: selection.id as u64,
231 start: Some(language::proto::serialize_anchor(
232 &selection.start.text_anchor,
233 )),
234 end: Some(language::proto::serialize_anchor(
235 &selection.end.text_anchor,
236 )),
237 reversed: selection.reversed,
238 }
239}
240
241fn deserialize_selection(
242 excerpt_id: &ExcerptId,
243 buffer_id: usize,
244 selection: proto::Selection,
245) -> Option<Selection<Anchor>> {
246 Some(Selection {
247 id: selection.id as usize,
248 start: Anchor {
249 buffer_id: Some(buffer_id),
250 excerpt_id: excerpt_id.clone(),
251 text_anchor: language::proto::deserialize_anchor(selection.start?)?,
252 },
253 end: Anchor {
254 buffer_id: Some(buffer_id),
255 excerpt_id: excerpt_id.clone(),
256 text_anchor: language::proto::deserialize_anchor(selection.end?)?,
257 },
258 reversed: selection.reversed,
259 goal: SelectionGoal::None,
260 })
261}
262
263impl Item for Editor {
264 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
265 if let Ok(data) = data.downcast::<NavigationData>() {
266 let newest_selection = self.selections.newest::<Point>(cx);
267 let buffer = self.buffer.read(cx).read(cx);
268 let offset = if buffer.can_resolve(&data.cursor_anchor) {
269 data.cursor_anchor.to_point(&buffer)
270 } else {
271 buffer.clip_point(data.cursor_position, Bias::Left)
272 };
273
274 let scroll_top_anchor = if buffer.can_resolve(&data.scroll_top_anchor) {
275 data.scroll_top_anchor
276 } else {
277 buffer.anchor_before(
278 buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
279 )
280 };
281
282 drop(buffer);
283
284 if newest_selection.head() == offset {
285 false
286 } else {
287 let nav_history = self.nav_history.take();
288 self.scroll_position = data.scroll_position;
289 self.scroll_top_anchor = scroll_top_anchor;
290 self.change_selections(Some(Autoscroll::Fit), cx, |s| {
291 s.select_ranges([offset..offset])
292 });
293 self.nav_history = nav_history;
294 true
295 }
296 } else {
297 false
298 }
299 }
300
301 fn tab_description<'a>(&'a self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>> {
302 match path_for_buffer(&self.buffer, detail, true, cx)? {
303 Cow::Borrowed(path) => Some(path.to_string_lossy()),
304 Cow::Owned(path) => Some(path.to_string_lossy().to_string().into()),
305 }
306 }
307
308 fn tab_content(
309 &self,
310 detail: Option<usize>,
311 style: &theme::Tab,
312 cx: &AppContext,
313 ) -> ElementBox {
314 Flex::row()
315 .with_child(
316 Label::new(self.title(cx).into(), style.label.clone())
317 .aligned()
318 .boxed(),
319 )
320 .with_children(detail.and_then(|detail| {
321 let path = path_for_buffer(&self.buffer, detail, false, cx)?;
322 let description = path.to_string_lossy();
323 Some(
324 Label::new(
325 if description.len() > MAX_TAB_TITLE_LEN {
326 description[..MAX_TAB_TITLE_LEN].to_string() + "…"
327 } else {
328 description.into()
329 },
330 style.description.text.clone(),
331 )
332 .contained()
333 .with_style(style.description.container)
334 .aligned()
335 .boxed(),
336 )
337 }))
338 .boxed()
339 }
340
341 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
342 let buffer = self.buffer.read(cx).as_singleton()?;
343 let file = buffer.read(cx).file();
344 File::from_dyn(file).map(|file| ProjectPath {
345 worktree_id: file.worktree_id(cx),
346 path: file.path().clone(),
347 })
348 }
349
350 fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
351 self.buffer
352 .read(cx)
353 .files(cx)
354 .into_iter()
355 .filter_map(|file| File::from_dyn(Some(file))?.project_entry_id(cx))
356 .collect()
357 }
358
359 fn is_singleton(&self, cx: &AppContext) -> bool {
360 self.buffer.read(cx).is_singleton()
361 }
362
363 fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
364 where
365 Self: Sized,
366 {
367 Some(self.clone(cx))
368 }
369
370 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
371 self.nav_history = Some(history);
372 }
373
374 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
375 let selection = self.selections.newest_anchor();
376 self.push_to_nav_history(selection.head(), None, cx);
377 }
378
379 fn is_dirty(&self, cx: &AppContext) -> bool {
380 self.buffer().read(cx).read(cx).is_dirty()
381 }
382
383 fn has_conflict(&self, cx: &AppContext) -> bool {
384 self.buffer().read(cx).read(cx).has_conflict()
385 }
386
387 fn can_save(&self, cx: &AppContext) -> bool {
388 !self.buffer().read(cx).is_singleton() || self.project_path(cx).is_some()
389 }
390
391 fn save(
392 &mut self,
393 project: ModelHandle<Project>,
394 cx: &mut ViewContext<Self>,
395 ) -> Task<Result<()>> {
396 let buffer = self.buffer().clone();
397 let buffers = buffer.read(cx).all_buffers();
398 let mut timeout = cx.background().timer(FORMAT_TIMEOUT).fuse();
399 let format = project.update(cx, |project, cx| project.format(buffers, true, cx));
400 cx.spawn(|_, mut cx| async move {
401 let transaction = futures::select_biased! {
402 _ = timeout => {
403 log::warn!("timed out waiting for formatting");
404 None
405 }
406 transaction = format.log_err().fuse() => transaction,
407 };
408
409 buffer
410 .update(&mut cx, |buffer, cx| {
411 if let Some(transaction) = transaction {
412 if !buffer.is_singleton() {
413 buffer.push_transaction(&transaction.0);
414 }
415 }
416
417 buffer.save(cx)
418 })
419 .await?;
420 Ok(())
421 })
422 }
423
424 fn save_as(
425 &mut self,
426 project: ModelHandle<Project>,
427 abs_path: PathBuf,
428 cx: &mut ViewContext<Self>,
429 ) -> Task<Result<()>> {
430 let buffer = self
431 .buffer()
432 .read(cx)
433 .as_singleton()
434 .expect("cannot call save_as on an excerpt list");
435
436 project.update(cx, |project, cx| {
437 project.save_buffer_as(buffer, abs_path, cx)
438 })
439 }
440
441 fn reload(
442 &mut self,
443 project: ModelHandle<Project>,
444 cx: &mut ViewContext<Self>,
445 ) -> Task<Result<()>> {
446 let buffer = self.buffer().clone();
447 let buffers = self.buffer.read(cx).all_buffers();
448 let reload_buffers =
449 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
450 cx.spawn(|this, mut cx| async move {
451 let transaction = reload_buffers.log_err().await;
452 this.update(&mut cx, |editor, cx| {
453 editor.request_autoscroll(Autoscroll::Fit, cx)
454 });
455 buffer.update(&mut cx, |buffer, _| {
456 if let Some(transaction) = transaction {
457 if !buffer.is_singleton() {
458 buffer.push_transaction(&transaction.0);
459 }
460 }
461 });
462 Ok(())
463 })
464 }
465
466 fn should_close_item_on_event(event: &Event) -> bool {
467 matches!(event, Event::Closed)
468 }
469
470 fn should_update_tab_on_event(event: &Event) -> bool {
471 matches!(
472 event,
473 Event::Saved | Event::DirtyChanged | Event::TitleChanged
474 )
475 }
476
477 fn is_edit_event(event: &Self::Event) -> bool {
478 matches!(event, Event::BufferEdited)
479 }
480}
481
482impl ProjectItem for Editor {
483 type Item = Buffer;
484
485 fn for_project_item(
486 project: ModelHandle<Project>,
487 buffer: ModelHandle<Buffer>,
488 cx: &mut ViewContext<Self>,
489 ) -> Self {
490 Self::for_buffer(buffer, Some(project), cx)
491 }
492}
493
494pub struct CursorPosition {
495 position: Option<Point>,
496 selected_count: usize,
497 _observe_active_editor: Option<Subscription>,
498}
499
500impl Default for CursorPosition {
501 fn default() -> Self {
502 Self::new()
503 }
504}
505
506impl CursorPosition {
507 pub fn new() -> Self {
508 Self {
509 position: None,
510 selected_count: 0,
511 _observe_active_editor: None,
512 }
513 }
514
515 fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
516 let editor = editor.read(cx);
517 let buffer = editor.buffer().read(cx).snapshot(cx);
518
519 self.selected_count = 0;
520 let mut last_selection: Option<Selection<usize>> = None;
521 for selection in editor.selections.all::<usize>(cx) {
522 self.selected_count += selection.end - selection.start;
523 if last_selection
524 .as_ref()
525 .map_or(true, |last_selection| selection.id > last_selection.id)
526 {
527 last_selection = Some(selection);
528 }
529 }
530 self.position = last_selection.map(|s| s.head().to_point(&buffer));
531
532 cx.notify();
533 }
534}
535
536impl Entity for CursorPosition {
537 type Event = ();
538}
539
540impl View for CursorPosition {
541 fn ui_name() -> &'static str {
542 "CursorPosition"
543 }
544
545 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
546 if let Some(position) = self.position {
547 let theme = &cx.global::<Settings>().theme.workspace.status_bar;
548 let mut text = format!("{},{}", position.row + 1, position.column + 1);
549 if self.selected_count > 0 {
550 write!(text, " ({} selected)", self.selected_count).unwrap();
551 }
552 Label::new(text, theme.cursor_position.clone()).boxed()
553 } else {
554 Empty::new().boxed()
555 }
556 }
557}
558
559impl StatusItemView for CursorPosition {
560 fn set_active_pane_item(
561 &mut self,
562 active_pane_item: Option<&dyn ItemHandle>,
563 cx: &mut ViewContext<Self>,
564 ) {
565 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
566 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
567 self.update_position(editor, cx);
568 } else {
569 self.position = None;
570 self._observe_active_editor = None;
571 }
572
573 cx.notify();
574 }
575}
576
577fn path_for_buffer<'a>(
578 buffer: &ModelHandle<MultiBuffer>,
579 mut height: usize,
580 include_filename: bool,
581 cx: &'a AppContext,
582) -> Option<Cow<'a, Path>> {
583 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
584 // Ensure we always render at least the filename.
585 height += 1;
586
587 let mut prefix = file.path().as_ref();
588 while height > 0 {
589 if let Some(parent) = prefix.parent() {
590 prefix = parent;
591 height -= 1;
592 } else {
593 break;
594 }
595 }
596
597 // Here we could have just always used `full_path`, but that is very
598 // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
599 // traversed all the way up to the worktree's root.
600 if height > 0 {
601 let full_path = file.full_path(cx);
602 if include_filename {
603 Some(full_path.into())
604 } else {
605 Some(full_path.parent().unwrap().to_path_buf().into())
606 }
607 } else {
608 let mut path = file.path().strip_prefix(prefix).unwrap();
609 if !include_filename {
610 path = path.parent().unwrap();
611 }
612 Some(path.into())
613 }
614}