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