1use crate::{
2 editor_settings::SeedQuerySetting,
3 persistence::{SerializedEditor, DB},
4 scroll::ScrollAnchor,
5 Anchor, Autoscroll, Editor, EditorEvent, EditorSettings, ExcerptId, ExcerptRange, MultiBuffer,
6 MultiBufferSnapshot, NavigationData, SearchWithinRange, ToPoint as _,
7};
8use anyhow::{anyhow, Context as _, Result};
9use collections::HashSet;
10use file_icons::FileIcons;
11use futures::future::try_join_all;
12use git::repository::GitFileStatus;
13use gpui::{
14 point, AnyElement, AppContext, AsyncWindowContext, Context, Entity, EntityId, EventEmitter,
15 IntoElement, Model, ParentElement, Pixels, SharedString, Styled, Task, View, ViewContext,
16 VisualContext, WeakView, WindowContext,
17};
18use language::{
19 proto::serialize_anchor as serialize_text_anchor, Bias, Buffer, CharKind, Point, SelectionGoal,
20};
21use multi_buffer::AnchorRangeExt;
22use project::{
23 lsp_store::FormatTrigger, project_settings::ProjectSettings, search::SearchQuery, Item as _,
24 Project, ProjectPath,
25};
26use rpc::proto::{self, update_view, PeerId};
27use settings::Settings;
28use workspace::item::{Dedup, ItemSettings, SerializableItem, TabContentParams};
29
30use std::{
31 any::TypeId,
32 borrow::Cow,
33 cmp::{self, Ordering},
34 iter,
35 ops::Range,
36 path::Path,
37 sync::Arc,
38};
39use text::{BufferId, Selection};
40use theme::{Theme, ThemeSettings};
41use ui::{h_flex, prelude::*, Label};
42use util::{paths::PathExt, ResultExt, TryFutureExt};
43use workspace::item::{BreadcrumbText, FollowEvent};
44use workspace::{
45 item::{FollowableItem, Item, ItemEvent, ProjectItem},
46 searchable::{Direction, SearchEvent, SearchableItem, SearchableItemHandle},
47 ItemId, ItemNavHistory, Pane, ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
48};
49
50pub const MAX_TAB_TITLE_LEN: usize = 24;
51
52impl FollowableItem for Editor {
53 fn remote_id(&self) -> Option<ViewId> {
54 self.remote_id
55 }
56
57 fn from_state_proto(
58 workspace: View<Workspace>,
59 remote_id: ViewId,
60 state: &mut Option<proto::view::Variant>,
61 cx: &mut WindowContext,
62 ) -> Option<Task<Result<View<Self>>>> {
63 let project = workspace.read(cx).project().to_owned();
64 let Some(proto::view::Variant::Editor(_)) = state else {
65 return None;
66 };
67 let Some(proto::view::Variant::Editor(state)) = state.take() else {
68 unreachable!()
69 };
70
71 let buffer_ids = state
72 .excerpts
73 .iter()
74 .map(|excerpt| excerpt.buffer_id)
75 .collect::<HashSet<_>>();
76 let buffers = project.update(cx, |project, cx| {
77 buffer_ids
78 .iter()
79 .map(|id| BufferId::new(*id).map(|id| project.open_buffer_by_id(id, cx)))
80 .collect::<Result<Vec<_>>>()
81 });
82
83 Some(cx.spawn(|mut cx| async move {
84 let mut buffers = futures::future::try_join_all(buffers?)
85 .await
86 .debug_assert_ok("leaders don't share views for unshared buffers")?;
87
88 let editor = cx.update(|cx| {
89 let multibuffer = cx.new_model(|cx| {
90 let mut multibuffer;
91 if state.singleton && buffers.len() == 1 {
92 multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
93 } else {
94 multibuffer = MultiBuffer::new(project.read(cx).capability());
95 let mut excerpts = state.excerpts.into_iter().peekable();
96 while let Some(excerpt) = excerpts.peek() {
97 let Ok(buffer_id) = BufferId::new(excerpt.buffer_id) else {
98 continue;
99 };
100 let buffer_excerpts = iter::from_fn(|| {
101 let excerpt = excerpts.peek()?;
102 (excerpt.buffer_id == u64::from(buffer_id))
103 .then(|| excerpts.next().unwrap())
104 });
105 let buffer =
106 buffers.iter().find(|b| b.read(cx).remote_id() == buffer_id);
107 if let Some(buffer) = buffer {
108 multibuffer.push_excerpts(
109 buffer.clone(),
110 buffer_excerpts.filter_map(deserialize_excerpt_range),
111 cx,
112 );
113 }
114 }
115 };
116
117 if let Some(title) = &state.title {
118 multibuffer = multibuffer.with_title(title.clone())
119 }
120
121 multibuffer
122 });
123
124 cx.new_view(|cx| {
125 let mut editor =
126 Editor::for_multibuffer(multibuffer, Some(project.clone()), true, cx);
127 editor.remote_id = Some(remote_id);
128 editor
129 })
130 })?;
131
132 update_editor_from_message(
133 editor.downgrade(),
134 project,
135 proto::update_view::Editor {
136 selections: state.selections,
137 pending_selection: state.pending_selection,
138 scroll_top_anchor: state.scroll_top_anchor,
139 scroll_x: state.scroll_x,
140 scroll_y: state.scroll_y,
141 ..Default::default()
142 },
143 &mut cx,
144 )
145 .await?;
146
147 Ok(editor)
148 }))
149 }
150
151 fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>) {
152 self.leader_peer_id = leader_peer_id;
153 if self.leader_peer_id.is_some() {
154 self.buffer.update(cx, |buffer, cx| {
155 buffer.remove_active_selections(cx);
156 });
157 } else if self.focus_handle.is_focused(cx) {
158 self.buffer.update(cx, |buffer, cx| {
159 buffer.set_active_selections(
160 &self.selections.disjoint_anchors(),
161 self.selections.line_mode,
162 self.cursor_shape,
163 cx,
164 );
165 });
166 }
167 cx.notify();
168 }
169
170 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
171 let buffer = self.buffer.read(cx);
172 if buffer
173 .as_singleton()
174 .and_then(|buffer| buffer.read(cx).file())
175 .map_or(false, |file| file.is_private())
176 {
177 return None;
178 }
179
180 let scroll_anchor = self.scroll_manager.anchor();
181 let excerpts = buffer
182 .read(cx)
183 .excerpts()
184 .map(|(id, buffer, range)| proto::Excerpt {
185 id: id.to_proto(),
186 buffer_id: buffer.remote_id().into(),
187 context_start: Some(serialize_text_anchor(&range.context.start)),
188 context_end: Some(serialize_text_anchor(&range.context.end)),
189 primary_start: range
190 .primary
191 .as_ref()
192 .map(|range| serialize_text_anchor(&range.start)),
193 primary_end: range
194 .primary
195 .as_ref()
196 .map(|range| serialize_text_anchor(&range.end)),
197 })
198 .collect();
199
200 Some(proto::view::Variant::Editor(proto::view::Editor {
201 singleton: buffer.is_singleton(),
202 title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
203 excerpts,
204 scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
205 scroll_x: scroll_anchor.offset.x,
206 scroll_y: scroll_anchor.offset.y,
207 selections: self
208 .selections
209 .disjoint_anchors()
210 .iter()
211 .map(serialize_selection)
212 .collect(),
213 pending_selection: self
214 .selections
215 .pending_anchor()
216 .as_ref()
217 .map(serialize_selection),
218 }))
219 }
220
221 fn to_follow_event(event: &EditorEvent) -> Option<workspace::item::FollowEvent> {
222 match event {
223 EditorEvent::Edited { .. } => Some(FollowEvent::Unfollow),
224 EditorEvent::SelectionsChanged { local }
225 | EditorEvent::ScrollPositionChanged { local, .. } => {
226 if *local {
227 Some(FollowEvent::Unfollow)
228 } else {
229 None
230 }
231 }
232 _ => None,
233 }
234 }
235
236 fn add_event_to_update_proto(
237 &self,
238 event: &EditorEvent,
239 update: &mut Option<proto::update_view::Variant>,
240 cx: &WindowContext,
241 ) -> bool {
242 let update =
243 update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
244
245 match update {
246 proto::update_view::Variant::Editor(update) => match event {
247 EditorEvent::ExcerptsAdded {
248 buffer,
249 predecessor,
250 excerpts,
251 } => {
252 let buffer_id = buffer.read(cx).remote_id();
253 let mut excerpts = excerpts.iter();
254 if let Some((id, range)) = excerpts.next() {
255 update.inserted_excerpts.push(proto::ExcerptInsertion {
256 previous_excerpt_id: Some(predecessor.to_proto()),
257 excerpt: serialize_excerpt(buffer_id, id, range),
258 });
259 update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
260 proto::ExcerptInsertion {
261 previous_excerpt_id: None,
262 excerpt: serialize_excerpt(buffer_id, id, range),
263 }
264 }))
265 }
266 true
267 }
268 EditorEvent::ExcerptsRemoved { ids } => {
269 update
270 .deleted_excerpts
271 .extend(ids.iter().map(ExcerptId::to_proto));
272 true
273 }
274 EditorEvent::ScrollPositionChanged { autoscroll, .. } if !autoscroll => {
275 let scroll_anchor = self.scroll_manager.anchor();
276 update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
277 update.scroll_x = scroll_anchor.offset.x;
278 update.scroll_y = scroll_anchor.offset.y;
279 true
280 }
281 EditorEvent::SelectionsChanged { .. } => {
282 update.selections = self
283 .selections
284 .disjoint_anchors()
285 .iter()
286 .map(serialize_selection)
287 .collect();
288 update.pending_selection = self
289 .selections
290 .pending_anchor()
291 .as_ref()
292 .map(serialize_selection);
293 true
294 }
295 _ => false,
296 },
297 }
298 }
299
300 fn apply_update_proto(
301 &mut self,
302 project: &Model<Project>,
303 message: update_view::Variant,
304 cx: &mut ViewContext<Self>,
305 ) -> Task<Result<()>> {
306 let update_view::Variant::Editor(message) = message;
307 let project = project.clone();
308 cx.spawn(|this, mut cx| async move {
309 update_editor_from_message(this, project, message, &mut cx).await
310 })
311 }
312
313 fn is_project_item(&self, _cx: &WindowContext) -> bool {
314 true
315 }
316
317 fn dedup(&self, existing: &Self, cx: &WindowContext) -> Option<Dedup> {
318 let self_singleton = self.buffer.read(cx).as_singleton()?;
319 let other_singleton = existing.buffer.read(cx).as_singleton()?;
320 if self_singleton == other_singleton {
321 Some(Dedup::KeepExisting)
322 } else {
323 None
324 }
325 }
326}
327
328async fn update_editor_from_message(
329 this: WeakView<Editor>,
330 project: Model<Project>,
331 message: proto::update_view::Editor,
332 cx: &mut AsyncWindowContext,
333) -> Result<()> {
334 // Open all of the buffers of which excerpts were added to the editor.
335 let inserted_excerpt_buffer_ids = message
336 .inserted_excerpts
337 .iter()
338 .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
339 .collect::<HashSet<_>>();
340 let inserted_excerpt_buffers = project.update(cx, |project, cx| {
341 inserted_excerpt_buffer_ids
342 .into_iter()
343 .map(|id| BufferId::new(id).map(|id| project.open_buffer_by_id(id, cx)))
344 .collect::<Result<Vec<_>>>()
345 })??;
346 let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
347
348 // Update the editor's excerpts.
349 this.update(cx, |editor, cx| {
350 editor.buffer.update(cx, |multibuffer, cx| {
351 let mut removed_excerpt_ids = message
352 .deleted_excerpts
353 .into_iter()
354 .map(ExcerptId::from_proto)
355 .collect::<Vec<_>>();
356 removed_excerpt_ids.sort_by({
357 let multibuffer = multibuffer.read(cx);
358 move |a, b| a.cmp(b, &multibuffer)
359 });
360
361 let mut insertions = message.inserted_excerpts.into_iter().peekable();
362 while let Some(insertion) = insertions.next() {
363 let Some(excerpt) = insertion.excerpt else {
364 continue;
365 };
366 let Some(previous_excerpt_id) = insertion.previous_excerpt_id else {
367 continue;
368 };
369 let buffer_id = BufferId::new(excerpt.buffer_id)?;
370 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
371 continue;
372 };
373
374 let adjacent_excerpts = iter::from_fn(|| {
375 let insertion = insertions.peek()?;
376 if insertion.previous_excerpt_id.is_none()
377 && insertion.excerpt.as_ref()?.buffer_id == u64::from(buffer_id)
378 {
379 insertions.next()?.excerpt
380 } else {
381 None
382 }
383 });
384
385 multibuffer.insert_excerpts_with_ids_after(
386 ExcerptId::from_proto(previous_excerpt_id),
387 buffer,
388 [excerpt]
389 .into_iter()
390 .chain(adjacent_excerpts)
391 .filter_map(|excerpt| {
392 Some((
393 ExcerptId::from_proto(excerpt.id),
394 deserialize_excerpt_range(excerpt)?,
395 ))
396 }),
397 cx,
398 );
399 }
400
401 multibuffer.remove_excerpts(removed_excerpt_ids, cx);
402 Result::<(), anyhow::Error>::Ok(())
403 })
404 })??;
405
406 // Deserialize the editor state.
407 let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {
408 let buffer = editor.buffer.read(cx).read(cx);
409 let selections = message
410 .selections
411 .into_iter()
412 .filter_map(|selection| deserialize_selection(&buffer, selection))
413 .collect::<Vec<_>>();
414 let pending_selection = message
415 .pending_selection
416 .and_then(|selection| deserialize_selection(&buffer, selection));
417 let scroll_top_anchor = message
418 .scroll_top_anchor
419 .and_then(|anchor| deserialize_anchor(&buffer, anchor));
420 anyhow::Ok((selections, pending_selection, scroll_top_anchor))
421 })??;
422
423 // Wait until the buffer has received all of the operations referenced by
424 // the editor's new state.
425 this.update(cx, |editor, cx| {
426 editor.buffer.update(cx, |buffer, cx| {
427 buffer.wait_for_anchors(
428 selections
429 .iter()
430 .chain(pending_selection.as_ref())
431 .flat_map(|selection| [selection.start, selection.end])
432 .chain(scroll_top_anchor),
433 cx,
434 )
435 })
436 })?
437 .await?;
438
439 // Update the editor's state.
440 this.update(cx, |editor, cx| {
441 if !selections.is_empty() || pending_selection.is_some() {
442 editor.set_selections_from_remote(selections, pending_selection, cx);
443 editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
444 } else if let Some(scroll_top_anchor) = scroll_top_anchor {
445 editor.set_scroll_anchor_remote(
446 ScrollAnchor {
447 anchor: scroll_top_anchor,
448 offset: point(message.scroll_x, message.scroll_y),
449 },
450 cx,
451 );
452 }
453 })?;
454 Ok(())
455}
456
457fn serialize_excerpt(
458 buffer_id: BufferId,
459 id: &ExcerptId,
460 range: &ExcerptRange<language::Anchor>,
461) -> Option<proto::Excerpt> {
462 Some(proto::Excerpt {
463 id: id.to_proto(),
464 buffer_id: buffer_id.into(),
465 context_start: Some(serialize_text_anchor(&range.context.start)),
466 context_end: Some(serialize_text_anchor(&range.context.end)),
467 primary_start: range
468 .primary
469 .as_ref()
470 .map(|r| serialize_text_anchor(&r.start)),
471 primary_end: range
472 .primary
473 .as_ref()
474 .map(|r| serialize_text_anchor(&r.end)),
475 })
476}
477
478fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
479 proto::Selection {
480 id: selection.id as u64,
481 start: Some(serialize_anchor(&selection.start)),
482 end: Some(serialize_anchor(&selection.end)),
483 reversed: selection.reversed,
484 }
485}
486
487fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
488 proto::EditorAnchor {
489 excerpt_id: anchor.excerpt_id.to_proto(),
490 anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
491 }
492}
493
494fn deserialize_excerpt_range(excerpt: proto::Excerpt) -> Option<ExcerptRange<language::Anchor>> {
495 let context = {
496 let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
497 let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
498 start..end
499 };
500 let primary = excerpt
501 .primary_start
502 .zip(excerpt.primary_end)
503 .and_then(|(start, end)| {
504 let start = language::proto::deserialize_anchor(start)?;
505 let end = language::proto::deserialize_anchor(end)?;
506 Some(start..end)
507 });
508 Some(ExcerptRange { context, primary })
509}
510
511fn deserialize_selection(
512 buffer: &MultiBufferSnapshot,
513 selection: proto::Selection,
514) -> Option<Selection<Anchor>> {
515 Some(Selection {
516 id: selection.id as usize,
517 start: deserialize_anchor(buffer, selection.start?)?,
518 end: deserialize_anchor(buffer, selection.end?)?,
519 reversed: selection.reversed,
520 goal: SelectionGoal::None,
521 })
522}
523
524fn deserialize_anchor(buffer: &MultiBufferSnapshot, anchor: proto::EditorAnchor) -> Option<Anchor> {
525 let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
526 Some(Anchor {
527 excerpt_id,
528 text_anchor: language::proto::deserialize_anchor(anchor.anchor?)?,
529 buffer_id: buffer.buffer_id_for_excerpt(excerpt_id),
530 })
531}
532
533impl Item for Editor {
534 type Event = EditorEvent;
535
536 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
537 if let Ok(data) = data.downcast::<NavigationData>() {
538 let newest_selection = self.selections.newest::<Point>(cx);
539 let buffer = self.buffer.read(cx).read(cx);
540 let offset = if buffer.can_resolve(&data.cursor_anchor) {
541 data.cursor_anchor.to_point(&buffer)
542 } else {
543 buffer.clip_point(data.cursor_position, Bias::Left)
544 };
545
546 let mut scroll_anchor = data.scroll_anchor;
547 if !buffer.can_resolve(&scroll_anchor.anchor) {
548 scroll_anchor.anchor = buffer.anchor_before(
549 buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
550 );
551 }
552
553 drop(buffer);
554
555 if newest_selection.head() == offset {
556 false
557 } else {
558 let nav_history = self.nav_history.take();
559 self.set_scroll_anchor(scroll_anchor, cx);
560 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
561 s.select_ranges([offset..offset])
562 });
563 self.nav_history = nav_history;
564 true
565 }
566 } else {
567 false
568 }
569 }
570
571 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
572 let file_path = self
573 .buffer()
574 .read(cx)
575 .as_singleton()?
576 .read(cx)
577 .file()
578 .and_then(|f| f.as_local())?
579 .abs_path(cx);
580
581 let file_path = file_path.compact().to_string_lossy().to_string();
582
583 Some(file_path.into())
584 }
585
586 fn telemetry_event_text(&self) -> Option<&'static str> {
587 None
588 }
589
590 fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString> {
591 let path = path_for_buffer(&self.buffer, detail, true, cx)?;
592 Some(path.to_string_lossy().to_string().into())
593 }
594
595 fn tab_icon(&self, cx: &WindowContext) -> Option<Icon> {
596 ItemSettings::get_global(cx)
597 .file_icons
598 .then(|| {
599 self.buffer
600 .read(cx)
601 .as_singleton()
602 .and_then(|buffer| buffer.read(cx).project_path(cx))
603 .and_then(|path| FileIcons::get_icon(path.path.as_ref(), cx))
604 })
605 .flatten()
606 .map(Icon::from_path)
607 }
608
609 fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
610 let label_color = if ItemSettings::get_global(cx).git_status {
611 self.buffer()
612 .read(cx)
613 .as_singleton()
614 .and_then(|buffer| buffer.read(cx).project_path(cx))
615 .and_then(|path| self.project.as_ref()?.read(cx).entry_for_path(&path, cx))
616 .map(|entry| {
617 entry_git_aware_label_color(entry.git_status, entry.is_ignored, params.selected)
618 })
619 .unwrap_or_else(|| entry_label_color(params.selected))
620 } else {
621 entry_label_color(params.selected)
622 };
623
624 let description = params.detail.and_then(|detail| {
625 let path = path_for_buffer(&self.buffer, detail, false, cx)?;
626 let description = path.to_string_lossy();
627 let description = description.trim();
628
629 if description.is_empty() {
630 return None;
631 }
632
633 Some(util::truncate_and_trailoff(description, MAX_TAB_TITLE_LEN))
634 });
635
636 h_flex()
637 .gap_2()
638 .child(
639 Label::new(self.title(cx).to_string())
640 .color(label_color)
641 .italic(params.preview),
642 )
643 .when_some(description, |this, description| {
644 this.child(
645 Label::new(description)
646 .size(LabelSize::XSmall)
647 .color(Color::Muted),
648 )
649 })
650 .into_any_element()
651 }
652
653 fn for_each_project_item(
654 &self,
655 cx: &AppContext,
656 f: &mut dyn FnMut(EntityId, &dyn project::Item),
657 ) {
658 self.buffer
659 .read(cx)
660 .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
661 }
662
663 fn is_singleton(&self, cx: &AppContext) -> bool {
664 self.buffer.read(cx).is_singleton()
665 }
666
667 fn clone_on_split(
668 &self,
669 _workspace_id: Option<WorkspaceId>,
670 cx: &mut ViewContext<Self>,
671 ) -> Option<View<Editor>>
672 where
673 Self: Sized,
674 {
675 Some(cx.new_view(|cx| self.clone(cx)))
676 }
677
678 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
679 self.nav_history = Some(history);
680 }
681
682 fn discarded(&self, _project: Model<Project>, cx: &mut ViewContext<Self>) {
683 for buffer in self.buffer().clone().read(cx).all_buffers() {
684 buffer.update(cx, |buffer, cx| buffer.discarded(cx))
685 }
686 }
687
688 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
689 let selection = self.selections.newest_anchor();
690 self.push_to_nav_history(selection.head(), None, cx);
691 }
692
693 fn workspace_deactivated(&mut self, cx: &mut ViewContext<Self>) {
694 self.hide_hovered_link(cx);
695 }
696
697 fn is_dirty(&self, cx: &AppContext) -> bool {
698 self.buffer().read(cx).read(cx).is_dirty()
699 }
700
701 fn has_conflict(&self, cx: &AppContext) -> bool {
702 self.buffer().read(cx).read(cx).has_conflict()
703 }
704
705 fn can_save(&self, cx: &AppContext) -> bool {
706 let buffer = &self.buffer().read(cx);
707 if let Some(buffer) = buffer.as_singleton() {
708 buffer.read(cx).project_path(cx).is_some()
709 } else {
710 true
711 }
712 }
713
714 fn save(
715 &mut self,
716 format: bool,
717 project: Model<Project>,
718 cx: &mut ViewContext<Self>,
719 ) -> Task<Result<()>> {
720 self.report_editor_event("save", None, cx);
721 let buffers = self.buffer().clone().read(cx).all_buffers();
722 cx.spawn(|this, mut cx| async move {
723 if format {
724 this.update(&mut cx, |editor, cx| {
725 editor.perform_format(project.clone(), FormatTrigger::Save, cx)
726 })?
727 .await?;
728 }
729
730 if buffers.len() == 1 {
731 // Apply full save routine for singleton buffers, to allow to `touch` the file via the editor.
732 project
733 .update(&mut cx, |project, cx| project.save_buffers(buffers, cx))?
734 .await?;
735 } else {
736 // For multi-buffers, only format and save the buffers with changes.
737 // For clean buffers, we simulate saving by calling `Buffer::did_save`,
738 // so that language servers or other downstream listeners of save events get notified.
739 let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
740 buffer
741 .update(&mut cx, |buffer, _| {
742 buffer.is_dirty() || buffer.has_conflict()
743 })
744 .unwrap_or(false)
745 });
746
747 project
748 .update(&mut cx, |project, cx| {
749 project.save_buffers(dirty_buffers, cx)
750 })?
751 .await?;
752 for buffer in clean_buffers {
753 buffer
754 .update(&mut cx, |buffer, cx| {
755 let version = buffer.saved_version().clone();
756 let mtime = buffer.saved_mtime();
757 buffer.did_save(version, mtime, cx);
758 })
759 .ok();
760 }
761 }
762
763 Ok(())
764 })
765 }
766
767 fn save_as(
768 &mut self,
769 project: Model<Project>,
770 path: ProjectPath,
771 cx: &mut ViewContext<Self>,
772 ) -> Task<Result<()>> {
773 let buffer = self
774 .buffer()
775 .read(cx)
776 .as_singleton()
777 .expect("cannot call save_as on an excerpt list");
778
779 let file_extension = path
780 .path
781 .extension()
782 .map(|a| a.to_string_lossy().to_string());
783 self.report_editor_event("save", file_extension, cx);
784
785 project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
786 }
787
788 fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
789 let buffer = self.buffer().clone();
790 let buffers = self.buffer.read(cx).all_buffers();
791 let reload_buffers =
792 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
793 cx.spawn(|this, mut cx| async move {
794 let transaction = reload_buffers.log_err().await;
795 this.update(&mut cx, |editor, cx| {
796 editor.request_autoscroll(Autoscroll::fit(), cx)
797 })?;
798 buffer
799 .update(&mut cx, |buffer, cx| {
800 if let Some(transaction) = transaction {
801 if !buffer.is_singleton() {
802 buffer.push_transaction(&transaction.0, cx);
803 }
804 }
805 })
806 .ok();
807 Ok(())
808 })
809 }
810
811 fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
812 Some(Box::new(handle.clone()))
813 }
814
815 fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<gpui::Point<Pixels>> {
816 self.pixel_position_of_newest_cursor
817 }
818
819 fn breadcrumb_location(&self) -> ToolbarItemLocation {
820 if self.show_breadcrumbs {
821 ToolbarItemLocation::PrimaryLeft
822 } else {
823 ToolbarItemLocation::Hidden
824 }
825 }
826
827 fn breadcrumbs(&self, variant: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
828 let cursor = self.selections.newest_anchor().head();
829 let multibuffer = &self.buffer().read(cx);
830 let (buffer_id, symbols) =
831 multibuffer.symbols_containing(cursor, Some(variant.syntax()), cx)?;
832 let buffer = multibuffer.buffer(buffer_id)?;
833
834 let buffer = buffer.read(cx);
835 let text = self.breadcrumb_header.clone().unwrap_or_else(|| {
836 buffer
837 .snapshot()
838 .resolve_file_path(
839 cx,
840 self.project
841 .as_ref()
842 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
843 .unwrap_or_default(),
844 )
845 .map(|path| path.to_string_lossy().to_string())
846 .unwrap_or_else(|| {
847 if multibuffer.is_singleton() {
848 multibuffer.title(cx).to_string()
849 } else {
850 "untitled".to_string()
851 }
852 })
853 });
854
855 let settings = ThemeSettings::get_global(cx);
856
857 let mut breadcrumbs = vec![BreadcrumbText {
858 text,
859 highlights: None,
860 font: Some(settings.buffer_font.clone()),
861 }];
862
863 breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
864 text: symbol.text,
865 highlights: Some(symbol.highlight_ranges),
866 font: Some(settings.buffer_font.clone()),
867 }));
868 Some(breadcrumbs)
869 }
870
871 fn added_to_workspace(&mut self, workspace: &mut Workspace, _: &mut ViewContext<Self>) {
872 self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
873 }
874
875 fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
876 match event {
877 EditorEvent::Closed => f(ItemEvent::CloseItem),
878
879 EditorEvent::Saved | EditorEvent::TitleChanged => {
880 f(ItemEvent::UpdateTab);
881 f(ItemEvent::UpdateBreadcrumbs);
882 }
883
884 EditorEvent::Reparsed(_) => {
885 f(ItemEvent::UpdateBreadcrumbs);
886 }
887
888 EditorEvent::SelectionsChanged { local } if *local => {
889 f(ItemEvent::UpdateBreadcrumbs);
890 }
891
892 EditorEvent::DirtyChanged => {
893 f(ItemEvent::UpdateTab);
894 }
895
896 EditorEvent::BufferEdited => {
897 f(ItemEvent::Edit);
898 f(ItemEvent::UpdateBreadcrumbs);
899 }
900
901 EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
902 f(ItemEvent::Edit);
903 }
904
905 _ => {}
906 }
907 }
908
909 fn preserve_preview(&self, cx: &AppContext) -> bool {
910 self.buffer.read(cx).preserve_preview(cx)
911 }
912}
913
914impl SerializableItem for Editor {
915 fn serialized_item_kind() -> &'static str {
916 "Editor"
917 }
918
919 fn cleanup(
920 workspace_id: WorkspaceId,
921 alive_items: Vec<ItemId>,
922 cx: &mut WindowContext,
923 ) -> Task<Result<()>> {
924 cx.spawn(|_| DB.delete_unloaded_items(workspace_id, alive_items))
925 }
926
927 fn deserialize(
928 project: Model<Project>,
929 _workspace: WeakView<Workspace>,
930 workspace_id: workspace::WorkspaceId,
931 item_id: ItemId,
932 cx: &mut ViewContext<Pane>,
933 ) -> Task<Result<View<Self>>> {
934 let serialized_editor = match DB
935 .get_serialized_editor(item_id, workspace_id)
936 .context("Failed to query editor state")
937 {
938 Ok(Some(serialized_editor)) => {
939 if ProjectSettings::get_global(cx)
940 .session
941 .restore_unsaved_buffers
942 {
943 serialized_editor
944 } else {
945 SerializedEditor {
946 path: serialized_editor.path,
947 contents: None,
948 language: None,
949 mtime: None,
950 }
951 }
952 }
953 Ok(None) => {
954 return Task::ready(Err(anyhow!("No path or contents found for buffer")));
955 }
956 Err(error) => {
957 return Task::ready(Err(error));
958 }
959 };
960
961 let buffer_task = match serialized_editor {
962 SerializedEditor {
963 path: None,
964 contents: Some(contents),
965 language,
966 ..
967 } => cx.spawn(|_, mut cx| {
968 let project = project.clone();
969 async move {
970 let language = if let Some(language_name) = language {
971 let language_registry =
972 project.update(&mut cx, |project, _| project.languages().clone())?;
973
974 // We don't fail here, because we'd rather not set the language if the name changed
975 // than fail to restore the buffer.
976 language_registry
977 .language_for_name(&language_name)
978 .await
979 .ok()
980 } else {
981 None
982 };
983
984 // First create the empty buffer
985 let buffer = project.update(&mut cx, |project, cx| {
986 project.create_local_buffer("", language, cx)
987 })?;
988
989 // Then set the text so that the dirty bit is set correctly
990 buffer.update(&mut cx, |buffer, cx| {
991 buffer.set_text(contents, cx);
992 })?;
993
994 anyhow::Ok(buffer)
995 }
996 }),
997 SerializedEditor {
998 path: Some(path),
999 contents,
1000 mtime,
1001 ..
1002 } => {
1003 let project_item = project.update(cx, |project, cx| {
1004 let (worktree, path) = project
1005 .find_worktree(&path, cx)
1006 .with_context(|| format!("No worktree for path: {path:?}"))?;
1007 let project_path = ProjectPath {
1008 worktree_id: worktree.read(cx).id(),
1009 path: path.into(),
1010 };
1011
1012 Ok(project.open_path(project_path, cx))
1013 });
1014
1015 project_item
1016 .map(|project_item| {
1017 cx.spawn(|_, mut cx| async move {
1018 let (_, project_item) = project_item.await?;
1019 let buffer = project_item.downcast::<Buffer>().map_err(|_| {
1020 anyhow!("Project item at stored path was not a buffer")
1021 })?;
1022
1023 // This is a bit wasteful: we're loading the whole buffer from
1024 // disk and then overwrite the content.
1025 // But for now, it keeps the implementation of the content serialization
1026 // simple, because we don't have to persist all of the metadata that we get
1027 // by loading the file (git diff base, ...).
1028 if let Some(buffer_text) = contents {
1029 buffer.update(&mut cx, |buffer, cx| {
1030 // If we did restore an mtime, we want to store it on the buffer
1031 // so that the next edit will mark the buffer as dirty/conflicted.
1032 if mtime.is_some() {
1033 buffer.did_reload(
1034 buffer.version(),
1035 buffer.line_ending(),
1036 mtime,
1037 cx,
1038 );
1039 }
1040 buffer.set_text(buffer_text, cx);
1041 })?;
1042 }
1043
1044 Ok(buffer)
1045 })
1046 })
1047 .unwrap_or_else(|error| Task::ready(Err(error)))
1048 }
1049 _ => return Task::ready(Err(anyhow!("No path or contents found for buffer"))),
1050 };
1051
1052 cx.spawn(|pane, mut cx| async move {
1053 let buffer = buffer_task.await?;
1054
1055 pane.update(&mut cx, |_, cx| {
1056 cx.new_view(|cx| {
1057 let mut editor = Editor::for_buffer(buffer, Some(project), cx);
1058
1059 editor.read_scroll_position_from_db(item_id, workspace_id, cx);
1060 editor
1061 })
1062 })
1063 })
1064 }
1065
1066 fn serialize(
1067 &mut self,
1068 workspace: &mut Workspace,
1069 item_id: ItemId,
1070 closing: bool,
1071 cx: &mut ViewContext<Self>,
1072 ) -> Option<Task<Result<()>>> {
1073 let mut serialize_dirty_buffers = self.serialize_dirty_buffers;
1074
1075 let project = self.project.clone()?;
1076 if project.read(cx).visible_worktrees(cx).next().is_none() {
1077 // If we don't have a worktree, we don't serialize, because
1078 // projects without worktrees aren't deserialized.
1079 serialize_dirty_buffers = false;
1080 }
1081
1082 if closing && !serialize_dirty_buffers {
1083 return None;
1084 }
1085
1086 let workspace_id = workspace.database_id()?;
1087
1088 let buffer = self.buffer().read(cx).as_singleton()?;
1089 let path = buffer
1090 .read(cx)
1091 .file()
1092 .map(|file| file.full_path(cx))
1093 .and_then(|full_path| project.read(cx).find_project_path(&full_path, cx))
1094 .and_then(|project_path| project.read(cx).absolute_path(&project_path, cx));
1095
1096 let is_dirty = buffer.read(cx).is_dirty();
1097 let mtime = buffer.read(cx).saved_mtime();
1098
1099 let snapshot = buffer.read(cx).snapshot();
1100
1101 Some(cx.spawn(|_this, cx| async move {
1102 cx.background_executor()
1103 .spawn(async move {
1104 let (contents, language) = if serialize_dirty_buffers && is_dirty {
1105 let contents = snapshot.text();
1106 let language = snapshot.language().map(|lang| lang.name().to_string());
1107 (Some(contents), language)
1108 } else {
1109 (None, None)
1110 };
1111
1112 let editor = SerializedEditor {
1113 path,
1114 contents,
1115 language,
1116 mtime,
1117 };
1118
1119 DB.save_serialized_editor(item_id, workspace_id, editor)
1120 .await
1121 .context("failed to save serialized editor")
1122 })
1123 .await
1124 .context("failed to save contents of buffer")?;
1125
1126 Ok(())
1127 }))
1128 }
1129
1130 fn should_serialize(&self, event: &Self::Event) -> bool {
1131 matches!(
1132 event,
1133 EditorEvent::Saved | EditorEvent::DirtyChanged | EditorEvent::BufferEdited
1134 )
1135 }
1136}
1137
1138impl ProjectItem for Editor {
1139 type Item = Buffer;
1140
1141 fn for_project_item(
1142 project: Model<Project>,
1143 buffer: Model<Buffer>,
1144 cx: &mut ViewContext<Self>,
1145 ) -> Self {
1146 Self::for_buffer(buffer, Some(project), cx)
1147 }
1148}
1149
1150impl EventEmitter<SearchEvent> for Editor {}
1151
1152pub(crate) enum BufferSearchHighlights {}
1153impl SearchableItem for Editor {
1154 type Match = Range<Anchor>;
1155
1156 fn get_matches(&self, _: &mut WindowContext) -> Vec<Range<Anchor>> {
1157 self.background_highlights
1158 .get(&TypeId::of::<BufferSearchHighlights>())
1159 .map_or(Vec::new(), |(_color, ranges)| {
1160 ranges.iter().cloned().collect()
1161 })
1162 }
1163
1164 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
1165 if self
1166 .clear_background_highlights::<BufferSearchHighlights>(cx)
1167 .is_some()
1168 {
1169 cx.emit(SearchEvent::MatchesInvalidated);
1170 }
1171 }
1172
1173 fn update_matches(&mut self, matches: &[Range<Anchor>], cx: &mut ViewContext<Self>) {
1174 let existing_range = self
1175 .background_highlights
1176 .get(&TypeId::of::<BufferSearchHighlights>())
1177 .map(|(_, range)| range.as_ref());
1178 let updated = existing_range != Some(matches);
1179 self.highlight_background::<BufferSearchHighlights>(
1180 matches,
1181 |theme| theme.search_match_background,
1182 cx,
1183 );
1184 if updated {
1185 cx.emit(SearchEvent::MatchesInvalidated);
1186 }
1187 }
1188
1189 fn has_filtered_search_ranges(&mut self) -> bool {
1190 self.has_background_highlights::<SearchWithinRange>()
1191 }
1192
1193 fn toggle_filtered_search_ranges(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
1194 if self.has_filtered_search_ranges() {
1195 self.previous_search_ranges = self
1196 .clear_background_highlights::<SearchWithinRange>(cx)
1197 .map(|(_, ranges)| ranges)
1198 }
1199
1200 if !enabled {
1201 return;
1202 }
1203
1204 let ranges = self.selections.disjoint_anchor_ranges();
1205 if ranges.iter().any(|range| range.start != range.end) {
1206 self.set_search_within_ranges(&ranges, cx);
1207 } else if let Some(previous_search_ranges) = self.previous_search_ranges.take() {
1208 self.set_search_within_ranges(&previous_search_ranges, cx)
1209 }
1210 }
1211
1212 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
1213 let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1214 let snapshot = &self.snapshot(cx).buffer_snapshot;
1215 let selection = self.selections.newest::<usize>(cx);
1216
1217 match setting {
1218 SeedQuerySetting::Never => String::new(),
1219 SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1220 let text: String = snapshot
1221 .text_for_range(selection.start..selection.end)
1222 .collect();
1223 if text.contains('\n') {
1224 String::new()
1225 } else {
1226 text
1227 }
1228 }
1229 SeedQuerySetting::Selection => String::new(),
1230 SeedQuerySetting::Always => {
1231 let (range, kind) = snapshot.surrounding_word(selection.start, true);
1232 if kind == Some(CharKind::Word) {
1233 let text: String = snapshot.text_for_range(range).collect();
1234 if !text.trim().is_empty() {
1235 return text;
1236 }
1237 }
1238 String::new()
1239 }
1240 }
1241 }
1242
1243 fn activate_match(
1244 &mut self,
1245 index: usize,
1246 matches: &[Range<Anchor>],
1247 cx: &mut ViewContext<Self>,
1248 ) {
1249 self.unfold_ranges([matches[index].clone()], false, true, cx);
1250 let range = self.range_for_match(&matches[index]);
1251 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
1252 s.select_ranges([range]);
1253 })
1254 }
1255
1256 fn select_matches(&mut self, matches: &[Self::Match], cx: &mut ViewContext<Self>) {
1257 self.unfold_ranges(matches.to_vec(), false, false, cx);
1258 let mut ranges = Vec::new();
1259 for m in matches {
1260 ranges.push(self.range_for_match(m))
1261 }
1262 self.change_selections(None, cx, |s| s.select_ranges(ranges));
1263 }
1264 fn replace(
1265 &mut self,
1266 identifier: &Self::Match,
1267 query: &SearchQuery,
1268 cx: &mut ViewContext<Self>,
1269 ) {
1270 let text = self.buffer.read(cx);
1271 let text = text.snapshot(cx);
1272 let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1273 let text: Cow<_> = if text.len() == 1 {
1274 text.first().cloned().unwrap().into()
1275 } else {
1276 let joined_chunks = text.join("");
1277 joined_chunks.into()
1278 };
1279
1280 if let Some(replacement) = query.replacement_for(&text) {
1281 self.transact(cx, |this, cx| {
1282 this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1283 });
1284 }
1285 }
1286 fn replace_all(
1287 &mut self,
1288 matches: &mut dyn Iterator<Item = &Self::Match>,
1289 query: &SearchQuery,
1290 cx: &mut ViewContext<Self>,
1291 ) {
1292 let text = self.buffer.read(cx);
1293 let text = text.snapshot(cx);
1294 let mut edits = vec![];
1295 for m in matches {
1296 let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1297 let text: Cow<_> = if text.len() == 1 {
1298 text.first().cloned().unwrap().into()
1299 } else {
1300 let joined_chunks = text.join("");
1301 joined_chunks.into()
1302 };
1303
1304 if let Some(replacement) = query.replacement_for(&text) {
1305 edits.push((m.clone(), Arc::from(&*replacement)));
1306 }
1307 }
1308
1309 if !edits.is_empty() {
1310 self.transact(cx, |this, cx| {
1311 this.edit(edits, cx);
1312 });
1313 }
1314 }
1315 fn match_index_for_direction(
1316 &mut self,
1317 matches: &[Range<Anchor>],
1318 current_index: usize,
1319 direction: Direction,
1320 count: usize,
1321 cx: &mut ViewContext<Self>,
1322 ) -> usize {
1323 let buffer = self.buffer().read(cx).snapshot(cx);
1324 let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1325 self.selections.newest_anchor().head()
1326 } else {
1327 matches[current_index].start
1328 };
1329
1330 let mut count = count % matches.len();
1331 if count == 0 {
1332 return current_index;
1333 }
1334 match direction {
1335 Direction::Next => {
1336 if matches[current_index]
1337 .start
1338 .cmp(¤t_index_position, &buffer)
1339 .is_gt()
1340 {
1341 count -= 1
1342 }
1343
1344 (current_index + count) % matches.len()
1345 }
1346 Direction::Prev => {
1347 if matches[current_index]
1348 .end
1349 .cmp(¤t_index_position, &buffer)
1350 .is_lt()
1351 {
1352 count -= 1;
1353 }
1354
1355 if current_index >= count {
1356 current_index - count
1357 } else {
1358 matches.len() - (count - current_index)
1359 }
1360 }
1361 }
1362 }
1363
1364 fn find_matches(
1365 &mut self,
1366 query: Arc<project::search::SearchQuery>,
1367 cx: &mut ViewContext<Self>,
1368 ) -> Task<Vec<Range<Anchor>>> {
1369 let buffer = self.buffer().read(cx).snapshot(cx);
1370 let search_within_ranges = self
1371 .background_highlights
1372 .get(&TypeId::of::<SearchWithinRange>())
1373 .map_or(vec![], |(_color, ranges)| {
1374 ranges.iter().cloned().collect::<Vec<_>>()
1375 });
1376
1377 cx.background_executor().spawn(async move {
1378 let mut ranges = Vec::new();
1379
1380 if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
1381 let search_within_ranges = if search_within_ranges.is_empty() {
1382 vec![None]
1383 } else {
1384 search_within_ranges
1385 .into_iter()
1386 .map(|range| Some(range.to_offset(&buffer)))
1387 .collect::<Vec<_>>()
1388 };
1389
1390 for range in search_within_ranges {
1391 let buffer = &buffer;
1392 ranges.extend(
1393 query
1394 .search(excerpt_buffer, range.clone())
1395 .await
1396 .into_iter()
1397 .map(|matched_range| {
1398 let offset = range.clone().map(|r| r.start).unwrap_or(0);
1399 buffer.anchor_after(matched_range.start + offset)
1400 ..buffer.anchor_before(matched_range.end + offset)
1401 }),
1402 );
1403 }
1404 } else {
1405 let search_within_ranges = if search_within_ranges.is_empty() {
1406 vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())]
1407 } else {
1408 search_within_ranges
1409 };
1410
1411 for (excerpt_id, search_buffer, search_range) in
1412 buffer.excerpts_in_ranges(search_within_ranges)
1413 {
1414 if !search_range.is_empty() {
1415 ranges.extend(
1416 query
1417 .search(search_buffer, Some(search_range.clone()))
1418 .await
1419 .into_iter()
1420 .map(|match_range| {
1421 let start = search_buffer
1422 .anchor_after(search_range.start + match_range.start);
1423 let end = search_buffer
1424 .anchor_before(search_range.start + match_range.end);
1425 buffer.anchor_in_excerpt(excerpt_id, start).unwrap()
1426 ..buffer.anchor_in_excerpt(excerpt_id, end).unwrap()
1427 }),
1428 );
1429 }
1430 }
1431 };
1432
1433 ranges
1434 })
1435 }
1436
1437 fn active_match_index(
1438 &mut self,
1439 matches: &[Range<Anchor>],
1440 cx: &mut ViewContext<Self>,
1441 ) -> Option<usize> {
1442 active_match_index(
1443 matches,
1444 &self.selections.newest_anchor().head(),
1445 &self.buffer().read(cx).snapshot(cx),
1446 )
1447 }
1448
1449 fn search_bar_visibility_changed(&mut self, _visible: bool, _cx: &mut ViewContext<Self>) {
1450 self.expect_bounds_change = self.last_bounds;
1451 }
1452}
1453
1454pub fn active_match_index(
1455 ranges: &[Range<Anchor>],
1456 cursor: &Anchor,
1457 buffer: &MultiBufferSnapshot,
1458) -> Option<usize> {
1459 if ranges.is_empty() {
1460 None
1461 } else {
1462 match ranges.binary_search_by(|probe| {
1463 if probe.end.cmp(cursor, buffer).is_lt() {
1464 Ordering::Less
1465 } else if probe.start.cmp(cursor, buffer).is_gt() {
1466 Ordering::Greater
1467 } else {
1468 Ordering::Equal
1469 }
1470 }) {
1471 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1472 }
1473 }
1474}
1475
1476pub fn entry_label_color(selected: bool) -> Color {
1477 if selected {
1478 Color::Default
1479 } else {
1480 Color::Muted
1481 }
1482}
1483
1484pub fn entry_git_aware_label_color(
1485 git_status: Option<GitFileStatus>,
1486 ignored: bool,
1487 selected: bool,
1488) -> Color {
1489 if ignored {
1490 Color::Ignored
1491 } else {
1492 match git_status {
1493 Some(GitFileStatus::Added) => Color::Created,
1494 Some(GitFileStatus::Modified) => Color::Modified,
1495 Some(GitFileStatus::Conflict) => Color::Conflict,
1496 None => entry_label_color(selected),
1497 }
1498 }
1499}
1500
1501fn path_for_buffer<'a>(
1502 buffer: &Model<MultiBuffer>,
1503 height: usize,
1504 include_filename: bool,
1505 cx: &'a AppContext,
1506) -> Option<Cow<'a, Path>> {
1507 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1508 path_for_file(file.as_ref(), height, include_filename, cx)
1509}
1510
1511fn path_for_file<'a>(
1512 file: &'a dyn language::File,
1513 mut height: usize,
1514 include_filename: bool,
1515 cx: &'a AppContext,
1516) -> Option<Cow<'a, Path>> {
1517 // Ensure we always render at least the filename.
1518 height += 1;
1519
1520 let mut prefix = file.path().as_ref();
1521 while height > 0 {
1522 if let Some(parent) = prefix.parent() {
1523 prefix = parent;
1524 height -= 1;
1525 } else {
1526 break;
1527 }
1528 }
1529
1530 // Here we could have just always used `full_path`, but that is very
1531 // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1532 // traversed all the way up to the worktree's root.
1533 if height > 0 {
1534 let full_path = file.full_path(cx);
1535 if include_filename {
1536 Some(full_path.into())
1537 } else {
1538 Some(full_path.parent()?.to_path_buf().into())
1539 }
1540 } else {
1541 let mut path = file.path().strip_prefix(prefix).ok()?;
1542 if !include_filename {
1543 path = path.parent()?;
1544 }
1545 Some(path.into())
1546 }
1547}
1548
1549#[cfg(test)]
1550mod tests {
1551 use crate::editor_tests::init_test;
1552
1553 use super::*;
1554 use gpui::{AppContext, VisualTestContext};
1555 use language::{LanguageMatcher, TestFile};
1556 use project::FakeFs;
1557 use std::{
1558 path::{Path, PathBuf},
1559 time::SystemTime,
1560 };
1561
1562 #[gpui::test]
1563 fn test_path_for_file(cx: &mut AppContext) {
1564 let file = TestFile {
1565 path: Path::new("").into(),
1566 root_name: String::new(),
1567 };
1568 assert_eq!(path_for_file(&file, 0, false, cx), None);
1569 }
1570
1571 async fn deserialize_editor(
1572 item_id: ItemId,
1573 workspace_id: WorkspaceId,
1574 workspace: View<Workspace>,
1575 project: Model<Project>,
1576 cx: &mut VisualTestContext,
1577 ) -> View<Editor> {
1578 workspace
1579 .update(cx, |workspace, cx| {
1580 let pane = workspace.active_pane();
1581 pane.update(cx, |_, cx| {
1582 Editor::deserialize(
1583 project.clone(),
1584 workspace.weak_handle(),
1585 workspace_id,
1586 item_id,
1587 cx,
1588 )
1589 })
1590 })
1591 .await
1592 .unwrap()
1593 }
1594
1595 fn rust_language() -> Arc<language::Language> {
1596 Arc::new(language::Language::new(
1597 language::LanguageConfig {
1598 name: "Rust".into(),
1599 matcher: LanguageMatcher {
1600 path_suffixes: vec!["rs".to_string()],
1601 ..Default::default()
1602 },
1603 ..Default::default()
1604 },
1605 Some(tree_sitter_rust::LANGUAGE.into()),
1606 ))
1607 }
1608
1609 #[gpui::test]
1610 async fn test_deserialize(cx: &mut gpui::TestAppContext) {
1611 init_test(cx, |_| {});
1612
1613 let now = SystemTime::now();
1614 let fs = FakeFs::new(cx.executor());
1615 fs.set_next_mtime(now);
1616 fs.insert_file("/file.rs", Default::default()).await;
1617
1618 // Test case 1: Deserialize with path and contents
1619 {
1620 let project = Project::test(fs.clone(), ["/file.rs".as_ref()], cx).await;
1621 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
1622 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1623 let item_id = 1234 as ItemId;
1624
1625 let serialized_editor = SerializedEditor {
1626 path: Some(PathBuf::from("/file.rs")),
1627 contents: Some("fn main() {}".to_string()),
1628 language: Some("Rust".to_string()),
1629 mtime: Some(now),
1630 };
1631
1632 DB.save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
1633 .await
1634 .unwrap();
1635
1636 let deserialized =
1637 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1638
1639 deserialized.update(cx, |editor, cx| {
1640 assert_eq!(editor.text(cx), "fn main() {}");
1641 assert!(editor.is_dirty(cx));
1642 assert!(!editor.has_conflict(cx));
1643 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1644 assert!(buffer.file().is_some());
1645 });
1646 }
1647
1648 // Test case 2: Deserialize with only path
1649 {
1650 let project = Project::test(fs.clone(), ["/file.rs".as_ref()], cx).await;
1651 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
1652
1653 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1654
1655 let item_id = 5678 as ItemId;
1656 let serialized_editor = SerializedEditor {
1657 path: Some(PathBuf::from("/file.rs")),
1658 contents: None,
1659 language: None,
1660 mtime: None,
1661 };
1662
1663 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1664 .await
1665 .unwrap();
1666
1667 let deserialized =
1668 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1669
1670 deserialized.update(cx, |editor, cx| {
1671 assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
1672 assert!(!editor.is_dirty(cx));
1673 assert!(!editor.has_conflict(cx));
1674
1675 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1676 assert!(buffer.file().is_some());
1677 });
1678 }
1679
1680 // Test case 3: Deserialize with no path (untitled buffer, with content and language)
1681 {
1682 let project = Project::test(fs.clone(), ["/file.rs".as_ref()], cx).await;
1683 // Add Rust to the language, so that we can restore the language of the buffer
1684 project.update(cx, |project, _| project.languages().add(rust_language()));
1685
1686 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
1687
1688 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1689
1690 let item_id = 9012 as ItemId;
1691 let serialized_editor = SerializedEditor {
1692 path: None,
1693 contents: Some("hello".to_string()),
1694 language: Some("Rust".to_string()),
1695 mtime: None,
1696 };
1697
1698 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1699 .await
1700 .unwrap();
1701
1702 let deserialized =
1703 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1704
1705 deserialized.update(cx, |editor, cx| {
1706 assert_eq!(editor.text(cx), "hello");
1707 assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
1708
1709 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1710 assert_eq!(
1711 buffer.language().map(|lang| lang.name()),
1712 Some("Rust".into())
1713 ); // Language should be set to Rust
1714 assert!(buffer.file().is_none()); // The buffer should not have an associated file
1715 });
1716 }
1717
1718 // Test case 4: Deserialize with path, content, and old mtime
1719 {
1720 let project = Project::test(fs.clone(), ["/file.rs".as_ref()], cx).await;
1721 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
1722
1723 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1724
1725 let item_id = 9345 as ItemId;
1726 let old_mtime = now
1727 .checked_sub(std::time::Duration::from_secs(60 * 60 * 24))
1728 .unwrap();
1729 let serialized_editor = SerializedEditor {
1730 path: Some(PathBuf::from("/file.rs")),
1731 contents: Some("fn main() {}".to_string()),
1732 language: Some("Rust".to_string()),
1733 mtime: Some(old_mtime),
1734 };
1735
1736 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1737 .await
1738 .unwrap();
1739
1740 let deserialized =
1741 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1742
1743 deserialized.update(cx, |editor, cx| {
1744 assert_eq!(editor.text(cx), "fn main() {}");
1745 assert!(editor.has_conflict(cx)); // The editor should have a conflict
1746 });
1747 }
1748 }
1749}