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