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