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::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::ThemeSettings::get_global(cx).buffer_font.clone();
984 Some((self.breadcrumbs_inner(cx)?, Some(font)))
985 } else {
986 None
987 }
988 }
989
990 fn added_to_workspace(
991 &mut self,
992 workspace: &mut Workspace,
993 window: &mut Window,
994 cx: &mut Context<Self>,
995 ) {
996 self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
997 if let Some(workspace_entity) = &workspace.weak_handle().upgrade() {
998 cx.subscribe(
999 workspace_entity,
1000 |editor, _, event: &workspace::Event, _cx| {
1001 if let workspace::Event::ModalOpened = event {
1002 editor.mouse_context_menu.take();
1003 editor.inline_blame_popover.take();
1004 }
1005 },
1006 )
1007 .detach();
1008 }
1009
1010 // Load persisted folds if this editor doesn't already have folds.
1011 // This handles manually-opened files (not workspace restoration).
1012 let display_snapshot = self
1013 .display_map
1014 .update(cx, |display_map, cx| display_map.snapshot(cx));
1015 let has_folds = display_snapshot
1016 .folds_in_range(MultiBufferOffset(0)..display_snapshot.buffer_snapshot().len())
1017 .next()
1018 .is_some();
1019
1020 if !has_folds {
1021 if let Some(workspace_id) = workspace.database_id()
1022 && let Some(file_path) = self.buffer().read(cx).as_singleton().and_then(|buffer| {
1023 project::File::from_dyn(buffer.read(cx).file()).map(|file| file.abs_path(cx))
1024 })
1025 {
1026 self.load_folds_from_db(workspace_id, file_path, window, cx);
1027 }
1028 }
1029 }
1030
1031 fn pane_changed(&mut self, new_pane_id: EntityId, cx: &mut Context<Self>) {
1032 if self
1033 .highlighted_rows
1034 .get(&TypeId::of::<ActiveDebugLine>())
1035 .is_some_and(|lines| !lines.is_empty())
1036 && let Some(breakpoint_store) = self.breakpoint_store.as_ref()
1037 {
1038 breakpoint_store.update(cx, |store, _cx| {
1039 store.set_active_debug_pane_id(new_pane_id);
1040 });
1041 }
1042 }
1043
1044 fn to_item_events(event: &EditorEvent, f: &mut dyn FnMut(ItemEvent)) {
1045 match event {
1046 EditorEvent::Saved | EditorEvent::TitleChanged => {
1047 f(ItemEvent::UpdateTab);
1048 f(ItemEvent::UpdateBreadcrumbs);
1049 }
1050
1051 EditorEvent::Reparsed(_) => {
1052 f(ItemEvent::UpdateBreadcrumbs);
1053 }
1054
1055 EditorEvent::SelectionsChanged { local } if *local => {
1056 f(ItemEvent::UpdateBreadcrumbs);
1057 }
1058
1059 EditorEvent::BreadcrumbsChanged => {
1060 f(ItemEvent::UpdateBreadcrumbs);
1061 }
1062
1063 EditorEvent::DirtyChanged => {
1064 f(ItemEvent::UpdateTab);
1065 }
1066
1067 EditorEvent::BufferEdited => {
1068 f(ItemEvent::Edit);
1069 f(ItemEvent::UpdateBreadcrumbs);
1070 }
1071
1072 EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
1073 f(ItemEvent::Edit);
1074 }
1075
1076 _ => {}
1077 }
1078 }
1079
1080 fn tab_extra_context_menu_actions(
1081 &self,
1082 _window: &mut Window,
1083 cx: &mut Context<Self>,
1084 ) -> Vec<(SharedString, Box<dyn gpui::Action>)> {
1085 let mut actions = Vec::new();
1086
1087 let is_markdown = self
1088 .buffer()
1089 .read(cx)
1090 .as_singleton()
1091 .and_then(|buffer| buffer.read(cx).language())
1092 .is_some_and(|language| language.name().as_ref() == "Markdown");
1093
1094 let is_svg = self
1095 .buffer()
1096 .read(cx)
1097 .as_singleton()
1098 .and_then(|buffer| buffer.read(cx).file())
1099 .is_some_and(|file| {
1100 std::path::Path::new(file.file_name(cx))
1101 .extension()
1102 .is_some_and(|ext| ext.eq_ignore_ascii_case("svg"))
1103 });
1104
1105 if is_markdown {
1106 actions.push((
1107 "Open Markdown Preview".into(),
1108 Box::new(OpenMarkdownPreview) as Box<dyn gpui::Action>,
1109 ));
1110 }
1111
1112 if is_svg {
1113 actions.push((
1114 "Open SVG Preview".into(),
1115 Box::new(OpenSvgPreview) as Box<dyn gpui::Action>,
1116 ));
1117 }
1118
1119 actions
1120 }
1121
1122 fn preserve_preview(&self, cx: &App) -> bool {
1123 self.buffer.read(cx).preserve_preview(cx)
1124 }
1125}
1126
1127impl SerializableItem for Editor {
1128 fn serialized_item_kind() -> &'static str {
1129 "Editor"
1130 }
1131
1132 fn cleanup(
1133 workspace_id: WorkspaceId,
1134 alive_items: Vec<ItemId>,
1135 _window: &mut Window,
1136 cx: &mut App,
1137 ) -> Task<Result<()>> {
1138 workspace::delete_unloaded_items(alive_items, workspace_id, "editors", &DB, cx)
1139 }
1140
1141 fn deserialize(
1142 project: Entity<Project>,
1143 _workspace: WeakEntity<Workspace>,
1144 workspace_id: workspace::WorkspaceId,
1145 item_id: ItemId,
1146 window: &mut Window,
1147 cx: &mut App,
1148 ) -> Task<Result<Entity<Self>>> {
1149 let serialized_editor = match DB
1150 .get_serialized_editor(item_id, workspace_id)
1151 .context("Failed to query editor state")
1152 {
1153 Ok(Some(serialized_editor)) => {
1154 if ProjectSettings::get_global(cx)
1155 .session
1156 .restore_unsaved_buffers
1157 {
1158 serialized_editor
1159 } else {
1160 SerializedEditor {
1161 abs_path: serialized_editor.abs_path,
1162 contents: None,
1163 language: None,
1164 mtime: None,
1165 }
1166 }
1167 }
1168 Ok(None) => {
1169 return Task::ready(Err(anyhow!(
1170 "Unable to deserialize editor: No entry in database for item_id: {item_id} and workspace_id {workspace_id:?}"
1171 )));
1172 }
1173 Err(error) => {
1174 return Task::ready(Err(error));
1175 }
1176 };
1177 log::debug!(
1178 "Deserialized editor {item_id:?} in workspace {workspace_id:?}, {serialized_editor:?}"
1179 );
1180
1181 match serialized_editor {
1182 SerializedEditor {
1183 abs_path: None,
1184 contents: Some(contents),
1185 language,
1186 ..
1187 } => window.spawn(cx, {
1188 let project = project.clone();
1189 async move |cx| {
1190 let language_registry =
1191 project.read_with(cx, |project, _| project.languages().clone());
1192
1193 let language = if let Some(language_name) = language {
1194 // We don't fail here, because we'd rather not set the language if the name changed
1195 // than fail to restore the buffer.
1196 language_registry
1197 .language_for_name(&language_name)
1198 .await
1199 .ok()
1200 } else {
1201 None
1202 };
1203
1204 // First create the empty buffer
1205 let buffer = project
1206 .update(cx, |project, cx| project.create_buffer(language, true, cx))
1207 .await
1208 .context("Failed to create buffer while deserializing editor")?;
1209
1210 // Then set the text so that the dirty bit is set correctly
1211 buffer.update(cx, |buffer, cx| {
1212 buffer.set_language_registry(language_registry);
1213 buffer.set_text(contents, cx);
1214 if let Some(entry) = buffer.peek_undo_stack() {
1215 buffer.forget_transaction(entry.transaction_id());
1216 }
1217 });
1218
1219 cx.update(|window, cx| {
1220 cx.new(|cx| {
1221 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1222
1223 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1224 editor
1225 })
1226 })
1227 }
1228 }),
1229 SerializedEditor {
1230 abs_path: Some(abs_path),
1231 contents,
1232 mtime,
1233 ..
1234 } => {
1235 let opened_buffer = project.update(cx, |project, cx| {
1236 let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1237 let project_path = ProjectPath {
1238 worktree_id: worktree.read(cx).id(),
1239 path: path,
1240 };
1241 Some(project.open_path(project_path, cx))
1242 });
1243
1244 match opened_buffer {
1245 Some(opened_buffer) => window.spawn(cx, async move |cx| {
1246 let (_, buffer) = opened_buffer
1247 .await
1248 .context("Failed to open path in project")?;
1249
1250 if let Some(contents) = contents {
1251 buffer.update(cx, |buffer, cx| {
1252 restore_serialized_buffer_contents(buffer, contents, mtime, cx);
1253 });
1254 }
1255
1256 cx.update(|window, cx| {
1257 cx.new(|cx| {
1258 let mut editor =
1259 Editor::for_buffer(buffer, Some(project), window, cx);
1260
1261 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1262 editor
1263 })
1264 })
1265 }),
1266 None => {
1267 // File is not in any worktree (e.g., opened as a standalone file).
1268 // Open the buffer directly via the project rather than through
1269 // workspace.open_abs_path(), which has the side effect of adding
1270 // the item to a pane. The caller (deserialize_to) will add the
1271 // returned item to the correct pane.
1272 window.spawn(cx, async move |cx| {
1273 let buffer = project
1274 .update(cx, |project, cx| project.open_local_buffer(&abs_path, cx))
1275 .await
1276 .with_context(|| {
1277 format!("Failed to open buffer for {abs_path:?}")
1278 })?;
1279
1280 if let Some(contents) = contents {
1281 buffer.update(cx, |buffer, cx| {
1282 restore_serialized_buffer_contents(buffer, contents, mtime, cx);
1283 });
1284 }
1285
1286 cx.update(|window, cx| {
1287 cx.new(|cx| {
1288 let mut editor =
1289 Editor::for_buffer(buffer, Some(project), window, cx);
1290 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1291 editor
1292 })
1293 })
1294 })
1295 }
1296 }
1297 }
1298 SerializedEditor {
1299 abs_path: None,
1300 contents: None,
1301 ..
1302 } => window.spawn(cx, async move |cx| {
1303 let buffer = project
1304 .update(cx, |project, cx| project.create_buffer(None, true, cx))
1305 .await
1306 .context("Failed to create buffer")?;
1307
1308 cx.update(|window, cx| {
1309 cx.new(|cx| {
1310 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1311
1312 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1313 editor
1314 })
1315 })
1316 }),
1317 }
1318 }
1319
1320 fn serialize(
1321 &mut self,
1322 workspace: &mut Workspace,
1323 item_id: ItemId,
1324 closing: bool,
1325 window: &mut Window,
1326 cx: &mut Context<Self>,
1327 ) -> Option<Task<Result<()>>> {
1328 let buffer_serialization = self.buffer_serialization?;
1329 let project = self.project.clone()?;
1330
1331 let serialize_dirty_buffers = match buffer_serialization {
1332 // Always serialize dirty buffers, including for worktree-less windows.
1333 // This enables hot-exit functionality for empty windows and single files.
1334 BufferSerialization::All => true,
1335 BufferSerialization::NonDirtyBuffers => false,
1336 };
1337
1338 if closing && !serialize_dirty_buffers {
1339 return None;
1340 }
1341
1342 let workspace_id = workspace.database_id()?;
1343
1344 let buffer = self.buffer().read(cx).as_singleton()?;
1345
1346 let abs_path = buffer.read(cx).file().and_then(|file| {
1347 let worktree_id = file.worktree_id(cx);
1348 project
1349 .read(cx)
1350 .worktree_for_id(worktree_id, cx)
1351 .map(|worktree| worktree.read(cx).absolutize(file.path()))
1352 .or_else(|| {
1353 let full_path = file.full_path(cx);
1354 let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1355 project.read(cx).absolute_path(&project_path, cx)
1356 })
1357 });
1358
1359 let is_dirty = buffer.read(cx).is_dirty();
1360 let mtime = buffer.read(cx).saved_mtime();
1361
1362 let snapshot = buffer.read(cx).snapshot();
1363
1364 Some(cx.spawn_in(window, async move |_this, cx| {
1365 cx.background_spawn(async move {
1366 let (contents, language) = if serialize_dirty_buffers && is_dirty {
1367 let contents = snapshot.text();
1368 let language = snapshot.language().map(|lang| lang.name().to_string());
1369 (Some(contents), language)
1370 } else {
1371 (None, None)
1372 };
1373
1374 let editor = SerializedEditor {
1375 abs_path,
1376 contents,
1377 language,
1378 mtime,
1379 };
1380 log::debug!("Serializing editor {item_id:?} in workspace {workspace_id:?}");
1381 DB.save_serialized_editor(item_id, workspace_id, editor)
1382 .await
1383 .context("failed to save serialized editor")
1384 })
1385 .await
1386 .context("failed to save contents of buffer")?;
1387
1388 Ok(())
1389 }))
1390 }
1391
1392 fn should_serialize(&self, event: &Self::Event) -> bool {
1393 self.should_serialize_buffer()
1394 && matches!(
1395 event,
1396 EditorEvent::Saved | EditorEvent::DirtyChanged | EditorEvent::BufferEdited
1397 )
1398 }
1399}
1400
1401#[derive(Debug, Default)]
1402struct EditorRestorationData {
1403 entries: HashMap<PathBuf, RestorationData>,
1404}
1405
1406#[derive(Default, Debug)]
1407pub struct RestorationData {
1408 pub scroll_position: (BufferRow, gpui::Point<ScrollOffset>),
1409 pub folds: Vec<Range<Point>>,
1410 pub selections: Vec<Range<Point>>,
1411}
1412
1413impl ProjectItem for Editor {
1414 type Item = Buffer;
1415
1416 fn project_item_kind() -> Option<ProjectItemKind> {
1417 Some(ProjectItemKind("Editor"))
1418 }
1419
1420 fn for_project_item(
1421 project: Entity<Project>,
1422 pane: Option<&Pane>,
1423 buffer: Entity<Buffer>,
1424 window: &mut Window,
1425 cx: &mut Context<Self>,
1426 ) -> Self {
1427 let mut editor = Self::for_buffer(buffer.clone(), Some(project), window, cx);
1428
1429 if let Some((excerpt_id, _, snapshot)) =
1430 editor.buffer().read(cx).snapshot(cx).as_singleton()
1431 && WorkspaceSettings::get(None, cx).restore_on_file_reopen
1432 && let Some(restoration_data) = Self::project_item_kind()
1433 .and_then(|kind| pane.as_ref()?.project_item_restoration_data.get(&kind))
1434 .and_then(|data| data.downcast_ref::<EditorRestorationData>())
1435 .and_then(|data| {
1436 let file = project::File::from_dyn(buffer.read(cx).file())?;
1437 data.entries.get(&file.abs_path(cx))
1438 })
1439 {
1440 if !restoration_data.folds.is_empty() {
1441 editor.fold_ranges(
1442 clip_ranges(&restoration_data.folds, snapshot),
1443 false,
1444 window,
1445 cx,
1446 );
1447 }
1448 if !restoration_data.selections.is_empty() {
1449 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1450 s.select_ranges(clip_ranges(&restoration_data.selections, snapshot));
1451 });
1452 }
1453 let (top_row, offset) = restoration_data.scroll_position;
1454 let anchor =
1455 Anchor::in_buffer(excerpt_id, snapshot.anchor_before(Point::new(top_row, 0)));
1456 editor.set_scroll_anchor(ScrollAnchor { anchor, offset }, window, cx);
1457 }
1458
1459 editor
1460 }
1461
1462 fn for_broken_project_item(
1463 abs_path: &Path,
1464 is_local: bool,
1465 e: &anyhow::Error,
1466 window: &mut Window,
1467 cx: &mut App,
1468 ) -> Option<InvalidItemView> {
1469 Some(InvalidItemView::new(abs_path, is_local, e, window, cx))
1470 }
1471}
1472
1473fn clip_ranges<'a>(
1474 original: impl IntoIterator<Item = &'a Range<Point>> + 'a,
1475 snapshot: &'a BufferSnapshot,
1476) -> Vec<Range<Point>> {
1477 original
1478 .into_iter()
1479 .map(|range| {
1480 snapshot.clip_point(range.start, Bias::Left)
1481 ..snapshot.clip_point(range.end, Bias::Right)
1482 })
1483 .collect()
1484}
1485
1486impl EventEmitter<SearchEvent> for Editor {}
1487
1488impl Editor {
1489 pub fn update_restoration_data(
1490 &self,
1491 cx: &mut Context<Self>,
1492 write: impl for<'a> FnOnce(&'a mut RestorationData) + 'static,
1493 ) {
1494 if self.mode.is_minimap() || !WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1495 return;
1496 }
1497
1498 let editor = cx.entity();
1499 cx.defer(move |cx| {
1500 editor.update(cx, |editor, cx| {
1501 let kind = Editor::project_item_kind()?;
1502 let pane = editor.workspace()?.read(cx).pane_for(&cx.entity())?;
1503 let buffer = editor.buffer().read(cx).as_singleton()?;
1504 let file_abs_path = project::File::from_dyn(buffer.read(cx).file())?.abs_path(cx);
1505 pane.update(cx, |pane, _| {
1506 let data = pane
1507 .project_item_restoration_data
1508 .entry(kind)
1509 .or_insert_with(|| Box::new(EditorRestorationData::default()) as Box<_>);
1510 let data = match data.downcast_mut::<EditorRestorationData>() {
1511 Some(data) => data,
1512 None => {
1513 *data = Box::new(EditorRestorationData::default());
1514 data.downcast_mut::<EditorRestorationData>()
1515 .expect("just written the type downcasted to")
1516 }
1517 };
1518
1519 let data = data.entries.entry(file_abs_path).or_default();
1520 write(data);
1521 Some(())
1522 })
1523 });
1524 });
1525 }
1526}
1527
1528impl SearchableItem for Editor {
1529 type Match = Range<Anchor>;
1530
1531 fn get_matches(&self, _window: &mut Window, _: &mut App) -> (Vec<Range<Anchor>>, SearchToken) {
1532 (
1533 self.background_highlights
1534 .get(&HighlightKey::BufferSearchHighlights)
1535 .map_or(Vec::new(), |(_color, ranges)| {
1536 ranges.iter().cloned().collect()
1537 }),
1538 SearchToken::default(),
1539 )
1540 }
1541
1542 fn clear_matches(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1543 if self
1544 .clear_background_highlights(HighlightKey::BufferSearchHighlights, cx)
1545 .is_some()
1546 {
1547 cx.emit(SearchEvent::MatchesInvalidated);
1548 }
1549 }
1550
1551 fn update_matches(
1552 &mut self,
1553 matches: &[Range<Anchor>],
1554 active_match_index: Option<usize>,
1555 _token: SearchToken,
1556 _: &mut Window,
1557 cx: &mut Context<Self>,
1558 ) {
1559 let existing_range = self
1560 .background_highlights
1561 .get(&HighlightKey::BufferSearchHighlights)
1562 .map(|(_, range)| range.as_ref());
1563 let updated = existing_range != Some(matches);
1564 self.highlight_background(
1565 HighlightKey::BufferSearchHighlights,
1566 matches,
1567 move |index, theme| {
1568 if active_match_index == Some(*index) {
1569 theme.colors().search_active_match_background
1570 } else {
1571 theme.colors().search_match_background
1572 }
1573 },
1574 cx,
1575 );
1576 if updated {
1577 cx.emit(SearchEvent::MatchesInvalidated);
1578 }
1579 }
1580
1581 fn has_filtered_search_ranges(&mut self) -> bool {
1582 self.has_background_highlights(HighlightKey::SearchWithinRange)
1583 }
1584
1585 fn toggle_filtered_search_ranges(
1586 &mut self,
1587 enabled: Option<FilteredSearchRange>,
1588 _: &mut Window,
1589 cx: &mut Context<Self>,
1590 ) {
1591 if self.has_filtered_search_ranges() {
1592 self.previous_search_ranges = self
1593 .clear_background_highlights(HighlightKey::SearchWithinRange, cx)
1594 .map(|(_, ranges)| ranges)
1595 }
1596
1597 if let Some(range) = enabled {
1598 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1599
1600 if ranges.iter().any(|s| s.start != s.end) {
1601 self.set_search_within_ranges(&ranges, cx);
1602 } else if let Some(previous_search_ranges) = self.previous_search_ranges.take()
1603 && range != FilteredSearchRange::Selection
1604 {
1605 self.set_search_within_ranges(&previous_search_ranges, cx);
1606 }
1607 }
1608 }
1609
1610 fn supported_options(&self) -> SearchOptions {
1611 if self.in_project_search {
1612 SearchOptions {
1613 case: true,
1614 word: true,
1615 regex: true,
1616 replacement: false,
1617 selection: false,
1618 find_in_results: true,
1619 }
1620 } else {
1621 SearchOptions {
1622 case: true,
1623 word: true,
1624 regex: true,
1625 replacement: true,
1626 selection: true,
1627 find_in_results: false,
1628 }
1629 }
1630 }
1631
1632 fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
1633 let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1634 let snapshot = self.snapshot(window, cx);
1635 let selection = self.selections.newest_adjusted(&snapshot.display_snapshot);
1636 let buffer_snapshot = snapshot.buffer_snapshot();
1637
1638 match setting {
1639 SeedQuerySetting::Never => String::new(),
1640 SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1641 let text: String = buffer_snapshot
1642 .text_for_range(selection.start..selection.end)
1643 .collect();
1644 if text.contains('\n') {
1645 String::new()
1646 } else {
1647 text
1648 }
1649 }
1650 SeedQuerySetting::Selection => String::new(),
1651 SeedQuerySetting::Always => {
1652 let (range, kind) = buffer_snapshot
1653 .surrounding_word(selection.start, Some(CharScopeContext::Completion));
1654 if kind == Some(CharKind::Word) {
1655 let text: String = buffer_snapshot.text_for_range(range).collect();
1656 if !text.trim().is_empty() {
1657 return text;
1658 }
1659 }
1660 String::new()
1661 }
1662 }
1663 }
1664
1665 fn activate_match(
1666 &mut self,
1667 index: usize,
1668 matches: &[Range<Anchor>],
1669 _token: SearchToken,
1670 window: &mut Window,
1671 cx: &mut Context<Self>,
1672 ) {
1673 self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1674 let range = self.range_for_match(&matches[index]);
1675 let autoscroll = if EditorSettings::get_global(cx).search.center_on_match {
1676 Autoscroll::center()
1677 } else {
1678 Autoscroll::fit()
1679 };
1680 self.change_selections(SelectionEffects::scroll(autoscroll), window, cx, |s| {
1681 s.select_ranges([range]);
1682 })
1683 }
1684
1685 fn select_matches(
1686 &mut self,
1687 matches: &[Self::Match],
1688 _token: SearchToken,
1689 window: &mut Window,
1690 cx: &mut Context<Self>,
1691 ) {
1692 self.unfold_ranges(matches, false, false, cx);
1693 self.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1694 s.select_ranges(matches.iter().cloned())
1695 });
1696 }
1697 fn replace(
1698 &mut self,
1699 identifier: &Self::Match,
1700 query: &SearchQuery,
1701 _token: SearchToken,
1702 window: &mut Window,
1703 cx: &mut Context<Self>,
1704 ) {
1705 let text = self.buffer.read(cx);
1706 let text = text.snapshot(cx);
1707 let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1708 let text: Cow<_> = if text.len() == 1 {
1709 text.first().cloned().unwrap().into()
1710 } else {
1711 let joined_chunks = text.join("");
1712 joined_chunks.into()
1713 };
1714
1715 if let Some(replacement) = query.replacement_for(&text) {
1716 self.transact(window, cx, |this, _, cx| {
1717 this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1718 });
1719 }
1720 }
1721 fn replace_all(
1722 &mut self,
1723 matches: &mut dyn Iterator<Item = &Self::Match>,
1724 query: &SearchQuery,
1725 _token: SearchToken,
1726 window: &mut Window,
1727 cx: &mut Context<Self>,
1728 ) {
1729 let text = self.buffer.read(cx);
1730 let text = text.snapshot(cx);
1731 let mut edits = vec![];
1732
1733 // A regex might have replacement variables so we cannot apply
1734 // the same replacement to all matches
1735 if query.is_regex() {
1736 edits = matches
1737 .filter_map(|m| {
1738 let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1739
1740 let text: Cow<_> = if text.len() == 1 {
1741 text.first().cloned().unwrap().into()
1742 } else {
1743 let joined_chunks = text.join("");
1744 joined_chunks.into()
1745 };
1746
1747 query
1748 .replacement_for(&text)
1749 .map(|replacement| (m.clone(), Arc::from(&*replacement)))
1750 })
1751 .collect();
1752 } else if let Some(replacement) = query.replacement().map(Arc::<str>::from) {
1753 edits = matches.map(|m| (m.clone(), replacement.clone())).collect();
1754 }
1755
1756 if !edits.is_empty() {
1757 self.transact(window, cx, |this, _, cx| {
1758 this.edit(edits, cx);
1759 });
1760 }
1761 }
1762 fn match_index_for_direction(
1763 &mut self,
1764 matches: &[Range<Anchor>],
1765 current_index: usize,
1766 direction: Direction,
1767 count: usize,
1768 _token: SearchToken,
1769 _: &mut Window,
1770 cx: &mut Context<Self>,
1771 ) -> usize {
1772 let buffer = self.buffer().read(cx).snapshot(cx);
1773 let current_index_position = if self.selections.disjoint_anchors_arc().len() == 1 {
1774 self.selections.newest_anchor().head()
1775 } else {
1776 matches[current_index].start
1777 };
1778
1779 let mut count = count % matches.len();
1780 if count == 0 {
1781 return current_index;
1782 }
1783 match direction {
1784 Direction::Next => {
1785 if matches[current_index]
1786 .start
1787 .cmp(¤t_index_position, &buffer)
1788 .is_gt()
1789 {
1790 count -= 1
1791 }
1792
1793 (current_index + count) % matches.len()
1794 }
1795 Direction::Prev => {
1796 if matches[current_index]
1797 .end
1798 .cmp(¤t_index_position, &buffer)
1799 .is_lt()
1800 {
1801 count -= 1;
1802 }
1803
1804 if current_index >= count {
1805 current_index - count
1806 } else {
1807 matches.len() - (count - current_index)
1808 }
1809 }
1810 }
1811 }
1812
1813 fn find_matches(
1814 &mut self,
1815 query: Arc<project::search::SearchQuery>,
1816 _: &mut Window,
1817 cx: &mut Context<Self>,
1818 ) -> Task<Vec<Range<Anchor>>> {
1819 let buffer = self.buffer().read(cx).snapshot(cx);
1820 let search_within_ranges = self
1821 .background_highlights
1822 .get(&HighlightKey::SearchWithinRange)
1823 .map_or(vec![], |(_color, ranges)| {
1824 ranges.iter().cloned().collect::<Vec<_>>()
1825 });
1826
1827 cx.background_spawn(async move {
1828 let mut ranges = Vec::new();
1829
1830 let search_within_ranges = if search_within_ranges.is_empty() {
1831 vec![buffer.anchor_before(MultiBufferOffset(0))..buffer.anchor_after(buffer.len())]
1832 } else {
1833 search_within_ranges
1834 };
1835
1836 for range in search_within_ranges {
1837 for (search_buffer, search_range, excerpt_id, deleted_hunk_anchor) in
1838 buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1839 {
1840 ranges.extend(
1841 query
1842 .search(
1843 search_buffer,
1844 Some(search_range.start.0..search_range.end.0),
1845 )
1846 .await
1847 .into_iter()
1848 .map(|match_range| {
1849 if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
1850 let start = search_buffer
1851 .anchor_after(search_range.start + match_range.start);
1852 let end = search_buffer
1853 .anchor_before(search_range.start + match_range.end);
1854 deleted_hunk_anchor.with_diff_base_anchor(start)
1855 ..deleted_hunk_anchor.with_diff_base_anchor(end)
1856 } else {
1857 let start = search_buffer
1858 .anchor_after(search_range.start + match_range.start);
1859 let end = search_buffer
1860 .anchor_before(search_range.start + match_range.end);
1861 Anchor::range_in_buffer(excerpt_id, start..end)
1862 }
1863 }),
1864 );
1865 }
1866 }
1867
1868 ranges
1869 })
1870 }
1871
1872 fn active_match_index(
1873 &mut self,
1874 direction: Direction,
1875 matches: &[Range<Anchor>],
1876 _token: SearchToken,
1877 _: &mut Window,
1878 cx: &mut Context<Self>,
1879 ) -> Option<usize> {
1880 active_match_index(
1881 direction,
1882 matches,
1883 &self.selections.newest_anchor().head(),
1884 &self.buffer().read(cx).snapshot(cx),
1885 )
1886 }
1887
1888 fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
1889 self.expect_bounds_change = self.last_bounds;
1890 }
1891
1892 fn set_search_is_case_sensitive(
1893 &mut self,
1894 case_sensitive: Option<bool>,
1895 _cx: &mut Context<Self>,
1896 ) {
1897 self.select_next_is_case_sensitive = case_sensitive;
1898 }
1899}
1900
1901pub fn active_match_index(
1902 direction: Direction,
1903 ranges: &[Range<Anchor>],
1904 cursor: &Anchor,
1905 buffer: &MultiBufferSnapshot,
1906) -> Option<usize> {
1907 if ranges.is_empty() {
1908 None
1909 } else {
1910 let r = ranges.binary_search_by(|probe| {
1911 if probe.end.cmp(cursor, buffer).is_lt() {
1912 Ordering::Less
1913 } else if probe.start.cmp(cursor, buffer).is_gt() {
1914 Ordering::Greater
1915 } else {
1916 Ordering::Equal
1917 }
1918 });
1919 match direction {
1920 Direction::Prev => match r {
1921 Ok(i) => Some(i),
1922 Err(i) => Some(i.saturating_sub(1)),
1923 },
1924 Direction::Next => match r {
1925 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1926 },
1927 }
1928 }
1929}
1930
1931pub fn entry_label_color(selected: bool) -> Color {
1932 if selected {
1933 Color::Default
1934 } else {
1935 Color::Muted
1936 }
1937}
1938
1939pub fn entry_diagnostic_aware_icon_name_and_color(
1940 diagnostic_severity: Option<DiagnosticSeverity>,
1941) -> Option<(IconName, Color)> {
1942 match diagnostic_severity {
1943 Some(DiagnosticSeverity::ERROR) => Some((IconName::Close, Color::Error)),
1944 Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1945 _ => None,
1946 }
1947}
1948
1949pub fn entry_diagnostic_aware_icon_decoration_and_color(
1950 diagnostic_severity: Option<DiagnosticSeverity>,
1951) -> Option<(IconDecorationKind, Color)> {
1952 match diagnostic_severity {
1953 Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1954 Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1955 _ => None,
1956 }
1957}
1958
1959pub fn entry_git_aware_label_color(git_status: GitSummary, ignored: bool, selected: bool) -> Color {
1960 let tracked = git_status.index + git_status.worktree;
1961 if git_status.conflict > 0 {
1962 Color::Conflict
1963 } else if tracked.deleted > 0 {
1964 Color::Deleted
1965 } else if tracked.modified > 0 {
1966 Color::Modified
1967 } else if tracked.added > 0 || git_status.untracked > 0 {
1968 Color::Created
1969 } else if ignored {
1970 Color::Ignored
1971 } else {
1972 entry_label_color(selected)
1973 }
1974}
1975
1976fn path_for_buffer<'a>(
1977 buffer: &Entity<MultiBuffer>,
1978 height: usize,
1979 include_filename: bool,
1980 cx: &'a App,
1981) -> Option<Cow<'a, str>> {
1982 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1983 path_for_file(file, height, include_filename, cx)
1984}
1985
1986fn path_for_file<'a>(
1987 file: &'a Arc<dyn language::File>,
1988 mut height: usize,
1989 include_filename: bool,
1990 cx: &'a App,
1991) -> Option<Cow<'a, str>> {
1992 if project::File::from_dyn(Some(file)).is_none() {
1993 return None;
1994 }
1995
1996 let file = file.as_ref();
1997 // Ensure we always render at least the filename.
1998 height += 1;
1999
2000 let mut prefix = file.path().as_ref();
2001 while height > 0 {
2002 if let Some(parent) = prefix.parent() {
2003 prefix = parent;
2004 height -= 1;
2005 } else {
2006 break;
2007 }
2008 }
2009
2010 // The full_path method allocates, so avoid calling it if height is zero.
2011 if height > 0 {
2012 let mut full_path = file.full_path(cx);
2013 if !include_filename {
2014 if !full_path.pop() {
2015 return None;
2016 }
2017 }
2018 Some(full_path.to_string_lossy().into_owned().into())
2019 } else {
2020 let mut path = file.path().strip_prefix(prefix).ok()?;
2021 if !include_filename {
2022 path = path.parent()?;
2023 }
2024 Some(path.display(file.path_style(cx)))
2025 }
2026}
2027
2028/// Restores serialized buffer contents by overwriting the buffer with saved text.
2029/// This is somewhat wasteful since we load the whole buffer from disk then overwrite it,
2030/// but keeps implementation simple as we don't need to persist all metadata from loading
2031/// (git diff base, etc.).
2032fn restore_serialized_buffer_contents(
2033 buffer: &mut Buffer,
2034 contents: String,
2035 mtime: Option<MTime>,
2036 cx: &mut Context<Buffer>,
2037) {
2038 // If we did restore an mtime, store it on the buffer so that
2039 // the next edit will mark the buffer as dirty/conflicted.
2040 if mtime.is_some() {
2041 buffer.did_reload(buffer.version(), buffer.line_ending(), mtime, cx);
2042 }
2043 buffer.set_text(contents, cx);
2044 if let Some(entry) = buffer.peek_undo_stack() {
2045 buffer.forget_transaction(entry.transaction_id());
2046 }
2047}
2048
2049#[cfg(test)]
2050mod tests {
2051 use crate::editor_tests::init_test;
2052 use fs::Fs;
2053 use workspace::MultiWorkspace;
2054
2055 use super::*;
2056 use fs::MTime;
2057 use gpui::{App, VisualTestContext};
2058 use language::TestFile;
2059 use project::FakeFs;
2060 use serde_json::json;
2061 use std::path::{Path, PathBuf};
2062 use util::{path, rel_path::RelPath};
2063
2064 #[gpui::test]
2065 fn test_path_for_file(cx: &mut App) {
2066 let file: Arc<dyn language::File> = Arc::new(TestFile {
2067 path: RelPath::empty().into(),
2068 root_name: String::new(),
2069 local_root: None,
2070 });
2071 assert_eq!(path_for_file(&file, 0, false, cx), None);
2072 }
2073
2074 async fn deserialize_editor(
2075 item_id: ItemId,
2076 workspace_id: WorkspaceId,
2077 workspace: Entity<Workspace>,
2078 project: Entity<Project>,
2079 cx: &mut VisualTestContext,
2080 ) -> Entity<Editor> {
2081 workspace
2082 .update_in(cx, |workspace, window, cx| {
2083 let pane = workspace.active_pane();
2084 pane.update(cx, |_, cx| {
2085 Editor::deserialize(
2086 project.clone(),
2087 workspace.weak_handle(),
2088 workspace_id,
2089 item_id,
2090 window,
2091 cx,
2092 )
2093 })
2094 })
2095 .await
2096 .unwrap()
2097 }
2098
2099 #[gpui::test]
2100 async fn test_deserialize(cx: &mut gpui::TestAppContext) {
2101 init_test(cx, |_| {});
2102
2103 let fs = FakeFs::new(cx.executor());
2104 fs.insert_file(path!("/file.rs"), Default::default()).await;
2105
2106 // Test case 1: Deserialize with path and contents
2107 {
2108 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2109 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2110 MultiWorkspace::test_new(project.clone(), window, cx)
2111 });
2112 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2113 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2114 let item_id = 1234 as ItemId;
2115 let mtime = fs
2116 .metadata(Path::new(path!("/file.rs")))
2117 .await
2118 .unwrap()
2119 .unwrap()
2120 .mtime;
2121
2122 let serialized_editor = SerializedEditor {
2123 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2124 contents: Some("fn main() {}".to_string()),
2125 language: Some("Rust".to_string()),
2126 mtime: Some(mtime),
2127 };
2128
2129 DB.save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
2130 .await
2131 .unwrap();
2132
2133 let deserialized =
2134 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2135
2136 deserialized.update(cx, |editor, cx| {
2137 assert_eq!(editor.text(cx), "fn main() {}");
2138 assert!(editor.is_dirty(cx));
2139 assert!(!editor.has_conflict(cx));
2140 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2141 assert!(buffer.file().is_some());
2142 });
2143 }
2144
2145 // Test case 2: Deserialize with only path
2146 {
2147 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2148 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2149 MultiWorkspace::test_new(project.clone(), window, cx)
2150 });
2151 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2152
2153 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2154
2155 let item_id = 5678 as ItemId;
2156 let serialized_editor = SerializedEditor {
2157 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2158 contents: None,
2159 language: None,
2160 mtime: None,
2161 };
2162
2163 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2164 .await
2165 .unwrap();
2166
2167 let deserialized =
2168 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2169
2170 deserialized.update(cx, |editor, cx| {
2171 assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
2172 assert!(!editor.is_dirty(cx));
2173 assert!(!editor.has_conflict(cx));
2174
2175 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2176 assert!(buffer.file().is_some());
2177 });
2178 }
2179
2180 // Test case 3: Deserialize with no path (untitled buffer, with content and language)
2181 {
2182 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2183 // Add Rust to the language, so that we can restore the language of the buffer
2184 project.read_with(cx, |project, _| {
2185 project.languages().add(languages::rust_lang())
2186 });
2187
2188 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2189 MultiWorkspace::test_new(project.clone(), window, cx)
2190 });
2191 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2192
2193 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2194
2195 let item_id = 9012 as ItemId;
2196 let serialized_editor = SerializedEditor {
2197 abs_path: None,
2198 contents: Some("hello".to_string()),
2199 language: Some("Rust".to_string()),
2200 mtime: None,
2201 };
2202
2203 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2204 .await
2205 .unwrap();
2206
2207 let deserialized =
2208 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2209
2210 deserialized.update(cx, |editor, cx| {
2211 assert_eq!(editor.text(cx), "hello");
2212 assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
2213
2214 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2215 assert_eq!(
2216 buffer.language().map(|lang| lang.name()),
2217 Some("Rust".into())
2218 ); // Language should be set to Rust
2219 assert!(buffer.file().is_none()); // The buffer should not have an associated file
2220 });
2221 }
2222
2223 // Test case 4: Deserialize with path, content, and old mtime
2224 {
2225 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2226 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2227 MultiWorkspace::test_new(project.clone(), window, cx)
2228 });
2229 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2230
2231 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2232
2233 let item_id = 9345 as ItemId;
2234 let old_mtime = MTime::from_seconds_and_nanos(0, 50);
2235 let serialized_editor = SerializedEditor {
2236 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2237 contents: Some("fn main() {}".to_string()),
2238 language: Some("Rust".to_string()),
2239 mtime: Some(old_mtime),
2240 };
2241
2242 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2243 .await
2244 .unwrap();
2245
2246 let deserialized =
2247 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2248
2249 deserialized.update(cx, |editor, cx| {
2250 assert_eq!(editor.text(cx), "fn main() {}");
2251 assert!(editor.has_conflict(cx)); // The editor should have a conflict
2252 });
2253 }
2254
2255 // Test case 5: Deserialize with no path, no content, no language, and no old mtime (new, empty, unsaved buffer)
2256 {
2257 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2258 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2259 MultiWorkspace::test_new(project.clone(), window, cx)
2260 });
2261 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2262
2263 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2264
2265 let item_id = 10000 as ItemId;
2266 let serialized_editor = SerializedEditor {
2267 abs_path: None,
2268 contents: None,
2269 language: None,
2270 mtime: None,
2271 };
2272
2273 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2274 .await
2275 .unwrap();
2276
2277 let deserialized =
2278 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2279
2280 deserialized.update(cx, |editor, cx| {
2281 assert_eq!(editor.text(cx), "");
2282 assert!(!editor.is_dirty(cx));
2283 assert!(!editor.has_conflict(cx));
2284
2285 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2286 assert!(buffer.file().is_none());
2287 });
2288 }
2289
2290 // Test case 6: Deserialize with path and contents in an empty workspace (no worktree)
2291 // This tests the hot-exit scenario where a file is opened in an empty workspace
2292 // and has unsaved changes that should be restored.
2293 {
2294 let fs = FakeFs::new(cx.executor());
2295 fs.insert_file(path!("/standalone.rs"), "original content".into())
2296 .await;
2297
2298 // Create an empty project with no worktrees
2299 let project = Project::test(fs.clone(), [], cx).await;
2300 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2301 MultiWorkspace::test_new(project.clone(), window, cx)
2302 });
2303 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2304
2305 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2306 let item_id = 11000 as ItemId;
2307
2308 let mtime = fs
2309 .metadata(Path::new(path!("/standalone.rs")))
2310 .await
2311 .unwrap()
2312 .unwrap()
2313 .mtime;
2314
2315 // Simulate serialized state: file with unsaved changes
2316 let serialized_editor = SerializedEditor {
2317 abs_path: Some(PathBuf::from(path!("/standalone.rs"))),
2318 contents: Some("modified content".to_string()),
2319 language: Some("Rust".to_string()),
2320 mtime: Some(mtime),
2321 };
2322
2323 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2324 .await
2325 .unwrap();
2326
2327 let deserialized =
2328 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2329
2330 deserialized.update(cx, |editor, cx| {
2331 // The editor should have the serialized contents, not the disk contents
2332 assert_eq!(editor.text(cx), "modified content");
2333 assert!(editor.is_dirty(cx));
2334 assert!(!editor.has_conflict(cx));
2335
2336 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2337 assert!(buffer.file().is_some());
2338 });
2339 }
2340 }
2341
2342 // Regression test for https://github.com/zed-industries/zed/issues/35947
2343 // Verifies that deserializing a non-worktree editor does not add the item
2344 // to any pane as a side effect.
2345 #[gpui::test]
2346 async fn test_deserialize_non_worktree_file_does_not_add_to_pane(
2347 cx: &mut gpui::TestAppContext,
2348 ) {
2349 init_test(cx, |_| {});
2350
2351 let fs = FakeFs::new(cx.executor());
2352 fs.insert_tree(path!("/outside"), json!({ "settings.json": "{}" }))
2353 .await;
2354
2355 // Project with a different root — settings.json is NOT in any worktree
2356 let project = Project::test(fs.clone(), [], cx).await;
2357 let (multi_workspace, cx) =
2358 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2359 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2360
2361 let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2362 let item_id = 99999 as ItemId;
2363
2364 let serialized_editor = SerializedEditor {
2365 abs_path: Some(PathBuf::from(path!("/outside/settings.json"))),
2366 contents: None,
2367 language: None,
2368 mtime: None,
2369 };
2370
2371 DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2372 .await
2373 .unwrap();
2374
2375 // Count items in all panes before deserialization
2376 let pane_items_before = workspace.read_with(cx, |workspace, cx| {
2377 workspace
2378 .panes()
2379 .iter()
2380 .map(|pane| pane.read(cx).items_len())
2381 .sum::<usize>()
2382 });
2383
2384 let deserialized =
2385 deserialize_editor(item_id, workspace_id, workspace.clone(), project, cx).await;
2386
2387 cx.run_until_parked();
2388
2389 // The editor should exist and have the file
2390 deserialized.update(cx, |editor, cx| {
2391 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2392 assert!(buffer.file().is_some());
2393 });
2394
2395 // No items should have been added to any pane as a side effect
2396 let pane_items_after = workspace.read_with(cx, |workspace, cx| {
2397 workspace
2398 .panes()
2399 .iter()
2400 .map(|pane| pane.read(cx).items_len())
2401 .sum::<usize>()
2402 });
2403
2404 assert_eq!(
2405 pane_items_before, pane_items_after,
2406 "Editor::deserialize should not add items to panes as a side effect"
2407 );
2408 }
2409}