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