1use crate::{
2 Anchor, Autoscroll, BufferSerialization, Capability, Editor, EditorEvent, EditorSettings,
3 ExcerptId, ExcerptRange, FormatTarget, MultiBuffer, MultiBufferSnapshot, NavigationData,
4 ReportEditorEvent, SearchWithinRange, SelectionEffects, ToPoint as _,
5 display_map::HighlightKey,
6 editor_settings::SeedQuerySetting,
7 persistence::{DB, SerializedEditor},
8 scroll::{ScrollAnchor, ScrollOffset},
9};
10use anyhow::{Context as _, Result, anyhow};
11use collections::{HashMap, HashSet};
12use file_icons::FileIcons;
13use futures::future::try_join_all;
14use git::status::GitSummary;
15use gpui::{
16 AnyElement, App, AsyncWindowContext, Context, Entity, EntityId, EventEmitter, IntoElement,
17 ParentElement, Pixels, SharedString, Styled, Task, WeakEntity, Window, point,
18};
19use language::{
20 Bias, Buffer, BufferRow, CharKind, CharScopeContext, DiskState, LocalFile, Point,
21 SelectionGoal, proto::serialize_anchor as serialize_text_anchor,
22};
23use lsp::DiagnosticSeverity;
24use multi_buffer::MultiBufferOffset;
25use project::{
26 File, Project, ProjectItem as _, ProjectPath, lsp_store::FormatTrigger,
27 project_settings::ProjectSettings, search::SearchQuery,
28};
29use rpc::proto::{self, update_view};
30use settings::Settings;
31use std::{
32 any::TypeId,
33 borrow::Cow,
34 cmp::{self, Ordering},
35 iter,
36 ops::Range,
37 path::{Path, PathBuf},
38 sync::Arc,
39};
40use text::{BufferId, BufferSnapshot, Selection};
41use theme::{Theme, ThemeSettings};
42use ui::{IconDecorationKind, prelude::*};
43use util::{ResultExt, TryFutureExt, paths::PathExt};
44use workspace::{
45 CollaboratorId, ItemId, ItemNavHistory, ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
46 invalid_item_view::InvalidItemView,
47 item::{FollowableItem, Item, ItemBufferKind, ItemEvent, ProjectItem, SaveOptions},
48 searchable::{
49 Direction, FilteredSearchRange, SearchEvent, SearchableItem, SearchableItemHandle,
50 },
51};
52use workspace::{
53 OpenOptions,
54 item::{Dedup, ItemSettings, SerializableItem, TabContentParams},
55};
56use workspace::{
57 OpenVisible, Pane, WorkspaceSettings,
58 item::{BreadcrumbText, FollowEvent, ProjectItemKind},
59 searchable::SearchOptions,
60};
61
62pub const MAX_TAB_TITLE_LEN: usize = 24;
63
64impl FollowableItem for Editor {
65 fn remote_id(&self) -> Option<ViewId> {
66 self.remote_id
67 }
68
69 fn from_state_proto(
70 workspace: Entity<Workspace>,
71 remote_id: ViewId,
72 state: &mut Option<proto::view::Variant>,
73 window: &mut Window,
74 cx: &mut App,
75 ) -> Option<Task<Result<Entity<Self>>>> {
76 let project = workspace.read(cx).project().to_owned();
77 let Some(proto::view::Variant::Editor(_)) = state else {
78 return None;
79 };
80 let Some(proto::view::Variant::Editor(state)) = state.take() else {
81 unreachable!()
82 };
83
84 let buffer_ids = state
85 .excerpts
86 .iter()
87 .map(|excerpt| excerpt.buffer_id)
88 .collect::<HashSet<_>>();
89 let buffers = project.update(cx, |project, cx| {
90 buffer_ids
91 .iter()
92 .map(|id| BufferId::new(*id).map(|id| project.open_buffer_by_id(id, cx)))
93 .collect::<Result<Vec<_>>>()
94 });
95
96 Some(window.spawn(cx, async move |cx| {
97 let mut buffers = futures::future::try_join_all(buffers?)
98 .await
99 .debug_assert_ok("leaders don't share views for unshared buffers")?;
100
101 let editor = cx.update(|window, cx| {
102 let multibuffer = cx.new(|cx| {
103 let mut multibuffer;
104 if state.singleton && buffers.len() == 1 {
105 multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
106 } else {
107 multibuffer = MultiBuffer::new(project.read(cx).capability());
108 let mut sorted_excerpts = state.excerpts.clone();
109 sorted_excerpts.sort_by_key(|e| e.id);
110 let sorted_excerpts = sorted_excerpts.into_iter().peekable();
111
112 for excerpt in sorted_excerpts {
113 let Ok(buffer_id) = BufferId::new(excerpt.buffer_id) else {
114 continue;
115 };
116
117 let mut insert_position = ExcerptId::min();
118 for e in &state.excerpts {
119 if e.id == excerpt.id {
120 break;
121 }
122 if e.id < excerpt.id {
123 insert_position = ExcerptId::from_proto(e.id);
124 }
125 }
126
127 let buffer =
128 buffers.iter().find(|b| b.read(cx).remote_id() == buffer_id);
129
130 let Some(excerpt) = deserialize_excerpt_range(excerpt) else {
131 continue;
132 };
133
134 let Some(buffer) = buffer else { continue };
135
136 multibuffer.insert_excerpts_with_ids_after(
137 insert_position,
138 buffer.clone(),
139 [excerpt],
140 cx,
141 );
142 }
143 };
144
145 if let Some(title) = &state.title {
146 multibuffer = multibuffer.with_title(title.clone())
147 }
148
149 multibuffer
150 });
151
152 cx.new(|cx| {
153 let mut editor =
154 Editor::for_multibuffer(multibuffer, Some(project.clone()), window, cx);
155 editor.remote_id = Some(remote_id);
156 editor
157 })
158 })?;
159
160 update_editor_from_message(
161 editor.downgrade(),
162 project,
163 proto::update_view::Editor {
164 selections: state.selections,
165 pending_selection: state.pending_selection,
166 scroll_top_anchor: state.scroll_top_anchor,
167 scroll_x: state.scroll_x,
168 scroll_y: state.scroll_y,
169 ..Default::default()
170 },
171 cx,
172 )
173 .await?;
174
175 Ok(editor)
176 }))
177 }
178
179 fn set_leader_id(
180 &mut self,
181 leader_id: Option<CollaboratorId>,
182 window: &mut Window,
183 cx: &mut Context<Self>,
184 ) {
185 self.leader_id = leader_id;
186 if self.leader_id.is_some() {
187 self.buffer.update(cx, |buffer, cx| {
188 buffer.remove_active_selections(cx);
189 });
190 } else if self.focus_handle.is_focused(window) {
191 self.buffer.update(cx, |buffer, cx| {
192 buffer.set_active_selections(
193 &self.selections.disjoint_anchors_arc(),
194 self.selections.line_mode(),
195 self.cursor_shape,
196 cx,
197 );
198 });
199 }
200 cx.notify();
201 }
202
203 fn to_state_proto(&self, _: &Window, cx: &App) -> Option<proto::view::Variant> {
204 let buffer = self.buffer.read(cx);
205 if buffer
206 .as_singleton()
207 .and_then(|buffer| buffer.read(cx).file())
208 .is_some_and(|file| file.is_private())
209 {
210 return None;
211 }
212
213 let scroll_anchor = self.scroll_manager.anchor();
214 let excerpts = buffer
215 .read(cx)
216 .excerpts()
217 .map(|(id, buffer, range)| proto::Excerpt {
218 id: id.to_proto(),
219 buffer_id: buffer.remote_id().into(),
220 context_start: Some(serialize_text_anchor(&range.context.start)),
221 context_end: Some(serialize_text_anchor(&range.context.end)),
222 primary_start: Some(serialize_text_anchor(&range.primary.start)),
223 primary_end: Some(serialize_text_anchor(&range.primary.end)),
224 })
225 .collect();
226 let snapshot = buffer.snapshot(cx);
227
228 Some(proto::view::Variant::Editor(proto::view::Editor {
229 singleton: buffer.is_singleton(),
230 title: buffer.explicit_title().map(ToOwned::to_owned),
231 excerpts,
232 scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor, &snapshot)),
233 scroll_x: scroll_anchor.offset.x,
234 scroll_y: scroll_anchor.offset.y,
235 selections: self
236 .selections
237 .disjoint_anchors_arc()
238 .iter()
239 .map(|s| serialize_selection(s, &snapshot))
240 .collect(),
241 pending_selection: self
242 .selections
243 .pending_anchor()
244 .as_ref()
245 .map(|s| serialize_selection(s, &snapshot)),
246 }))
247 }
248
249 fn to_follow_event(event: &EditorEvent) -> Option<workspace::item::FollowEvent> {
250 match event {
251 EditorEvent::Edited { .. } => Some(FollowEvent::Unfollow),
252 EditorEvent::SelectionsChanged { local }
253 | EditorEvent::ScrollPositionChanged { local, .. } => {
254 if *local {
255 Some(FollowEvent::Unfollow)
256 } else {
257 None
258 }
259 }
260 _ => None,
261 }
262 }
263
264 fn add_event_to_update_proto(
265 &self,
266 event: &EditorEvent,
267 update: &mut Option<proto::update_view::Variant>,
268 _: &Window,
269 cx: &App,
270 ) -> bool {
271 let update =
272 update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
273
274 match update {
275 proto::update_view::Variant::Editor(update) => match event {
276 EditorEvent::ExcerptsAdded {
277 buffer,
278 predecessor,
279 excerpts,
280 } => {
281 let buffer_id = buffer.read(cx).remote_id();
282 let mut excerpts = excerpts.iter();
283 if let Some((id, range)) = excerpts.next() {
284 update.inserted_excerpts.push(proto::ExcerptInsertion {
285 previous_excerpt_id: Some(predecessor.to_proto()),
286 excerpt: serialize_excerpt(buffer_id, id, range),
287 });
288 update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
289 proto::ExcerptInsertion {
290 previous_excerpt_id: None,
291 excerpt: serialize_excerpt(buffer_id, id, range),
292 }
293 }))
294 }
295 true
296 }
297 EditorEvent::ExcerptsRemoved { ids, .. } => {
298 update
299 .deleted_excerpts
300 .extend(ids.iter().copied().map(ExcerptId::to_proto));
301 true
302 }
303 EditorEvent::ScrollPositionChanged { autoscroll, .. } if !autoscroll => {
304 let snapshot = self.buffer.read(cx).snapshot(cx);
305 let scroll_anchor = self.scroll_manager.anchor();
306 update.scroll_top_anchor =
307 Some(serialize_anchor(&scroll_anchor.anchor, &snapshot));
308 update.scroll_x = scroll_anchor.offset.x;
309 update.scroll_y = scroll_anchor.offset.y;
310 true
311 }
312 EditorEvent::SelectionsChanged { .. } => {
313 let snapshot = self.buffer.read(cx).snapshot(cx);
314 update.selections = self
315 .selections
316 .disjoint_anchors_arc()
317 .iter()
318 .map(|s| serialize_selection(s, &snapshot))
319 .collect();
320 update.pending_selection = self
321 .selections
322 .pending_anchor()
323 .as_ref()
324 .map(|s| serialize_selection(s, &snapshot));
325 true
326 }
327 _ => false,
328 },
329 }
330 }
331
332 fn apply_update_proto(
333 &mut self,
334 project: &Entity<Project>,
335 message: update_view::Variant,
336 window: &mut Window,
337 cx: &mut Context<Self>,
338 ) -> Task<Result<()>> {
339 let update_view::Variant::Editor(message) = message;
340 let project = project.clone();
341 cx.spawn_in(window, async move |this, cx| {
342 update_editor_from_message(this, project, message, cx).await
343 })
344 }
345
346 fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
347 true
348 }
349
350 fn dedup(&self, existing: &Self, _: &Window, cx: &App) -> Option<Dedup> {
351 let self_singleton = self.buffer.read(cx).as_singleton()?;
352 let other_singleton = existing.buffer.read(cx).as_singleton()?;
353 if self_singleton == other_singleton {
354 Some(Dedup::KeepExisting)
355 } else {
356 None
357 }
358 }
359
360 fn update_agent_location(
361 &mut self,
362 location: language::Anchor,
363 window: &mut Window,
364 cx: &mut Context<Self>,
365 ) {
366 let buffer = self.buffer.read(cx);
367 let buffer = buffer.read(cx);
368 let Some(position) = buffer.as_singleton_anchor(location) else {
369 return;
370 };
371 let selection = Selection {
372 id: 0,
373 reversed: false,
374 start: position,
375 end: position,
376 goal: SelectionGoal::None,
377 };
378 drop(buffer);
379 self.set_selections_from_remote(vec![selection], None, window, cx);
380 self.request_autoscroll_remotely(Autoscroll::fit(), cx);
381 }
382}
383
384async fn update_editor_from_message(
385 this: WeakEntity<Editor>,
386 project: Entity<Project>,
387 message: proto::update_view::Editor,
388 cx: &mut AsyncWindowContext,
389) -> Result<()> {
390 // Open all of the buffers of which excerpts were added to the editor.
391 let inserted_excerpt_buffer_ids = message
392 .inserted_excerpts
393 .iter()
394 .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
395 .collect::<HashSet<_>>();
396 let inserted_excerpt_buffers = project.update(cx, |project, cx| {
397 inserted_excerpt_buffer_ids
398 .into_iter()
399 .map(|id| BufferId::new(id).map(|id| project.open_buffer_by_id(id, cx)))
400 .collect::<Result<Vec<_>>>()
401 })??;
402 let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
403
404 // Update the editor's excerpts.
405 this.update(cx, |editor, cx| {
406 editor.buffer.update(cx, |multibuffer, cx| {
407 let mut removed_excerpt_ids = message
408 .deleted_excerpts
409 .into_iter()
410 .map(ExcerptId::from_proto)
411 .collect::<Vec<_>>();
412 removed_excerpt_ids.sort_by({
413 let multibuffer = multibuffer.read(cx);
414 move |a, b| a.cmp(b, &multibuffer)
415 });
416
417 let mut insertions = message.inserted_excerpts.into_iter().peekable();
418 while let Some(insertion) = insertions.next() {
419 let Some(excerpt) = insertion.excerpt else {
420 continue;
421 };
422 let Some(previous_excerpt_id) = insertion.previous_excerpt_id else {
423 continue;
424 };
425 let buffer_id = BufferId::new(excerpt.buffer_id)?;
426 let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
427 continue;
428 };
429
430 let adjacent_excerpts = iter::from_fn(|| {
431 let insertion = insertions.peek()?;
432 if insertion.previous_excerpt_id.is_none()
433 && insertion.excerpt.as_ref()?.buffer_id == u64::from(buffer_id)
434 {
435 insertions.next()?.excerpt
436 } else {
437 None
438 }
439 });
440
441 multibuffer.insert_excerpts_with_ids_after(
442 ExcerptId::from_proto(previous_excerpt_id),
443 buffer,
444 [excerpt]
445 .into_iter()
446 .chain(adjacent_excerpts)
447 .filter_map(deserialize_excerpt_range),
448 cx,
449 );
450 }
451
452 multibuffer.remove_excerpts(removed_excerpt_ids, cx);
453 anyhow::Ok(())
454 })
455 })??;
456
457 // Deserialize the editor state.
458 let selections = message
459 .selections
460 .into_iter()
461 .filter_map(deserialize_selection)
462 .collect::<Vec<_>>();
463 let pending_selection = message.pending_selection.and_then(deserialize_selection);
464 let scroll_top_anchor = message.scroll_top_anchor.and_then(deserialize_anchor);
465
466 // Wait until the buffer has received all of the operations referenced by
467 // the editor's new state.
468 this.update(cx, |editor, cx| {
469 editor.buffer.update(cx, |buffer, cx| {
470 buffer.wait_for_anchors(
471 selections
472 .iter()
473 .chain(pending_selection.as_ref())
474 .flat_map(|selection| [selection.start, selection.end])
475 .chain(scroll_top_anchor),
476 cx,
477 )
478 })
479 })?
480 .await?;
481
482 // Update the editor's state.
483 this.update_in(cx, |editor, window, cx| {
484 if !selections.is_empty() || pending_selection.is_some() {
485 editor.set_selections_from_remote(selections, pending_selection, window, cx);
486 editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
487 } else if let Some(scroll_top_anchor) = scroll_top_anchor {
488 editor.set_scroll_anchor_remote(
489 ScrollAnchor {
490 anchor: scroll_top_anchor,
491 offset: point(message.scroll_x, message.scroll_y),
492 },
493 window,
494 cx,
495 );
496 }
497 })?;
498 Ok(())
499}
500
501fn serialize_excerpt(
502 buffer_id: BufferId,
503 id: &ExcerptId,
504 range: &ExcerptRange<language::Anchor>,
505) -> Option<proto::Excerpt> {
506 Some(proto::Excerpt {
507 id: id.to_proto(),
508 buffer_id: buffer_id.into(),
509 context_start: Some(serialize_text_anchor(&range.context.start)),
510 context_end: Some(serialize_text_anchor(&range.context.end)),
511 primary_start: Some(serialize_text_anchor(&range.primary.start)),
512 primary_end: Some(serialize_text_anchor(&range.primary.end)),
513 })
514}
515
516fn serialize_selection(
517 selection: &Selection<Anchor>,
518 buffer: &MultiBufferSnapshot,
519) -> proto::Selection {
520 proto::Selection {
521 id: selection.id as u64,
522 start: Some(serialize_anchor(&selection.start, buffer)),
523 end: Some(serialize_anchor(&selection.end, buffer)),
524 reversed: selection.reversed,
525 }
526}
527
528fn serialize_anchor(anchor: &Anchor, buffer: &MultiBufferSnapshot) -> proto::EditorAnchor {
529 proto::EditorAnchor {
530 excerpt_id: buffer.latest_excerpt_id(anchor.excerpt_id).to_proto(),
531 anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
532 }
533}
534
535fn deserialize_excerpt_range(
536 excerpt: proto::Excerpt,
537) -> Option<(ExcerptId, ExcerptRange<language::Anchor>)> {
538 let context = {
539 let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
540 let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
541 start..end
542 };
543 let primary = excerpt
544 .primary_start
545 .zip(excerpt.primary_end)
546 .and_then(|(start, end)| {
547 let start = language::proto::deserialize_anchor(start)?;
548 let end = language::proto::deserialize_anchor(end)?;
549 Some(start..end)
550 })
551 .unwrap_or_else(|| context.clone());
552 Some((
553 ExcerptId::from_proto(excerpt.id),
554 ExcerptRange { context, primary },
555 ))
556}
557
558fn deserialize_selection(selection: proto::Selection) -> Option<Selection<Anchor>> {
559 Some(Selection {
560 id: selection.id as usize,
561 start: deserialize_anchor(selection.start?)?,
562 end: deserialize_anchor(selection.end?)?,
563 reversed: selection.reversed,
564 goal: SelectionGoal::None,
565 })
566}
567
568fn deserialize_anchor(anchor: proto::EditorAnchor) -> Option<Anchor> {
569 let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
570 Some(Anchor::in_buffer(
571 excerpt_id,
572 language::proto::deserialize_anchor(anchor.anchor?)?,
573 ))
574}
575
576impl Item for Editor {
577 type Event = EditorEvent;
578
579 fn act_as_type<'a>(
580 &'a self,
581 type_id: TypeId,
582 self_handle: &'a Entity<Self>,
583 cx: &'a App,
584 ) -> Option<gpui::AnyEntity> {
585 if TypeId::of::<Self>() == type_id {
586 Some(self_handle.clone().into())
587 } else if TypeId::of::<MultiBuffer>() == type_id {
588 Some(self_handle.read(cx).buffer.clone().into())
589 } else {
590 None
591 }
592 }
593
594 fn navigate(
595 &mut self,
596 data: Box<dyn std::any::Any>,
597 window: &mut Window,
598 cx: &mut Context<Self>,
599 ) -> bool {
600 if let Ok(data) = data.downcast::<NavigationData>() {
601 let newest_selection = self.selections.newest::<Point>(&self.display_snapshot(cx));
602 let buffer = self.buffer.read(cx).read(cx);
603 let offset = if buffer.can_resolve(&data.cursor_anchor) {
604 data.cursor_anchor.to_point(&buffer)
605 } else {
606 buffer.clip_point(data.cursor_position, Bias::Left)
607 };
608
609 let mut scroll_anchor = data.scroll_anchor;
610 if !buffer.can_resolve(&scroll_anchor.anchor) {
611 scroll_anchor.anchor = buffer.anchor_before(
612 buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
613 );
614 }
615
616 drop(buffer);
617
618 if newest_selection.head() == offset {
619 false
620 } else {
621 self.set_scroll_anchor(scroll_anchor, window, cx);
622 self.change_selections(
623 SelectionEffects::default().nav_history(false),
624 window,
625 cx,
626 |s| s.select_ranges([offset..offset]),
627 );
628 true
629 }
630 } else {
631 false
632 }
633 }
634
635 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
636 self.buffer()
637 .read(cx)
638 .as_singleton()
639 .and_then(|buffer| buffer.read(cx).file())
640 .and_then(|file| File::from_dyn(Some(file)))
641 .map(|file| {
642 file.worktree
643 .read(cx)
644 .absolutize(&file.path)
645 .compact()
646 .to_string_lossy()
647 .into_owned()
648 .into()
649 })
650 }
651
652 fn telemetry_event_text(&self) -> Option<&'static str> {
653 None
654 }
655
656 fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
657 if let Some(path) = path_for_buffer(&self.buffer, detail, true, cx) {
658 path.to_string().into()
659 } else {
660 // Use the same logic as the displayed title for consistency
661 self.buffer.read(cx).title(cx).to_string().into()
662 }
663 }
664
665 fn suggested_filename(&self, cx: &App) -> SharedString {
666 self.buffer.read(cx).title(cx).to_string().into()
667 }
668
669 fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
670 ItemSettings::get_global(cx)
671 .file_icons
672 .then(|| {
673 path_for_buffer(&self.buffer, 0, true, cx)
674 .and_then(|path| FileIcons::get_icon(Path::new(&*path), cx))
675 })
676 .flatten()
677 .map(Icon::from_path)
678 }
679
680 fn tab_content(&self, params: TabContentParams, _: &Window, cx: &App) -> AnyElement {
681 let label_color = if ItemSettings::get_global(cx).git_status {
682 self.buffer()
683 .read(cx)
684 .as_singleton()
685 .and_then(|buffer| {
686 let buffer = buffer.read(cx);
687 let path = buffer.project_path(cx)?;
688 let buffer_id = buffer.remote_id();
689 let project = self.project()?.read(cx);
690 let entry = project.entry_for_path(&path, cx)?;
691 let (repo, repo_path) = project
692 .git_store()
693 .read(cx)
694 .repository_and_path_for_buffer_id(buffer_id, cx)?;
695 let status = repo.read(cx).status_for_path(&repo_path)?.status;
696
697 Some(entry_git_aware_label_color(
698 status.summary(),
699 entry.is_ignored,
700 params.selected,
701 ))
702 })
703 .unwrap_or_else(|| entry_label_color(params.selected))
704 } else {
705 entry_label_color(params.selected)
706 };
707
708 let description = params.detail.and_then(|detail| {
709 let path = path_for_buffer(&self.buffer, detail, false, cx)?;
710 let description = path.trim();
711
712 if description.is_empty() {
713 return None;
714 }
715
716 Some(util::truncate_and_trailoff(description, MAX_TAB_TITLE_LEN))
717 });
718
719 // Whether the file was saved in the past but is now deleted.
720 let was_deleted: bool = self
721 .buffer()
722 .read(cx)
723 .as_singleton()
724 .and_then(|buffer| buffer.read(cx).file())
725 .is_some_and(|file| file.disk_state() == DiskState::Deleted);
726
727 h_flex()
728 .gap_2()
729 .child(
730 Label::new(self.title(cx).to_string())
731 .color(label_color)
732 .when(params.preview, |this| this.italic())
733 .when(was_deleted, |this| this.strikethrough()),
734 )
735 .when_some(description, |this, description| {
736 this.child(
737 Label::new(description)
738 .size(LabelSize::XSmall)
739 .color(Color::Muted),
740 )
741 })
742 .into_any_element()
743 }
744
745 fn for_each_project_item(
746 &self,
747 cx: &App,
748 f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
749 ) {
750 self.buffer
751 .read(cx)
752 .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
753 }
754
755 fn buffer_kind(&self, cx: &App) -> ItemBufferKind {
756 match self.buffer.read(cx).is_singleton() {
757 true => ItemBufferKind::Singleton,
758 false => ItemBufferKind::Multibuffer,
759 }
760 }
761
762 fn can_save_as(&self, cx: &App) -> bool {
763 self.buffer.read(cx).is_singleton()
764 }
765
766 fn can_split(&self) -> bool {
767 true
768 }
769
770 fn clone_on_split(
771 &self,
772 _workspace_id: Option<WorkspaceId>,
773 window: &mut Window,
774 cx: &mut Context<Self>,
775 ) -> Task<Option<Entity<Editor>>>
776 where
777 Self: Sized,
778 {
779 Task::ready(Some(cx.new(|cx| self.clone(window, cx))))
780 }
781
782 fn set_nav_history(
783 &mut self,
784 history: ItemNavHistory,
785 _window: &mut Window,
786 _: &mut Context<Self>,
787 ) {
788 self.nav_history = Some(history);
789 }
790
791 fn on_removed(&self, cx: &App) {
792 self.report_editor_event(ReportEditorEvent::Closed, None, cx);
793 }
794
795 fn deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
796 let selection = self.selections.newest_anchor();
797 self.push_to_nav_history(selection.head(), None, true, false, cx);
798 }
799
800 fn workspace_deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
801 self.hide_hovered_link(cx);
802 }
803
804 fn is_dirty(&self, cx: &App) -> bool {
805 self.buffer().read(cx).read(cx).is_dirty()
806 }
807
808 fn is_read_only(&self, cx: &App) -> bool {
809 self.read_only(cx)
810 }
811
812 // Note: this mirrors the logic in `Editor::toggle_read_only`, but is reachable
813 // without relying on focus-based action dispatch.
814 fn toggle_read_only(&mut self, window: &mut Window, cx: &mut Context<Self>) {
815 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
816 buffer.update(cx, |buffer, cx| {
817 buffer.set_capability(
818 match buffer.capability() {
819 Capability::ReadWrite => Capability::Read,
820 Capability::Read => Capability::ReadWrite,
821 Capability::ReadOnly => Capability::ReadOnly,
822 },
823 cx,
824 );
825 });
826 }
827 cx.notify();
828 window.refresh();
829 }
830
831 fn has_deleted_file(&self, cx: &App) -> bool {
832 self.buffer().read(cx).read(cx).has_deleted_file()
833 }
834
835 fn has_conflict(&self, cx: &App) -> bool {
836 self.buffer().read(cx).read(cx).has_conflict()
837 }
838
839 fn can_save(&self, cx: &App) -> bool {
840 let buffer = &self.buffer().read(cx);
841 if let Some(buffer) = buffer.as_singleton() {
842 buffer.read(cx).project_path(cx).is_some()
843 } else {
844 true
845 }
846 }
847
848 fn save(
849 &mut self,
850 options: SaveOptions,
851 project: Entity<Project>,
852 window: &mut Window,
853 cx: &mut Context<Self>,
854 ) -> Task<Result<()>> {
855 // Add meta data tracking # of auto saves
856 if options.autosave {
857 self.report_editor_event(ReportEditorEvent::Saved { auto_saved: true }, None, cx);
858 } else {
859 self.report_editor_event(ReportEditorEvent::Saved { auto_saved: false }, None, cx);
860 }
861
862 let buffers = self.buffer().clone().read(cx).all_buffers();
863 let buffers = buffers
864 .into_iter()
865 .map(|handle| handle.read(cx).base_buffer().unwrap_or(handle.clone()))
866 .collect::<HashSet<_>>();
867
868 let buffers_to_save = if self.buffer.read(cx).is_singleton() && !options.autosave {
869 buffers
870 } else {
871 buffers
872 .into_iter()
873 .filter(|buffer| buffer.read(cx).is_dirty())
874 .collect()
875 };
876
877 cx.spawn_in(window, async move |this, cx| {
878 if options.format {
879 this.update_in(cx, |editor, window, cx| {
880 editor.perform_format(
881 project.clone(),
882 FormatTrigger::Save,
883 FormatTarget::Buffers(buffers_to_save.clone()),
884 window,
885 cx,
886 )
887 })?
888 .await?;
889 }
890
891 if !buffers_to_save.is_empty() {
892 project
893 .update(cx, |project, cx| {
894 project.save_buffers(buffers_to_save.clone(), cx)
895 })?
896 .await?;
897 }
898
899 Ok(())
900 })
901 }
902
903 fn save_as(
904 &mut self,
905 project: Entity<Project>,
906 path: ProjectPath,
907 _: &mut Window,
908 cx: &mut Context<Self>,
909 ) -> Task<Result<()>> {
910 let buffer = self
911 .buffer()
912 .read(cx)
913 .as_singleton()
914 .expect("cannot call save_as on an excerpt list");
915
916 let file_extension = path.path.extension().map(|a| a.to_string());
917 self.report_editor_event(
918 ReportEditorEvent::Saved { auto_saved: false },
919 file_extension,
920 cx,
921 );
922
923 project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
924 }
925
926 fn reload(
927 &mut self,
928 project: Entity<Project>,
929 window: &mut Window,
930 cx: &mut Context<Self>,
931 ) -> Task<Result<()>> {
932 let buffer = self.buffer().clone();
933 let buffers = self.buffer.read(cx).all_buffers();
934 let reload_buffers =
935 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
936 cx.spawn_in(window, async move |this, cx| {
937 let transaction = reload_buffers.log_err().await;
938 this.update(cx, |editor, cx| {
939 editor.request_autoscroll(Autoscroll::fit(), cx)
940 })?;
941 buffer
942 .update(cx, |buffer, cx| {
943 if let Some(transaction) = transaction
944 && !buffer.is_singleton()
945 {
946 buffer.push_transaction(&transaction.0, cx);
947 }
948 })
949 .ok();
950 Ok(())
951 })
952 }
953
954 fn as_searchable(
955 &self,
956 handle: &Entity<Self>,
957 _: &App,
958 ) -> Option<Box<dyn SearchableItemHandle>> {
959 Some(Box::new(handle.clone()))
960 }
961
962 fn pixel_position_of_cursor(&self, _: &App) -> Option<gpui::Point<Pixels>> {
963 self.pixel_position_of_newest_cursor
964 }
965
966 fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
967 if self.show_breadcrumbs {
968 ToolbarItemLocation::PrimaryLeft
969 } else {
970 ToolbarItemLocation::Hidden
971 }
972 }
973
974 fn breadcrumbs(&self, variant: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
975 let cursor = self.selections.newest_anchor().head();
976 let multibuffer = self.buffer().read(cx);
977 let (buffer_id, symbols) = multibuffer
978 .read(cx)
979 .symbols_containing(cursor, Some(variant.syntax()))?;
980 let buffer = multibuffer.buffer(buffer_id)?;
981
982 let buffer = buffer.read(cx);
983 let text = self.breadcrumb_header.clone().unwrap_or_else(|| {
984 buffer
985 .snapshot()
986 .resolve_file_path(
987 self.project
988 .as_ref()
989 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
990 .unwrap_or_default(),
991 cx,
992 )
993 .unwrap_or_else(|| {
994 if multibuffer.is_singleton() {
995 multibuffer.title(cx).to_string()
996 } else {
997 "untitled".to_string()
998 }
999 })
1000 });
1001
1002 let settings = ThemeSettings::get_global(cx);
1003
1004 let mut breadcrumbs = vec![BreadcrumbText {
1005 text,
1006 highlights: None,
1007 font: Some(settings.buffer_font.clone()),
1008 }];
1009
1010 breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
1011 text: symbol.text,
1012 highlights: Some(symbol.highlight_ranges),
1013 font: Some(settings.buffer_font.clone()),
1014 }));
1015 Some(breadcrumbs)
1016 }
1017
1018 fn added_to_workspace(
1019 &mut self,
1020 workspace: &mut Workspace,
1021 _window: &mut Window,
1022 cx: &mut Context<Self>,
1023 ) {
1024 self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
1025 if let Some(workspace) = &workspace.weak_handle().upgrade() {
1026 cx.subscribe(workspace, |editor, _, event: &workspace::Event, _cx| {
1027 if let workspace::Event::ModalOpened = event {
1028 editor.mouse_context_menu.take();
1029 editor.inline_blame_popover.take();
1030 }
1031 })
1032 .detach();
1033 }
1034 }
1035
1036 fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
1037 match event {
1038 EditorEvent::Saved | EditorEvent::TitleChanged => {
1039 f(ItemEvent::UpdateTab);
1040 f(ItemEvent::UpdateBreadcrumbs);
1041 }
1042
1043 EditorEvent::Reparsed(_) => {
1044 f(ItemEvent::UpdateBreadcrumbs);
1045 }
1046
1047 EditorEvent::SelectionsChanged { local } if *local => {
1048 f(ItemEvent::UpdateBreadcrumbs);
1049 }
1050
1051 EditorEvent::BreadcrumbsChanged => {
1052 f(ItemEvent::UpdateBreadcrumbs);
1053 }
1054
1055 EditorEvent::DirtyChanged => {
1056 f(ItemEvent::UpdateTab);
1057 }
1058
1059 EditorEvent::BufferEdited => {
1060 f(ItemEvent::Edit);
1061 f(ItemEvent::UpdateBreadcrumbs);
1062 }
1063
1064 EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
1065 f(ItemEvent::Edit);
1066 }
1067
1068 _ => {}
1069 }
1070 }
1071
1072 fn preserve_preview(&self, cx: &App) -> bool {
1073 self.buffer.read(cx).preserve_preview(cx)
1074 }
1075}
1076
1077impl SerializableItem for Editor {
1078 fn serialized_item_kind() -> &'static str {
1079 "Editor"
1080 }
1081
1082 fn cleanup(
1083 workspace_id: WorkspaceId,
1084 alive_items: Vec<ItemId>,
1085 _window: &mut Window,
1086 cx: &mut App,
1087 ) -> Task<Result<()>> {
1088 workspace::delete_unloaded_items(alive_items, workspace_id, "editors", &DB, cx)
1089 }
1090
1091 fn deserialize(
1092 project: Entity<Project>,
1093 workspace: WeakEntity<Workspace>,
1094 workspace_id: workspace::WorkspaceId,
1095 item_id: ItemId,
1096 window: &mut Window,
1097 cx: &mut App,
1098 ) -> Task<Result<Entity<Self>>> {
1099 let serialized_editor = match DB
1100 .get_serialized_editor(item_id, workspace_id)
1101 .context("Failed to query editor state")
1102 {
1103 Ok(Some(serialized_editor)) => {
1104 if ProjectSettings::get_global(cx)
1105 .session
1106 .restore_unsaved_buffers
1107 {
1108 serialized_editor
1109 } else {
1110 SerializedEditor {
1111 abs_path: serialized_editor.abs_path,
1112 contents: None,
1113 language: None,
1114 mtime: None,
1115 }
1116 }
1117 }
1118 Ok(None) => {
1119 return Task::ready(Err(anyhow!(
1120 "Unable to deserialize editor: No entry in database for item_id: {item_id} and workspace_id {workspace_id:?}"
1121 )));
1122 }
1123 Err(error) => {
1124 return Task::ready(Err(error));
1125 }
1126 };
1127 log::debug!(
1128 "Deserialized editor {item_id:?} in workspace {workspace_id:?}, {serialized_editor:?}"
1129 );
1130
1131 match serialized_editor {
1132 SerializedEditor {
1133 abs_path: None,
1134 contents: Some(contents),
1135 language,
1136 ..
1137 } => window.spawn(cx, {
1138 let project = project.clone();
1139 async move |cx| {
1140 let language_registry =
1141 project.read_with(cx, |project, _| project.languages().clone())?;
1142
1143 let language = if let Some(language_name) = language {
1144 // We don't fail here, because we'd rather not set the language if the name changed
1145 // than fail to restore the buffer.
1146 language_registry
1147 .language_for_name(&language_name)
1148 .await
1149 .ok()
1150 } else {
1151 None
1152 };
1153
1154 // First create the empty buffer
1155 let buffer = project
1156 .update(cx, |project, cx| project.create_buffer(true, cx))?
1157 .await
1158 .context("Failed to create buffer while deserializing editor")?;
1159
1160 // Then set the text so that the dirty bit is set correctly
1161 buffer.update(cx, |buffer, cx| {
1162 buffer.set_language_registry(language_registry);
1163 if let Some(language) = language {
1164 buffer.set_language(Some(language), cx);
1165 }
1166 buffer.set_text(contents, cx);
1167 if let Some(entry) = buffer.peek_undo_stack() {
1168 buffer.forget_transaction(entry.transaction_id());
1169 }
1170 })?;
1171
1172 cx.update(|window, cx| {
1173 cx.new(|cx| {
1174 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1175
1176 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1177 editor
1178 })
1179 })
1180 }
1181 }),
1182 SerializedEditor {
1183 abs_path: Some(abs_path),
1184 contents,
1185 mtime,
1186 ..
1187 } => {
1188 let opened_buffer = project.update(cx, |project, cx| {
1189 let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1190 let project_path = ProjectPath {
1191 worktree_id: worktree.read(cx).id(),
1192 path: path,
1193 };
1194 Some(project.open_path(project_path, cx))
1195 });
1196
1197 match opened_buffer {
1198 Some(opened_buffer) => {
1199 window.spawn(cx, async move |cx| {
1200 let (_, buffer) = opened_buffer
1201 .await
1202 .context("Failed to open path in project")?;
1203
1204 // This is a bit wasteful: we're loading the whole buffer from
1205 // disk and then overwrite the content.
1206 // But for now, it keeps the implementation of the content serialization
1207 // simple, because we don't have to persist all of the metadata that we get
1208 // by loading the file (git diff base, ...).
1209 if let Some(buffer_text) = contents {
1210 buffer.update(cx, |buffer, cx| {
1211 // If we did restore an mtime, we want to store it on the buffer
1212 // so that the next edit will mark the buffer as dirty/conflicted.
1213 if mtime.is_some() {
1214 buffer.did_reload(
1215 buffer.version(),
1216 buffer.line_ending(),
1217 mtime,
1218 cx,
1219 );
1220 }
1221 buffer.set_text(buffer_text, cx);
1222 if let Some(entry) = buffer.peek_undo_stack() {
1223 buffer.forget_transaction(entry.transaction_id());
1224 }
1225 })?;
1226 }
1227
1228 cx.update(|window, cx| {
1229 cx.new(|cx| {
1230 let mut editor =
1231 Editor::for_buffer(buffer, Some(project), window, cx);
1232
1233 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1234 editor
1235 })
1236 })
1237 })
1238 }
1239 None => {
1240 let open_by_abs_path = workspace.update(cx, |workspace, cx| {
1241 workspace.open_abs_path(
1242 abs_path.clone(),
1243 OpenOptions {
1244 visible: Some(OpenVisible::None),
1245 ..Default::default()
1246 },
1247 window,
1248 cx,
1249 )
1250 });
1251 window.spawn(cx, async move |cx| {
1252 let editor = open_by_abs_path?.await?.downcast::<Editor>().with_context(|| format!("Failed to downcast to Editor after opening abs path {abs_path:?}"))?;
1253 editor.update_in(cx, |editor, window, cx| {
1254 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1255 })?;
1256 Ok(editor)
1257 })
1258 }
1259 }
1260 }
1261 SerializedEditor {
1262 abs_path: None,
1263 contents: None,
1264 ..
1265 } => window.spawn(cx, async move |cx| {
1266 let buffer = project
1267 .update(cx, |project, cx| project.create_buffer(true, cx))?
1268 .await
1269 .context("Failed to create buffer")?;
1270
1271 cx.update(|window, cx| {
1272 cx.new(|cx| {
1273 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1274
1275 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1276 editor
1277 })
1278 })
1279 }),
1280 }
1281 }
1282
1283 fn serialize(
1284 &mut self,
1285 workspace: &mut Workspace,
1286 item_id: ItemId,
1287 closing: bool,
1288 window: &mut Window,
1289 cx: &mut Context<Self>,
1290 ) -> Option<Task<Result<()>>> {
1291 let buffer_serialization = self.buffer_serialization?;
1292 let project = self.project.clone()?;
1293
1294 let serialize_dirty_buffers = match buffer_serialization {
1295 // If we don't have a worktree, we don't serialize, because
1296 // projects without worktrees aren't deserialized.
1297 BufferSerialization::All => project.read(cx).visible_worktrees(cx).next().is_some(),
1298 BufferSerialization::NonDirtyBuffers => false,
1299 };
1300
1301 if closing && !serialize_dirty_buffers {
1302 return None;
1303 }
1304
1305 let workspace_id = workspace.database_id()?;
1306
1307 let buffer = self.buffer().read(cx).as_singleton()?;
1308
1309 let abs_path = buffer.read(cx).file().and_then(|file| {
1310 let worktree_id = file.worktree_id(cx);
1311 project
1312 .read(cx)
1313 .worktree_for_id(worktree_id, cx)
1314 .map(|worktree| worktree.read(cx).absolutize(file.path()))
1315 .or_else(|| {
1316 let full_path = file.full_path(cx);
1317 let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1318 project.read(cx).absolute_path(&project_path, cx)
1319 })
1320 });
1321
1322 let is_dirty = buffer.read(cx).is_dirty();
1323 let mtime = buffer.read(cx).saved_mtime();
1324
1325 let snapshot = buffer.read(cx).snapshot();
1326
1327 Some(cx.spawn_in(window, async move |_this, cx| {
1328 cx.background_spawn(async move {
1329 let (contents, language) = if serialize_dirty_buffers && is_dirty {
1330 let contents = snapshot.text();
1331 let language = snapshot.language().map(|lang| lang.name().to_string());
1332 (Some(contents), language)
1333 } else {
1334 (None, None)
1335 };
1336
1337 let editor = SerializedEditor {
1338 abs_path,
1339 contents,
1340 language,
1341 mtime,
1342 };
1343 log::debug!("Serializing editor {item_id:?} in workspace {workspace_id:?}");
1344 DB.save_serialized_editor(item_id, workspace_id, editor)
1345 .await
1346 .context("failed to save serialized editor")
1347 })
1348 .await
1349 .context("failed to save contents of buffer")?;
1350
1351 Ok(())
1352 }))
1353 }
1354
1355 fn should_serialize(&self, event: &Self::Event) -> bool {
1356 self.should_serialize_buffer()
1357 && matches!(
1358 event,
1359 EditorEvent::Saved | EditorEvent::DirtyChanged | EditorEvent::BufferEdited
1360 )
1361 }
1362}
1363
1364#[derive(Debug, Default)]
1365struct EditorRestorationData {
1366 entries: HashMap<PathBuf, RestorationData>,
1367}
1368
1369#[derive(Default, Debug)]
1370pub struct RestorationData {
1371 pub scroll_position: (BufferRow, gpui::Point<ScrollOffset>),
1372 pub folds: Vec<Range<Point>>,
1373 pub selections: Vec<Range<Point>>,
1374}
1375
1376impl ProjectItem for Editor {
1377 type Item = Buffer;
1378
1379 fn project_item_kind() -> Option<ProjectItemKind> {
1380 Some(ProjectItemKind("Editor"))
1381 }
1382
1383 fn for_project_item(
1384 project: Entity<Project>,
1385 pane: Option<&Pane>,
1386 buffer: Entity<Buffer>,
1387 window: &mut Window,
1388 cx: &mut Context<Self>,
1389 ) -> Self {
1390 let mut editor = Self::for_buffer(buffer.clone(), Some(project), window, cx);
1391 if let Some((excerpt_id, _, snapshot)) =
1392 editor.buffer().read(cx).snapshot(cx).as_singleton()
1393 && WorkspaceSettings::get(None, cx).restore_on_file_reopen
1394 && let Some(restoration_data) = Self::project_item_kind()
1395 .and_then(|kind| pane.as_ref()?.project_item_restoration_data.get(&kind))
1396 .and_then(|data| data.downcast_ref::<EditorRestorationData>())
1397 .and_then(|data| {
1398 let file = project::File::from_dyn(buffer.read(cx).file())?;
1399 data.entries.get(&file.abs_path(cx))
1400 })
1401 {
1402 editor.fold_ranges(
1403 clip_ranges(&restoration_data.folds, snapshot),
1404 false,
1405 window,
1406 cx,
1407 );
1408 if !restoration_data.selections.is_empty() {
1409 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1410 s.select_ranges(clip_ranges(&restoration_data.selections, snapshot));
1411 });
1412 }
1413 let (top_row, offset) = restoration_data.scroll_position;
1414 let anchor =
1415 Anchor::in_buffer(*excerpt_id, snapshot.anchor_before(Point::new(top_row, 0)));
1416 editor.set_scroll_anchor(ScrollAnchor { anchor, offset }, window, cx);
1417 }
1418
1419 editor
1420 }
1421
1422 fn for_broken_project_item(
1423 abs_path: &Path,
1424 is_local: bool,
1425 e: &anyhow::Error,
1426 window: &mut Window,
1427 cx: &mut App,
1428 ) -> Option<InvalidItemView> {
1429 Some(InvalidItemView::new(abs_path, is_local, e, window, cx))
1430 }
1431}
1432
1433fn clip_ranges<'a>(
1434 original: impl IntoIterator<Item = &'a Range<Point>> + 'a,
1435 snapshot: &'a BufferSnapshot,
1436) -> Vec<Range<Point>> {
1437 original
1438 .into_iter()
1439 .map(|range| {
1440 snapshot.clip_point(range.start, Bias::Left)
1441 ..snapshot.clip_point(range.end, Bias::Right)
1442 })
1443 .collect()
1444}
1445
1446impl EventEmitter<SearchEvent> for Editor {}
1447
1448impl Editor {
1449 pub fn update_restoration_data(
1450 &self,
1451 cx: &mut Context<Self>,
1452 write: impl for<'a> FnOnce(&'a mut RestorationData) + 'static,
1453 ) {
1454 if self.mode.is_minimap() || !WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1455 return;
1456 }
1457
1458 let editor = cx.entity();
1459 cx.defer(move |cx| {
1460 editor.update(cx, |editor, cx| {
1461 let kind = Editor::project_item_kind()?;
1462 let pane = editor.workspace()?.read(cx).pane_for(&cx.entity())?;
1463 let buffer = editor.buffer().read(cx).as_singleton()?;
1464 let file_abs_path = project::File::from_dyn(buffer.read(cx).file())?.abs_path(cx);
1465 pane.update(cx, |pane, _| {
1466 let data = pane
1467 .project_item_restoration_data
1468 .entry(kind)
1469 .or_insert_with(|| Box::new(EditorRestorationData::default()) as Box<_>);
1470 let data = match data.downcast_mut::<EditorRestorationData>() {
1471 Some(data) => data,
1472 None => {
1473 *data = Box::new(EditorRestorationData::default());
1474 data.downcast_mut::<EditorRestorationData>()
1475 .expect("just written the type downcasted to")
1476 }
1477 };
1478
1479 let data = data.entries.entry(file_abs_path).or_default();
1480 write(data);
1481 Some(())
1482 })
1483 });
1484 });
1485 }
1486}
1487
1488pub(crate) enum BufferSearchHighlights {}
1489impl SearchableItem for Editor {
1490 type Match = Range<Anchor>;
1491
1492 fn get_matches(&self, _window: &mut Window, _: &mut App) -> Vec<Range<Anchor>> {
1493 self.background_highlights
1494 .get(&HighlightKey::Type(TypeId::of::<BufferSearchHighlights>()))
1495 .map_or(Vec::new(), |(_color, ranges)| {
1496 ranges.iter().cloned().collect()
1497 })
1498 }
1499
1500 fn clear_matches(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1501 if self
1502 .clear_background_highlights::<BufferSearchHighlights>(cx)
1503 .is_some()
1504 {
1505 cx.emit(SearchEvent::MatchesInvalidated);
1506 }
1507 }
1508
1509 fn update_matches(
1510 &mut self,
1511 matches: &[Range<Anchor>],
1512 active_match_index: Option<usize>,
1513 _: &mut Window,
1514 cx: &mut Context<Self>,
1515 ) {
1516 let existing_range = self
1517 .background_highlights
1518 .get(&HighlightKey::Type(TypeId::of::<BufferSearchHighlights>()))
1519 .map(|(_, range)| range.as_ref());
1520 let updated = existing_range != Some(matches);
1521 self.highlight_background::<BufferSearchHighlights>(
1522 matches,
1523 move |index, theme| {
1524 if active_match_index == Some(*index) {
1525 theme.colors().search_active_match_background
1526 } else {
1527 theme.colors().search_match_background
1528 }
1529 },
1530 cx,
1531 );
1532 if updated {
1533 cx.emit(SearchEvent::MatchesInvalidated);
1534 }
1535 }
1536
1537 fn has_filtered_search_ranges(&mut self) -> bool {
1538 self.has_background_highlights::<SearchWithinRange>()
1539 }
1540
1541 fn toggle_filtered_search_ranges(
1542 &mut self,
1543 enabled: Option<FilteredSearchRange>,
1544 _: &mut Window,
1545 cx: &mut Context<Self>,
1546 ) {
1547 if self.has_filtered_search_ranges() {
1548 self.previous_search_ranges = self
1549 .clear_background_highlights::<SearchWithinRange>(cx)
1550 .map(|(_, ranges)| ranges)
1551 }
1552
1553 if let Some(range) = enabled {
1554 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1555
1556 if ranges.iter().any(|s| s.start != s.end) {
1557 self.set_search_within_ranges(&ranges, cx);
1558 } else if let Some(previous_search_ranges) = self.previous_search_ranges.take()
1559 && range != FilteredSearchRange::Selection
1560 {
1561 self.set_search_within_ranges(&previous_search_ranges, cx);
1562 }
1563 }
1564 }
1565
1566 fn supported_options(&self) -> SearchOptions {
1567 if self.in_project_search {
1568 SearchOptions {
1569 case: true,
1570 word: true,
1571 regex: true,
1572 replacement: false,
1573 selection: false,
1574 find_in_results: true,
1575 }
1576 } else {
1577 SearchOptions {
1578 case: true,
1579 word: true,
1580 regex: true,
1581 replacement: true,
1582 selection: true,
1583 find_in_results: false,
1584 }
1585 }
1586 }
1587
1588 fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
1589 let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1590 let snapshot = self.snapshot(window, cx);
1591 let selection = self.selections.newest_adjusted(&snapshot.display_snapshot);
1592 let buffer_snapshot = snapshot.buffer_snapshot();
1593
1594 match setting {
1595 SeedQuerySetting::Never => String::new(),
1596 SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1597 let text: String = buffer_snapshot
1598 .text_for_range(selection.start..selection.end)
1599 .collect();
1600 if text.contains('\n') {
1601 String::new()
1602 } else {
1603 text
1604 }
1605 }
1606 SeedQuerySetting::Selection => String::new(),
1607 SeedQuerySetting::Always => {
1608 let (range, kind) = buffer_snapshot
1609 .surrounding_word(selection.start, Some(CharScopeContext::Completion));
1610 if kind == Some(CharKind::Word) {
1611 let text: String = buffer_snapshot.text_for_range(range).collect();
1612 if !text.trim().is_empty() {
1613 return text;
1614 }
1615 }
1616 String::new()
1617 }
1618 }
1619 }
1620
1621 fn activate_match(
1622 &mut self,
1623 index: usize,
1624 matches: &[Range<Anchor>],
1625 window: &mut Window,
1626 cx: &mut Context<Self>,
1627 ) {
1628 self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1629 let range = self.range_for_match(&matches[index]);
1630 let autoscroll = if EditorSettings::get_global(cx).search.center_on_match {
1631 Autoscroll::center()
1632 } else {
1633 Autoscroll::fit()
1634 };
1635 self.change_selections(SelectionEffects::scroll(autoscroll), window, cx, |s| {
1636 s.select_ranges([range]);
1637 })
1638 }
1639
1640 fn select_matches(
1641 &mut self,
1642 matches: &[Self::Match],
1643 window: &mut Window,
1644 cx: &mut Context<Self>,
1645 ) {
1646 self.unfold_ranges(matches, false, false, cx);
1647 self.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1648 s.select_ranges(matches.iter().cloned())
1649 });
1650 }
1651 fn replace(
1652 &mut self,
1653 identifier: &Self::Match,
1654 query: &SearchQuery,
1655 window: &mut Window,
1656 cx: &mut Context<Self>,
1657 ) {
1658 let text = self.buffer.read(cx);
1659 let text = text.snapshot(cx);
1660 let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1661 let text: Cow<_> = if text.len() == 1 {
1662 text.first().cloned().unwrap().into()
1663 } else {
1664 let joined_chunks = text.join("");
1665 joined_chunks.into()
1666 };
1667
1668 if let Some(replacement) = query.replacement_for(&text) {
1669 self.transact(window, cx, |this, _, cx| {
1670 this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1671 });
1672 }
1673 }
1674 fn replace_all(
1675 &mut self,
1676 matches: &mut dyn Iterator<Item = &Self::Match>,
1677 query: &SearchQuery,
1678 window: &mut Window,
1679 cx: &mut Context<Self>,
1680 ) {
1681 let text = self.buffer.read(cx);
1682 let text = text.snapshot(cx);
1683 let mut edits = vec![];
1684
1685 for m in matches {
1686 let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1687
1688 let text: Cow<_> = if text.len() == 1 {
1689 text.first().cloned().unwrap().into()
1690 } else {
1691 let joined_chunks = text.join("");
1692 joined_chunks.into()
1693 };
1694
1695 if let Some(replacement) = query.replacement_for(&text) {
1696 edits.push((m.clone(), Arc::from(&*replacement)));
1697 }
1698 }
1699
1700 if !edits.is_empty() {
1701 self.transact(window, cx, |this, _, cx| {
1702 this.edit(edits, cx);
1703 });
1704 }
1705 }
1706 fn match_index_for_direction(
1707 &mut self,
1708 matches: &[Range<Anchor>],
1709 current_index: usize,
1710 direction: Direction,
1711 count: usize,
1712 _: &mut Window,
1713 cx: &mut Context<Self>,
1714 ) -> usize {
1715 let buffer = self.buffer().read(cx).snapshot(cx);
1716 let current_index_position = if self.selections.disjoint_anchors_arc().len() == 1 {
1717 self.selections.newest_anchor().head()
1718 } else {
1719 matches[current_index].start
1720 };
1721
1722 let mut count = count % matches.len();
1723 if count == 0 {
1724 return current_index;
1725 }
1726 match direction {
1727 Direction::Next => {
1728 if matches[current_index]
1729 .start
1730 .cmp(¤t_index_position, &buffer)
1731 .is_gt()
1732 {
1733 count -= 1
1734 }
1735
1736 (current_index + count) % matches.len()
1737 }
1738 Direction::Prev => {
1739 if matches[current_index]
1740 .end
1741 .cmp(¤t_index_position, &buffer)
1742 .is_lt()
1743 {
1744 count -= 1;
1745 }
1746
1747 if current_index >= count {
1748 current_index - count
1749 } else {
1750 matches.len() - (count - current_index)
1751 }
1752 }
1753 }
1754 }
1755
1756 fn find_matches(
1757 &mut self,
1758 query: Arc<project::search::SearchQuery>,
1759 _: &mut Window,
1760 cx: &mut Context<Self>,
1761 ) -> Task<Vec<Range<Anchor>>> {
1762 let buffer = self.buffer().read(cx).snapshot(cx);
1763 let search_within_ranges = self
1764 .background_highlights
1765 .get(&HighlightKey::Type(TypeId::of::<SearchWithinRange>()))
1766 .map_or(vec![], |(_color, ranges)| {
1767 ranges.iter().cloned().collect::<Vec<_>>()
1768 });
1769
1770 cx.background_spawn(async move {
1771 let mut ranges = Vec::new();
1772
1773 let search_within_ranges = if search_within_ranges.is_empty() {
1774 vec![buffer.anchor_before(MultiBufferOffset(0))..buffer.anchor_after(buffer.len())]
1775 } else {
1776 search_within_ranges
1777 };
1778
1779 for range in search_within_ranges {
1780 for (search_buffer, search_range, excerpt_id, deleted_hunk_anchor) in
1781 buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1782 {
1783 ranges.extend(
1784 query
1785 .search(
1786 search_buffer,
1787 Some(search_range.start.0..search_range.end.0),
1788 )
1789 .await
1790 .into_iter()
1791 .map(|match_range| {
1792 if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
1793 let start = search_buffer
1794 .anchor_after(search_range.start + match_range.start);
1795 let end = search_buffer
1796 .anchor_before(search_range.start + match_range.end);
1797 deleted_hunk_anchor.with_diff_base_anchor(start)
1798 ..deleted_hunk_anchor.with_diff_base_anchor(end)
1799 } else {
1800 let start = search_buffer
1801 .anchor_after(search_range.start + match_range.start);
1802 let end = search_buffer
1803 .anchor_before(search_range.start + match_range.end);
1804 Anchor::range_in_buffer(excerpt_id, start..end)
1805 }
1806 }),
1807 );
1808 }
1809 }
1810
1811 ranges
1812 })
1813 }
1814
1815 fn active_match_index(
1816 &mut self,
1817 direction: Direction,
1818 matches: &[Range<Anchor>],
1819 _: &mut Window,
1820 cx: &mut Context<Self>,
1821 ) -> Option<usize> {
1822 active_match_index(
1823 direction,
1824 matches,
1825 &self.selections.newest_anchor().head(),
1826 &self.buffer().read(cx).snapshot(cx),
1827 )
1828 }
1829
1830 fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
1831 self.expect_bounds_change = self.last_bounds;
1832 }
1833
1834 fn set_search_is_case_sensitive(
1835 &mut self,
1836 case_sensitive: Option<bool>,
1837 _cx: &mut Context<Self>,
1838 ) {
1839 self.select_next_is_case_sensitive = case_sensitive;
1840 }
1841}
1842
1843pub fn active_match_index(
1844 direction: Direction,
1845 ranges: &[Range<Anchor>],
1846 cursor: &Anchor,
1847 buffer: &MultiBufferSnapshot,
1848) -> Option<usize> {
1849 if ranges.is_empty() {
1850 None
1851 } else {
1852 let r = ranges.binary_search_by(|probe| {
1853 if probe.end.cmp(cursor, buffer).is_lt() {
1854 Ordering::Less
1855 } else if probe.start.cmp(cursor, buffer).is_gt() {
1856 Ordering::Greater
1857 } else {
1858 Ordering::Equal
1859 }
1860 });
1861 match direction {
1862 Direction::Prev => match r {
1863 Ok(i) => Some(i),
1864 Err(i) => Some(i.saturating_sub(1)),
1865 },
1866 Direction::Next => match r {
1867 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1868 },
1869 }
1870 }
1871}
1872
1873pub fn entry_label_color(selected: bool) -> Color {
1874 if selected {
1875 Color::Default
1876 } else {
1877 Color::Muted
1878 }
1879}
1880
1881pub fn entry_diagnostic_aware_icon_name_and_color(
1882 diagnostic_severity: Option<DiagnosticSeverity>,
1883) -> Option<(IconName, Color)> {
1884 match diagnostic_severity {
1885 Some(DiagnosticSeverity::ERROR) => Some((IconName::Close, Color::Error)),
1886 Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1887 _ => None,
1888 }
1889}
1890
1891pub fn entry_diagnostic_aware_icon_decoration_and_color(
1892 diagnostic_severity: Option<DiagnosticSeverity>,
1893) -> Option<(IconDecorationKind, Color)> {
1894 match diagnostic_severity {
1895 Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1896 Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1897 _ => None,
1898 }
1899}
1900
1901pub fn entry_git_aware_label_color(git_status: GitSummary, ignored: bool, selected: bool) -> Color {
1902 let tracked = git_status.index + git_status.worktree;
1903 if ignored {
1904 Color::Ignored
1905 } else if git_status.conflict > 0 {
1906 Color::Conflict
1907 } else if tracked.modified > 0 {
1908 Color::Modified
1909 } else if tracked.added > 0 || git_status.untracked > 0 {
1910 Color::Created
1911 } else {
1912 entry_label_color(selected)
1913 }
1914}
1915
1916fn path_for_buffer<'a>(
1917 buffer: &Entity<MultiBuffer>,
1918 height: usize,
1919 include_filename: bool,
1920 cx: &'a App,
1921) -> Option<Cow<'a, str>> {
1922 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1923 path_for_file(file, height, include_filename, cx)
1924}
1925
1926fn path_for_file<'a>(
1927 file: &'a Arc<dyn language::File>,
1928 mut height: usize,
1929 include_filename: bool,
1930 cx: &'a App,
1931) -> Option<Cow<'a, str>> {
1932 if project::File::from_dyn(Some(file)).is_none() {
1933 return None;
1934 }
1935
1936 let file = file.as_ref();
1937 // Ensure we always render at least the filename.
1938 height += 1;
1939
1940 let mut prefix = file.path().as_ref();
1941 while height > 0 {
1942 if let Some(parent) = prefix.parent() {
1943 prefix = parent;
1944 height -= 1;
1945 } else {
1946 break;
1947 }
1948 }
1949
1950 // The full_path method allocates, so avoid calling it if height is zero.
1951 if height > 0 {
1952 let mut full_path = file.full_path(cx);
1953 if !include_filename {
1954 if !full_path.pop() {
1955 return None;
1956 }
1957 }
1958 Some(full_path.to_string_lossy().into_owned().into())
1959 } else {
1960 let mut path = file.path().strip_prefix(prefix).ok()?;
1961 if !include_filename {
1962 path = path.parent()?;
1963 }
1964 Some(path.display(file.path_style(cx)))
1965 }
1966}
1967
1968#[cfg(test)]
1969mod tests {
1970 use crate::editor_tests::init_test;
1971 use fs::Fs;
1972
1973 use super::*;
1974 use fs::MTime;
1975 use gpui::{App, VisualTestContext};
1976 use language::TestFile;
1977 use project::FakeFs;
1978 use std::path::{Path, PathBuf};
1979 use util::{path, rel_path::RelPath};
1980
1981 #[gpui::test]
1982 fn test_path_for_file(cx: &mut App) {
1983 let file: Arc<dyn language::File> = Arc::new(TestFile {
1984 path: RelPath::empty().into(),
1985 root_name: String::new(),
1986 local_root: None,
1987 });
1988 assert_eq!(path_for_file(&file, 0, false, cx), None);
1989 }
1990
1991 async fn deserialize_editor(
1992 item_id: ItemId,
1993 workspace_id: WorkspaceId,
1994 workspace: Entity<Workspace>,
1995 project: Entity<Project>,
1996 cx: &mut VisualTestContext,
1997 ) -> Entity<Editor> {
1998 workspace
1999 .update_in(cx, |workspace, window, cx| {
2000 let pane = workspace.active_pane();
2001 pane.update(cx, |_, cx| {
2002 Editor::deserialize(
2003 project.clone(),
2004 workspace.weak_handle(),
2005 workspace_id,
2006 item_id,
2007 window,
2008 cx,
2009 )
2010 })
2011 })
2012 .await
2013 .unwrap()
2014 }
2015
2016 #[gpui::test]
2017 async fn test_deserialize(cx: &mut gpui::TestAppContext) {
2018 init_test(cx, |_| {});
2019
2020 let fs = FakeFs::new(cx.executor());
2021 fs.insert_file(path!("/file.rs"), Default::default()).await;
2022
2023 // Test case 1: Deserialize with path and contents
2024 {
2025 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2026 let (workspace, cx) =
2027 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2028 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2029 let item_id = 1234 as ItemId;
2030 let mtime = fs
2031 .metadata(Path::new(path!("/file.rs")))
2032 .await
2033 .unwrap()
2034 .unwrap()
2035 .mtime;
2036
2037 let serialized_editor = SerializedEditor {
2038 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2039 contents: Some("fn main() {}".to_string()),
2040 language: Some("Rust".to_string()),
2041 mtime: Some(mtime),
2042 };
2043
2044 DB.save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
2045 .await
2046 .unwrap();
2047
2048 let deserialized =
2049 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2050
2051 deserialized.update(cx, |editor, cx| {
2052 assert_eq!(editor.text(cx), "fn main() {}");
2053 assert!(editor.is_dirty(cx));
2054 assert!(!editor.has_conflict(cx));
2055 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2056 assert!(buffer.file().is_some());
2057 });
2058 }
2059
2060 // Test case 2: Deserialize with only path
2061 {
2062 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2063 let (workspace, cx) =
2064 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2065
2066 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2067
2068 let item_id = 5678 as ItemId;
2069 let serialized_editor = SerializedEditor {
2070 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2071 contents: None,
2072 language: None,
2073 mtime: None,
2074 };
2075
2076 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2077 .await
2078 .unwrap();
2079
2080 let deserialized =
2081 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2082
2083 deserialized.update(cx, |editor, cx| {
2084 assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
2085 assert!(!editor.is_dirty(cx));
2086 assert!(!editor.has_conflict(cx));
2087
2088 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2089 assert!(buffer.file().is_some());
2090 });
2091 }
2092
2093 // Test case 3: Deserialize with no path (untitled buffer, with content and language)
2094 {
2095 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2096 // Add Rust to the language, so that we can restore the language of the buffer
2097 project.read_with(cx, |project, _| {
2098 project.languages().add(languages::rust_lang())
2099 });
2100
2101 let (workspace, cx) =
2102 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2103
2104 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2105
2106 let item_id = 9012 as ItemId;
2107 let serialized_editor = SerializedEditor {
2108 abs_path: None,
2109 contents: Some("hello".to_string()),
2110 language: Some("Rust".to_string()),
2111 mtime: None,
2112 };
2113
2114 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2115 .await
2116 .unwrap();
2117
2118 let deserialized =
2119 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2120
2121 deserialized.update(cx, |editor, cx| {
2122 assert_eq!(editor.text(cx), "hello");
2123 assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
2124
2125 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2126 assert_eq!(
2127 buffer.language().map(|lang| lang.name()),
2128 Some("Rust".into())
2129 ); // Language should be set to Rust
2130 assert!(buffer.file().is_none()); // The buffer should not have an associated file
2131 });
2132 }
2133
2134 // Test case 4: Deserialize with path, content, and old mtime
2135 {
2136 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2137 let (workspace, cx) =
2138 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2139
2140 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2141
2142 let item_id = 9345 as ItemId;
2143 let old_mtime = MTime::from_seconds_and_nanos(0, 50);
2144 let serialized_editor = SerializedEditor {
2145 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2146 contents: Some("fn main() {}".to_string()),
2147 language: Some("Rust".to_string()),
2148 mtime: Some(old_mtime),
2149 };
2150
2151 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2152 .await
2153 .unwrap();
2154
2155 let deserialized =
2156 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2157
2158 deserialized.update(cx, |editor, cx| {
2159 assert_eq!(editor.text(cx), "fn main() {}");
2160 assert!(editor.has_conflict(cx)); // The editor should have a conflict
2161 });
2162 }
2163
2164 // Test case 5: Deserialize with no path, no content, no language, and no old mtime (new, empty, unsaved buffer)
2165 {
2166 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2167 let (workspace, cx) =
2168 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2169
2170 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2171
2172 let item_id = 10000 as ItemId;
2173 let serialized_editor = SerializedEditor {
2174 abs_path: None,
2175 contents: None,
2176 language: None,
2177 mtime: None,
2178 };
2179
2180 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2181 .await
2182 .unwrap();
2183
2184 let deserialized =
2185 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2186
2187 deserialized.update(cx, |editor, cx| {
2188 assert_eq!(editor.text(cx), "");
2189 assert!(!editor.is_dirty(cx));
2190 assert!(!editor.has_conflict(cx));
2191
2192 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2193 assert!(buffer.file().is_none());
2194 });
2195 }
2196 }
2197}