1use crate::{
2 display_map::ToDisplayPoint, link_go_to_definition::hide_link_definition,
3 movement::surrounding_word, persistence::DB, scroll::ScrollAnchor, Anchor, Autoscroll, Editor,
4 Event, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, NavigationData, ToPoint as _,
5};
6use anyhow::{Context, Result};
7use collections::HashSet;
8use futures::future::try_join_all;
9use gpui::{
10 elements::*,
11 geometry::vector::{vec2f, Vector2F},
12 AppContext, AsyncAppContext, Entity, ModelHandle, Subscription, Task, View, ViewContext,
13 ViewHandle, WeakViewHandle,
14};
15use language::{
16 proto::serialize_anchor as serialize_text_anchor, Bias, Buffer, OffsetRangeExt, Point,
17 SelectionGoal,
18};
19use project::{FormatTrigger, Item as _, Project, ProjectPath};
20use rpc::proto::{self, update_view};
21use smallvec::SmallVec;
22use std::{
23 borrow::Cow,
24 cmp::{self, Ordering},
25 fmt::Write,
26 iter,
27 ops::Range,
28 path::{Path, PathBuf},
29};
30use text::Selection;
31use util::{
32 paths::{PathExt, FILE_ROW_COLUMN_DELIMITER},
33 ResultExt, TryFutureExt,
34};
35use workspace::item::{BreadcrumbText, FollowableItemHandle};
36use workspace::{
37 item::{FollowableItem, Item, ItemEvent, ItemHandle, ProjectItem},
38 searchable::{Direction, SearchEvent, SearchableItem, SearchableItemHandle},
39 ItemId, ItemNavHistory, Pane, StatusItemView, ToolbarItemLocation, ViewId, Workspace,
40 WorkspaceId,
41};
42
43pub const MAX_TAB_TITLE_LEN: usize = 24;
44
45impl FollowableItem for Editor {
46 fn remote_id(&self) -> Option<ViewId> {
47 self.remote_id
48 }
49
50 fn from_state_proto(
51 pane: ViewHandle<workspace::Pane>,
52 workspace: ViewHandle<Workspace>,
53 remote_id: ViewId,
54 state: &mut Option<proto::view::Variant>,
55 cx: &mut AppContext,
56 ) -> Option<Task<Result<ViewHandle<Self>>>> {
57 let project = workspace.read(cx).project().to_owned();
58 let Some(proto::view::Variant::Editor(_)) = state else { return None };
59 let Some(proto::view::Variant::Editor(state)) = state.take() else { unreachable!() };
60
61 let client = project.read(cx).client();
62 let replica_id = project.read(cx).replica_id();
63 let buffer_ids = state
64 .excerpts
65 .iter()
66 .map(|excerpt| excerpt.buffer_id)
67 .collect::<HashSet<_>>();
68 let buffers = project.update(cx, |project, cx| {
69 buffer_ids
70 .iter()
71 .map(|id| project.open_buffer_by_id(*id, cx))
72 .collect::<Vec<_>>()
73 });
74
75 let pane = pane.downgrade();
76 Some(cx.spawn(|mut cx| async move {
77 let mut buffers = futures::future::try_join_all(buffers).await?;
78 let editor = pane.read_with(&cx, |pane, cx| {
79 let mut editors = pane.items_of_type::<Self>();
80 editors.find(|editor| {
81 let ids_match = editor.remote_id(&client, cx) == Some(remote_id);
82 let singleton_buffer_matches = state.singleton
83 && buffers.first()
84 == editor.read(cx).buffer.read(cx).as_singleton().as_ref();
85 ids_match || singleton_buffer_matches
86 })
87 })?;
88
89 let editor = if let Some(editor) = editor {
90 editor
91 } else {
92 pane.update(&mut cx, |_, cx| {
93 let multibuffer = cx.add_model(|cx| {
94 let mut multibuffer;
95 if state.singleton && buffers.len() == 1 {
96 multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
97 } else {
98 multibuffer = MultiBuffer::new(replica_id);
99 let mut excerpts = state.excerpts.into_iter().peekable();
100 while let Some(excerpt) = excerpts.peek() {
101 let buffer_id = excerpt.buffer_id;
102 let buffer_excerpts = iter::from_fn(|| {
103 let excerpt = excerpts.peek()?;
104 (excerpt.buffer_id == buffer_id)
105 .then(|| excerpts.next().unwrap())
106 });
107 let buffer =
108 buffers.iter().find(|b| b.read(cx).remote_id() == buffer_id);
109 if let Some(buffer) = buffer {
110 multibuffer.push_excerpts(
111 buffer.clone(),
112 buffer_excerpts.filter_map(deserialize_excerpt_range),
113 cx,
114 );
115 }
116 }
117 };
118
119 if let Some(title) = &state.title {
120 multibuffer = multibuffer.with_title(title.clone())
121 }
122
123 multibuffer
124 });
125
126 cx.add_view(|cx| {
127 let mut editor =
128 Editor::for_multibuffer(multibuffer, Some(project.clone()), cx);
129 editor.remote_id = Some(remote_id);
130 editor
131 })
132 })?
133 };
134
135 update_editor_from_message(
136 editor.downgrade(),
137 project,
138 proto::update_view::Editor {
139 selections: state.selections,
140 pending_selection: state.pending_selection,
141 scroll_top_anchor: state.scroll_top_anchor,
142 scroll_x: state.scroll_x,
143 scroll_y: state.scroll_y,
144 ..Default::default()
145 },
146 &mut cx,
147 )
148 .await?;
149
150 Ok(editor)
151 }))
152 }
153
154 fn set_leader_replica_id(
155 &mut self,
156 leader_replica_id: Option<u16>,
157 cx: &mut ViewContext<Self>,
158 ) {
159 self.leader_replica_id = leader_replica_id;
160 if self.leader_replica_id.is_some() {
161 self.buffer.update(cx, |buffer, cx| {
162 buffer.remove_active_selections(cx);
163 });
164 } else {
165 self.buffer.update(cx, |buffer, cx| {
166 if self.focused {
167 buffer.set_active_selections(
168 &self.selections.disjoint_anchors(),
169 self.selections.line_mode,
170 self.cursor_shape,
171 cx,
172 );
173 }
174 });
175 }
176 cx.notify();
177 }
178
179 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
180 let buffer = self.buffer.read(cx);
181 let scroll_anchor = self.scroll_manager.anchor();
182 let excerpts = buffer
183 .read(cx)
184 .excerpts()
185 .map(|(id, buffer, range)| proto::Excerpt {
186 id: id.to_proto(),
187 buffer_id: buffer.remote_id(),
188 context_start: Some(serialize_text_anchor(&range.context.start)),
189 context_end: Some(serialize_text_anchor(&range.context.end)),
190 primary_start: range
191 .primary
192 .as_ref()
193 .map(|range| serialize_text_anchor(&range.start)),
194 primary_end: range
195 .primary
196 .as_ref()
197 .map(|range| serialize_text_anchor(&range.end)),
198 })
199 .collect();
200
201 Some(proto::view::Variant::Editor(proto::view::Editor {
202 singleton: buffer.is_singleton(),
203 title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
204 excerpts,
205 scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
206 scroll_x: scroll_anchor.offset.x(),
207 scroll_y: scroll_anchor.offset.y(),
208 selections: self
209 .selections
210 .disjoint_anchors()
211 .iter()
212 .map(serialize_selection)
213 .collect(),
214 pending_selection: self
215 .selections
216 .pending_anchor()
217 .as_ref()
218 .map(serialize_selection),
219 }))
220 }
221
222 fn add_event_to_update_proto(
223 &self,
224 event: &Self::Event,
225 update: &mut Option<proto::update_view::Variant>,
226 cx: &AppContext,
227 ) -> bool {
228 let update =
229 update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
230
231 match update {
232 proto::update_view::Variant::Editor(update) => match event {
233 Event::ExcerptsAdded {
234 buffer,
235 predecessor,
236 excerpts,
237 } => {
238 let buffer_id = buffer.read(cx).remote_id();
239 let mut excerpts = excerpts.iter();
240 if let Some((id, range)) = excerpts.next() {
241 update.inserted_excerpts.push(proto::ExcerptInsertion {
242 previous_excerpt_id: Some(predecessor.to_proto()),
243 excerpt: serialize_excerpt(buffer_id, id, range),
244 });
245 update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
246 proto::ExcerptInsertion {
247 previous_excerpt_id: None,
248 excerpt: serialize_excerpt(buffer_id, id, range),
249 }
250 }))
251 }
252 true
253 }
254 Event::ExcerptsRemoved { ids } => {
255 update
256 .deleted_excerpts
257 .extend(ids.iter().map(ExcerptId::to_proto));
258 true
259 }
260 Event::ScrollPositionChanged { .. } => {
261 let scroll_anchor = self.scroll_manager.anchor();
262 update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
263 update.scroll_x = scroll_anchor.offset.x();
264 update.scroll_y = scroll_anchor.offset.y();
265 true
266 }
267 Event::SelectionsChanged { .. } => {
268 update.selections = self
269 .selections
270 .disjoint_anchors()
271 .iter()
272 .map(serialize_selection)
273 .collect();
274 update.pending_selection = self
275 .selections
276 .pending_anchor()
277 .as_ref()
278 .map(serialize_selection);
279 true
280 }
281 _ => false,
282 },
283 }
284 }
285
286 fn apply_update_proto(
287 &mut self,
288 project: &ModelHandle<Project>,
289 message: update_view::Variant,
290 cx: &mut ViewContext<Self>,
291 ) -> Task<Result<()>> {
292 let update_view::Variant::Editor(message) = message;
293 let project = project.clone();
294 cx.spawn(|this, mut cx| async move {
295 update_editor_from_message(this, project, message, &mut cx).await
296 })
297 }
298
299 fn should_unfollow_on_event(event: &Self::Event, _: &AppContext) -> bool {
300 match event {
301 Event::Edited => true,
302 Event::SelectionsChanged { local } => *local,
303 Event::ScrollPositionChanged { local, .. } => *local,
304 _ => false,
305 }
306 }
307}
308
309async fn update_editor_from_message(
310 this: WeakViewHandle<Editor>,
311 project: ModelHandle<Project>,
312 message: proto::update_view::Editor,
313 cx: &mut AsyncAppContext,
314) -> Result<()> {
315 // Open all of the buffers of which excerpts were added to the editor.
316 let inserted_excerpt_buffer_ids = message
317 .inserted_excerpts
318 .iter()
319 .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
320 .collect::<HashSet<_>>();
321 let inserted_excerpt_buffers = project.update(cx, |project, cx| {
322 inserted_excerpt_buffer_ids
323 .into_iter()
324 .map(|id| project.open_buffer_by_id(id, cx))
325 .collect::<Vec<_>>()
326 });
327 let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
328
329 // Update the editor's excerpts.
330 this.update(cx, |editor, cx| {
331 editor.buffer.update(cx, |multibuffer, cx| {
332 let mut removed_excerpt_ids = message
333 .deleted_excerpts
334 .into_iter()
335 .map(ExcerptId::from_proto)
336 .collect::<Vec<_>>();
337 removed_excerpt_ids.sort_by({
338 let multibuffer = multibuffer.read(cx);
339 move |a, b| a.cmp(&b, &multibuffer)
340 });
341
342 let mut insertions = message.inserted_excerpts.into_iter().peekable();
343 while let Some(insertion) = insertions.next() {
344 let Some(excerpt) = insertion.excerpt else { continue };
345 let Some(previous_excerpt_id) = insertion.previous_excerpt_id else { continue };
346 let buffer_id = excerpt.buffer_id;
347 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else { continue };
348
349 let adjacent_excerpts = iter::from_fn(|| {
350 let insertion = insertions.peek()?;
351 if insertion.previous_excerpt_id.is_none()
352 && insertion.excerpt.as_ref()?.buffer_id == buffer_id
353 {
354 insertions.next()?.excerpt
355 } else {
356 None
357 }
358 });
359
360 multibuffer.insert_excerpts_with_ids_after(
361 ExcerptId::from_proto(previous_excerpt_id),
362 buffer,
363 [excerpt]
364 .into_iter()
365 .chain(adjacent_excerpts)
366 .filter_map(|excerpt| {
367 Some((
368 ExcerptId::from_proto(excerpt.id),
369 deserialize_excerpt_range(excerpt)?,
370 ))
371 }),
372 cx,
373 );
374 }
375
376 multibuffer.remove_excerpts(removed_excerpt_ids, cx);
377 });
378 })?;
379
380 // Deserialize the editor state.
381 let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {
382 let buffer = editor.buffer.read(cx).read(cx);
383 let selections = message
384 .selections
385 .into_iter()
386 .filter_map(|selection| deserialize_selection(&buffer, selection))
387 .collect::<Vec<_>>();
388 let pending_selection = message
389 .pending_selection
390 .and_then(|selection| deserialize_selection(&buffer, selection));
391 let scroll_top_anchor = message
392 .scroll_top_anchor
393 .and_then(|anchor| deserialize_anchor(&buffer, anchor));
394 anyhow::Ok((selections, pending_selection, scroll_top_anchor))
395 })??;
396
397 // Wait until the buffer has received all of the operations referenced by
398 // the editor's new state.
399 this.update(cx, |editor, cx| {
400 editor.buffer.update(cx, |buffer, cx| {
401 buffer.wait_for_anchors(
402 selections
403 .iter()
404 .chain(pending_selection.as_ref())
405 .flat_map(|selection| [selection.start, selection.end])
406 .chain(scroll_top_anchor),
407 cx,
408 )
409 })
410 })?
411 .await?;
412
413 // Update the editor's state.
414 this.update(cx, |editor, cx| {
415 if !selections.is_empty() || pending_selection.is_some() {
416 editor.set_selections_from_remote(selections, pending_selection, cx);
417 editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
418 } else if let Some(scroll_top_anchor) = scroll_top_anchor {
419 editor.set_scroll_anchor_remote(
420 ScrollAnchor {
421 anchor: scroll_top_anchor,
422 offset: vec2f(message.scroll_x, message.scroll_y),
423 },
424 cx,
425 );
426 }
427 })?;
428 Ok(())
429}
430
431fn serialize_excerpt(
432 buffer_id: u64,
433 id: &ExcerptId,
434 range: &ExcerptRange<language::Anchor>,
435) -> Option<proto::Excerpt> {
436 Some(proto::Excerpt {
437 id: id.to_proto(),
438 buffer_id,
439 context_start: Some(serialize_text_anchor(&range.context.start)),
440 context_end: Some(serialize_text_anchor(&range.context.end)),
441 primary_start: range
442 .primary
443 .as_ref()
444 .map(|r| serialize_text_anchor(&r.start)),
445 primary_end: range
446 .primary
447 .as_ref()
448 .map(|r| serialize_text_anchor(&r.end)),
449 })
450}
451
452fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
453 proto::Selection {
454 id: selection.id as u64,
455 start: Some(serialize_anchor(&selection.start)),
456 end: Some(serialize_anchor(&selection.end)),
457 reversed: selection.reversed,
458 }
459}
460
461fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
462 proto::EditorAnchor {
463 excerpt_id: anchor.excerpt_id.to_proto(),
464 anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
465 }
466}
467
468fn deserialize_excerpt_range(excerpt: proto::Excerpt) -> Option<ExcerptRange<language::Anchor>> {
469 let context = {
470 let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
471 let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
472 start..end
473 };
474 let primary = excerpt
475 .primary_start
476 .zip(excerpt.primary_end)
477 .and_then(|(start, end)| {
478 let start = language::proto::deserialize_anchor(start)?;
479 let end = language::proto::deserialize_anchor(end)?;
480 Some(start..end)
481 });
482 Some(ExcerptRange { context, primary })
483}
484
485fn deserialize_selection(
486 buffer: &MultiBufferSnapshot,
487 selection: proto::Selection,
488) -> Option<Selection<Anchor>> {
489 Some(Selection {
490 id: selection.id as usize,
491 start: deserialize_anchor(buffer, selection.start?)?,
492 end: deserialize_anchor(buffer, selection.end?)?,
493 reversed: selection.reversed,
494 goal: SelectionGoal::None,
495 })
496}
497
498fn deserialize_anchor(buffer: &MultiBufferSnapshot, anchor: proto::EditorAnchor) -> Option<Anchor> {
499 let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
500 Some(Anchor {
501 excerpt_id,
502 text_anchor: language::proto::deserialize_anchor(anchor.anchor?)?,
503 buffer_id: buffer.buffer_id_for_excerpt(excerpt_id),
504 })
505}
506
507impl Item for Editor {
508 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
509 if let Ok(data) = data.downcast::<NavigationData>() {
510 let newest_selection = self.selections.newest::<Point>(cx);
511 let buffer = self.buffer.read(cx).read(cx);
512 let offset = if buffer.can_resolve(&data.cursor_anchor) {
513 data.cursor_anchor.to_point(&buffer)
514 } else {
515 buffer.clip_point(data.cursor_position, Bias::Left)
516 };
517
518 let mut scroll_anchor = data.scroll_anchor;
519 if !buffer.can_resolve(&scroll_anchor.anchor) {
520 scroll_anchor.anchor = buffer.anchor_before(
521 buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
522 );
523 }
524
525 drop(buffer);
526
527 if newest_selection.head() == offset {
528 false
529 } else {
530 let nav_history = self.nav_history.take();
531 self.set_scroll_anchor(scroll_anchor, cx);
532 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
533 s.select_ranges([offset..offset])
534 });
535 self.nav_history = nav_history;
536 true
537 }
538 } else {
539 false
540 }
541 }
542
543 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<Cow<str>> {
544 let file_path = self
545 .buffer()
546 .read(cx)
547 .as_singleton()?
548 .read(cx)
549 .file()
550 .and_then(|f| f.as_local())?
551 .abs_path(cx);
552
553 let file_path = file_path.compact().to_string_lossy().to_string();
554
555 Some(file_path.into())
556 }
557
558 fn tab_description<'a>(&'a self, detail: usize, cx: &'a AppContext) -> Option<Cow<str>> {
559 match path_for_buffer(&self.buffer, detail, true, cx)? {
560 Cow::Borrowed(path) => Some(path.to_string_lossy()),
561 Cow::Owned(path) => Some(path.to_string_lossy().to_string().into()),
562 }
563 }
564
565 fn tab_content<T: 'static>(
566 &self,
567 detail: Option<usize>,
568 style: &theme::Tab,
569 cx: &AppContext,
570 ) -> AnyElement<T> {
571 Flex::row()
572 .with_child(Label::new(self.title(cx).to_string(), style.label.clone()).into_any())
573 .with_children(detail.and_then(|detail| {
574 let path = path_for_buffer(&self.buffer, detail, false, cx)?;
575 let description = path.to_string_lossy();
576 Some(
577 Label::new(
578 util::truncate_and_trailoff(&description, MAX_TAB_TITLE_LEN),
579 style.description.text.clone(),
580 )
581 .contained()
582 .with_style(style.description.container)
583 .aligned(),
584 )
585 }))
586 .align_children_center()
587 .into_any()
588 }
589
590 fn for_each_project_item(&self, cx: &AppContext, f: &mut dyn FnMut(usize, &dyn project::Item)) {
591 self.buffer
592 .read(cx)
593 .for_each_buffer(|buffer| f(buffer.id(), buffer.read(cx)));
594 }
595
596 fn is_singleton(&self, cx: &AppContext) -> bool {
597 self.buffer.read(cx).is_singleton()
598 }
599
600 fn clone_on_split(&self, _workspace_id: WorkspaceId, cx: &mut ViewContext<Self>) -> Option<Self>
601 where
602 Self: Sized,
603 {
604 Some(self.clone(cx))
605 }
606
607 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
608 self.nav_history = Some(history);
609 }
610
611 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
612 let selection = self.selections.newest_anchor();
613 self.push_to_nav_history(selection.head(), None, cx);
614 }
615
616 fn workspace_deactivated(&mut self, cx: &mut ViewContext<Self>) {
617 hide_link_definition(self, cx);
618 self.link_go_to_definition_state.last_mouse_location = None;
619 }
620
621 fn is_dirty(&self, cx: &AppContext) -> bool {
622 self.buffer().read(cx).read(cx).is_dirty()
623 }
624
625 fn has_conflict(&self, cx: &AppContext) -> bool {
626 self.buffer().read(cx).read(cx).has_conflict()
627 }
628
629 fn can_save(&self, cx: &AppContext) -> bool {
630 let buffer = &self.buffer().read(cx);
631 if let Some(buffer) = buffer.as_singleton() {
632 buffer.read(cx).project_path(cx).is_some()
633 } else {
634 true
635 }
636 }
637
638 fn save(
639 &mut self,
640 project: ModelHandle<Project>,
641 cx: &mut ViewContext<Self>,
642 ) -> Task<Result<()>> {
643 self.report_editor_event("save", None, cx);
644 let format = self.perform_format(project.clone(), FormatTrigger::Save, cx);
645 let buffers = self.buffer().clone().read(cx).all_buffers();
646 cx.spawn(|_, mut cx| async move {
647 format.await?;
648
649 if buffers.len() == 1 {
650 project
651 .update(&mut cx, |project, cx| project.save_buffers(buffers, cx))
652 .await?;
653 } else {
654 // For multi-buffers, only save those ones that contain changes. For clean buffers
655 // we simulate saving by calling `Buffer::did_save`, so that language servers or
656 // other downstream listeners of save events get notified.
657 let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
658 buffer.read_with(&cx, |buffer, _| buffer.is_dirty() || buffer.has_conflict())
659 });
660
661 project
662 .update(&mut cx, |project, cx| {
663 project.save_buffers(dirty_buffers, cx)
664 })
665 .await?;
666 for buffer in clean_buffers {
667 buffer.update(&mut cx, |buffer, cx| {
668 let version = buffer.saved_version().clone();
669 let fingerprint = buffer.saved_version_fingerprint();
670 let mtime = buffer.saved_mtime();
671 buffer.did_save(version, fingerprint, mtime, cx);
672 });
673 }
674 }
675
676 Ok(())
677 })
678 }
679
680 fn save_as(
681 &mut self,
682 project: ModelHandle<Project>,
683 abs_path: PathBuf,
684 cx: &mut ViewContext<Self>,
685 ) -> Task<Result<()>> {
686 let buffer = self
687 .buffer()
688 .read(cx)
689 .as_singleton()
690 .expect("cannot call save_as on an excerpt list");
691
692 let file_extension = abs_path
693 .extension()
694 .map(|a| a.to_string_lossy().to_string());
695 self.report_editor_event("save", file_extension, cx);
696
697 project.update(cx, |project, cx| {
698 project.save_buffer_as(buffer, abs_path, cx)
699 })
700 }
701
702 fn reload(
703 &mut self,
704 project: ModelHandle<Project>,
705 cx: &mut ViewContext<Self>,
706 ) -> Task<Result<()>> {
707 let buffer = self.buffer().clone();
708 let buffers = self.buffer.read(cx).all_buffers();
709 let reload_buffers =
710 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
711 cx.spawn(|this, mut cx| async move {
712 let transaction = reload_buffers.log_err().await;
713 this.update(&mut cx, |editor, cx| {
714 editor.request_autoscroll(Autoscroll::fit(), cx)
715 })?;
716 buffer.update(&mut cx, |buffer, cx| {
717 if let Some(transaction) = transaction {
718 if !buffer.is_singleton() {
719 buffer.push_transaction(&transaction.0, cx);
720 }
721 }
722 });
723 Ok(())
724 })
725 }
726
727 fn to_item_events(event: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
728 let mut result = SmallVec::new();
729 match event {
730 Event::Closed => result.push(ItemEvent::CloseItem),
731 Event::Saved | Event::TitleChanged => {
732 result.push(ItemEvent::UpdateTab);
733 result.push(ItemEvent::UpdateBreadcrumbs);
734 }
735 Event::Reparsed => {
736 result.push(ItemEvent::UpdateBreadcrumbs);
737 }
738 Event::SelectionsChanged { local } if *local => {
739 result.push(ItemEvent::UpdateBreadcrumbs);
740 }
741 Event::DirtyChanged => {
742 result.push(ItemEvent::UpdateTab);
743 }
744 Event::BufferEdited => {
745 result.push(ItemEvent::Edit);
746 result.push(ItemEvent::UpdateBreadcrumbs);
747 }
748 _ => {}
749 }
750 result
751 }
752
753 fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
754 Some(Box::new(handle.clone()))
755 }
756
757 fn pixel_position_of_cursor(&self) -> Option<Vector2F> {
758 self.pixel_position_of_newest_cursor
759 }
760
761 fn breadcrumb_location(&self) -> ToolbarItemLocation {
762 ToolbarItemLocation::PrimaryLeft { flex: None }
763 }
764
765 fn breadcrumbs(&self, theme: &theme::Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
766 let cursor = self.selections.newest_anchor().head();
767 let multibuffer = &self.buffer().read(cx);
768 let (buffer_id, symbols) =
769 multibuffer.symbols_containing(cursor, Some(&theme.editor.syntax), cx)?;
770 let buffer = multibuffer.buffer(buffer_id)?;
771
772 let buffer = buffer.read(cx);
773 let filename = buffer
774 .snapshot()
775 .resolve_file_path(
776 cx,
777 self.project
778 .as_ref()
779 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
780 .unwrap_or_default(),
781 )
782 .map(|path| path.to_string_lossy().to_string())
783 .unwrap_or_else(|| "untitled".to_string());
784
785 let mut breadcrumbs = vec![BreadcrumbText {
786 text: filename,
787 highlights: None,
788 }];
789 breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
790 text: symbol.text,
791 highlights: Some(symbol.highlight_ranges),
792 }));
793 Some(breadcrumbs)
794 }
795
796 fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
797 let workspace_id = workspace.database_id();
798 let item_id = cx.view_id();
799 self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
800
801 fn serialize(
802 buffer: ModelHandle<Buffer>,
803 workspace_id: WorkspaceId,
804 item_id: ItemId,
805 cx: &mut AppContext,
806 ) {
807 if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
808 let path = file.abs_path(cx);
809
810 cx.background()
811 .spawn(async move {
812 DB.save_path(item_id, workspace_id, path.clone())
813 .await
814 .log_err()
815 })
816 .detach();
817 }
818 }
819
820 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
821 serialize(buffer.clone(), workspace_id, item_id, cx);
822
823 cx.subscribe(&buffer, |this, buffer, event, cx| {
824 if let Some((_, workspace_id)) = this.workspace.as_ref() {
825 if let language::Event::FileHandleChanged = event {
826 serialize(buffer, *workspace_id, cx.view_id(), cx);
827 }
828 }
829 })
830 .detach();
831 }
832 }
833
834 fn serialized_item_kind() -> Option<&'static str> {
835 Some("Editor")
836 }
837
838 fn deserialize(
839 project: ModelHandle<Project>,
840 _workspace: WeakViewHandle<Workspace>,
841 workspace_id: workspace::WorkspaceId,
842 item_id: ItemId,
843 cx: &mut ViewContext<Pane>,
844 ) -> Task<Result<ViewHandle<Self>>> {
845 let project_item: Result<_> = project.update(cx, |project, cx| {
846 // Look up the path with this key associated, create a self with that path
847 let path = DB
848 .get_path(item_id, workspace_id)?
849 .context("No path stored for this editor")?;
850
851 let (worktree, path) = project
852 .find_local_worktree(&path, cx)
853 .with_context(|| format!("No worktree for path: {path:?}"))?;
854 let project_path = ProjectPath {
855 worktree_id: worktree.read(cx).id(),
856 path: path.into(),
857 };
858
859 Ok(project.open_path(project_path, cx))
860 });
861
862 project_item
863 .map(|project_item| {
864 cx.spawn(|pane, mut cx| async move {
865 let (_, project_item) = project_item.await?;
866 let buffer = project_item
867 .downcast::<Buffer>()
868 .context("Project item at stored path was not a buffer")?;
869 Ok(pane.update(&mut cx, |_, cx| {
870 cx.add_view(|cx| {
871 let mut editor = Editor::for_buffer(buffer, Some(project), cx);
872 editor.read_scroll_position_from_db(item_id, workspace_id, cx);
873 editor
874 })
875 })?)
876 })
877 })
878 .unwrap_or_else(|error| Task::ready(Err(error)))
879 }
880}
881
882impl ProjectItem for Editor {
883 type Item = Buffer;
884
885 fn for_project_item(
886 project: ModelHandle<Project>,
887 buffer: ModelHandle<Buffer>,
888 cx: &mut ViewContext<Self>,
889 ) -> Self {
890 Self::for_buffer(buffer, Some(project), cx)
891 }
892}
893
894pub(crate) enum BufferSearchHighlights {}
895impl SearchableItem for Editor {
896 type Match = Range<Anchor>;
897
898 fn to_search_event(
899 &mut self,
900 event: &Self::Event,
901 _: &mut ViewContext<Self>,
902 ) -> Option<SearchEvent> {
903 match event {
904 Event::BufferEdited => Some(SearchEvent::MatchesInvalidated),
905 Event::SelectionsChanged { .. } => {
906 if self.selections.disjoint_anchors().len() == 1 {
907 Some(SearchEvent::ActiveMatchChanged)
908 } else {
909 None
910 }
911 }
912 _ => None,
913 }
914 }
915
916 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
917 self.clear_background_highlights::<BufferSearchHighlights>(cx);
918 }
919
920 fn update_matches(&mut self, matches: Vec<Range<Anchor>>, cx: &mut ViewContext<Self>) {
921 self.highlight_background::<BufferSearchHighlights>(
922 matches,
923 |theme| theme.search.match_background,
924 cx,
925 );
926 }
927
928 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
929 let display_map = self.snapshot(cx).display_snapshot;
930 let selection = self.selections.newest::<usize>(cx);
931 if selection.start == selection.end {
932 let point = selection.start.to_display_point(&display_map);
933 let range = surrounding_word(&display_map, point);
934 let range = range.start.to_offset(&display_map, Bias::Left)
935 ..range.end.to_offset(&display_map, Bias::Right);
936 let text: String = display_map.buffer_snapshot.text_for_range(range).collect();
937 if text.trim().is_empty() {
938 String::new()
939 } else {
940 text
941 }
942 } else {
943 display_map
944 .buffer_snapshot
945 .text_for_range(selection.start..selection.end)
946 .collect()
947 }
948 }
949
950 fn activate_match(
951 &mut self,
952 index: usize,
953 matches: Vec<Range<Anchor>>,
954 cx: &mut ViewContext<Self>,
955 ) {
956 self.unfold_ranges([matches[index].clone()], false, true, cx);
957 let range = self.range_for_match(&matches[index]);
958 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
959 s.select_ranges([range]);
960 })
961 }
962
963 fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
964 self.unfold_ranges(matches.clone(), false, false, cx);
965 let mut ranges = Vec::new();
966 for m in &matches {
967 ranges.push(self.range_for_match(&m))
968 }
969 self.change_selections(None, cx, |s| s.select_ranges(ranges));
970 }
971
972 fn match_index_for_direction(
973 &mut self,
974 matches: &Vec<Range<Anchor>>,
975 current_index: usize,
976 direction: Direction,
977 count: usize,
978 cx: &mut ViewContext<Self>,
979 ) -> usize {
980 let buffer = self.buffer().read(cx).snapshot(cx);
981 let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
982 self.selections.newest_anchor().head()
983 } else {
984 matches[current_index].start
985 };
986
987 let mut count = count % matches.len();
988 if count == 0 {
989 return current_index;
990 }
991 match direction {
992 Direction::Next => {
993 if matches[current_index]
994 .start
995 .cmp(¤t_index_position, &buffer)
996 .is_gt()
997 {
998 count = count - 1
999 }
1000
1001 (current_index + count) % matches.len()
1002 }
1003 Direction::Prev => {
1004 if matches[current_index]
1005 .end
1006 .cmp(¤t_index_position, &buffer)
1007 .is_lt()
1008 {
1009 count = count - 1;
1010 }
1011
1012 if current_index >= count {
1013 current_index - count
1014 } else {
1015 matches.len() - (count - current_index)
1016 }
1017 }
1018 }
1019 }
1020
1021 fn find_matches(
1022 &mut self,
1023 query: project::search::SearchQuery,
1024 cx: &mut ViewContext<Self>,
1025 ) -> Task<Vec<Range<Anchor>>> {
1026 let buffer = self.buffer().read(cx).snapshot(cx);
1027 cx.background().spawn(async move {
1028 let mut ranges = Vec::new();
1029 if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
1030 ranges.extend(
1031 query
1032 .search(excerpt_buffer, None)
1033 .await
1034 .into_iter()
1035 .map(|range| {
1036 buffer.anchor_after(range.start)..buffer.anchor_before(range.end)
1037 }),
1038 );
1039 } else {
1040 for excerpt in buffer.excerpt_boundaries_in_range(0..buffer.len()) {
1041 let excerpt_range = excerpt.range.context.to_offset(&excerpt.buffer);
1042 ranges.extend(
1043 query
1044 .search(&excerpt.buffer, Some(excerpt_range.clone()))
1045 .await
1046 .into_iter()
1047 .map(|range| {
1048 let start = excerpt
1049 .buffer
1050 .anchor_after(excerpt_range.start + range.start);
1051 let end = excerpt
1052 .buffer
1053 .anchor_before(excerpt_range.start + range.end);
1054 buffer.anchor_in_excerpt(excerpt.id.clone(), start)
1055 ..buffer.anchor_in_excerpt(excerpt.id.clone(), end)
1056 }),
1057 );
1058 }
1059 }
1060 ranges
1061 })
1062 }
1063
1064 fn active_match_index(
1065 &mut self,
1066 matches: Vec<Range<Anchor>>,
1067 cx: &mut ViewContext<Self>,
1068 ) -> Option<usize> {
1069 active_match_index(
1070 &matches,
1071 &self.selections.newest_anchor().head(),
1072 &self.buffer().read(cx).snapshot(cx),
1073 )
1074 }
1075}
1076
1077pub fn active_match_index(
1078 ranges: &[Range<Anchor>],
1079 cursor: &Anchor,
1080 buffer: &MultiBufferSnapshot,
1081) -> Option<usize> {
1082 if ranges.is_empty() {
1083 None
1084 } else {
1085 match ranges.binary_search_by(|probe| {
1086 if probe.end.cmp(cursor, &*buffer).is_lt() {
1087 Ordering::Less
1088 } else if probe.start.cmp(cursor, &*buffer).is_gt() {
1089 Ordering::Greater
1090 } else {
1091 Ordering::Equal
1092 }
1093 }) {
1094 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1095 }
1096 }
1097}
1098
1099pub struct CursorPosition {
1100 position: Option<Point>,
1101 selected_count: usize,
1102 _observe_active_editor: Option<Subscription>,
1103}
1104
1105impl Default for CursorPosition {
1106 fn default() -> Self {
1107 Self::new()
1108 }
1109}
1110
1111impl CursorPosition {
1112 pub fn new() -> Self {
1113 Self {
1114 position: None,
1115 selected_count: 0,
1116 _observe_active_editor: None,
1117 }
1118 }
1119
1120 fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
1121 let editor = editor.read(cx);
1122 let buffer = editor.buffer().read(cx).snapshot(cx);
1123
1124 self.selected_count = 0;
1125 let mut last_selection: Option<Selection<usize>> = None;
1126 for selection in editor.selections.all::<usize>(cx) {
1127 self.selected_count += selection.end - selection.start;
1128 if last_selection
1129 .as_ref()
1130 .map_or(true, |last_selection| selection.id > last_selection.id)
1131 {
1132 last_selection = Some(selection);
1133 }
1134 }
1135 self.position = last_selection.map(|s| s.head().to_point(&buffer));
1136
1137 cx.notify();
1138 }
1139}
1140
1141impl Entity for CursorPosition {
1142 type Event = ();
1143}
1144
1145impl View for CursorPosition {
1146 fn ui_name() -> &'static str {
1147 "CursorPosition"
1148 }
1149
1150 fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
1151 if let Some(position) = self.position {
1152 let theme = &theme::current(cx).workspace.status_bar;
1153 let mut text = format!(
1154 "{}{FILE_ROW_COLUMN_DELIMITER}{}",
1155 position.row + 1,
1156 position.column + 1
1157 );
1158 if self.selected_count > 0 {
1159 write!(text, " ({} selected)", self.selected_count).unwrap();
1160 }
1161 Label::new(text, theme.cursor_position.clone()).into_any()
1162 } else {
1163 Empty::new().into_any()
1164 }
1165 }
1166}
1167
1168impl StatusItemView for CursorPosition {
1169 fn set_active_pane_item(
1170 &mut self,
1171 active_pane_item: Option<&dyn ItemHandle>,
1172 cx: &mut ViewContext<Self>,
1173 ) {
1174 if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
1175 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
1176 self.update_position(editor, cx);
1177 } else {
1178 self.position = None;
1179 self._observe_active_editor = None;
1180 }
1181
1182 cx.notify();
1183 }
1184}
1185
1186fn path_for_buffer<'a>(
1187 buffer: &ModelHandle<MultiBuffer>,
1188 height: usize,
1189 include_filename: bool,
1190 cx: &'a AppContext,
1191) -> Option<Cow<'a, Path>> {
1192 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1193 path_for_file(file.as_ref(), height, include_filename, cx)
1194}
1195
1196fn path_for_file<'a>(
1197 file: &'a dyn language::File,
1198 mut height: usize,
1199 include_filename: bool,
1200 cx: &'a AppContext,
1201) -> Option<Cow<'a, Path>> {
1202 // Ensure we always render at least the filename.
1203 height += 1;
1204
1205 let mut prefix = file.path().as_ref();
1206 while height > 0 {
1207 if let Some(parent) = prefix.parent() {
1208 prefix = parent;
1209 height -= 1;
1210 } else {
1211 break;
1212 }
1213 }
1214
1215 // Here we could have just always used `full_path`, but that is very
1216 // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1217 // traversed all the way up to the worktree's root.
1218 if height > 0 {
1219 let full_path = file.full_path(cx);
1220 if include_filename {
1221 Some(full_path.into())
1222 } else {
1223 Some(full_path.parent()?.to_path_buf().into())
1224 }
1225 } else {
1226 let mut path = file.path().strip_prefix(prefix).ok()?;
1227 if !include_filename {
1228 path = path.parent()?;
1229 }
1230 Some(path.into())
1231 }
1232}
1233
1234#[cfg(test)]
1235mod tests {
1236 use super::*;
1237 use gpui::AppContext;
1238 use std::{
1239 path::{Path, PathBuf},
1240 sync::Arc,
1241 time::SystemTime,
1242 };
1243
1244 #[gpui::test]
1245 fn test_path_for_file(cx: &mut AppContext) {
1246 let file = TestFile {
1247 path: Path::new("").into(),
1248 full_path: PathBuf::from(""),
1249 };
1250 assert_eq!(path_for_file(&file, 0, false, cx), None);
1251 }
1252
1253 struct TestFile {
1254 path: Arc<Path>,
1255 full_path: PathBuf,
1256 }
1257
1258 impl language::File for TestFile {
1259 fn path(&self) -> &Arc<Path> {
1260 &self.path
1261 }
1262
1263 fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
1264 self.full_path.clone()
1265 }
1266
1267 fn as_local(&self) -> Option<&dyn language::LocalFile> {
1268 unimplemented!()
1269 }
1270
1271 fn mtime(&self) -> SystemTime {
1272 unimplemented!()
1273 }
1274
1275 fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
1276 unimplemented!()
1277 }
1278
1279 fn worktree_id(&self) -> usize {
1280 0
1281 }
1282
1283 fn is_deleted(&self) -> bool {
1284 unimplemented!()
1285 }
1286
1287 fn as_any(&self) -> &dyn std::any::Any {
1288 unimplemented!()
1289 }
1290
1291 fn to_proto(&self) -> rpc::proto::File {
1292 unimplemented!()
1293 }
1294 }
1295}