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 let multi_buffer = self.buffer().read(cx);
649 if let Some(file) = multi_buffer
650 .as_singleton()
651 .and_then(|buffer| buffer.read(cx).file())
652 .and_then(|file| File::from_dyn(Some(file)))
653 {
654 Some(
655 file.worktree
656 .read(cx)
657 .absolutize(&file.path)
658 .compact()
659 .to_string_lossy()
660 .into_owned()
661 .into(),
662 )
663 } else {
664 let title = multi_buffer.title(cx);
665 (!title.is_empty()).then(|| title.to_string().into())
666 }
667 }
668
669 fn telemetry_event_text(&self) -> Option<&'static str> {
670 None
671 }
672
673 fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
674 if let Some(path) = path_for_buffer(&self.buffer, detail, true, cx) {
675 path.to_string().into()
676 } else {
677 // Use the same logic as the displayed title for consistency
678 self.buffer.read(cx).title(cx).to_string().into()
679 }
680 }
681
682 fn suggested_filename(&self, cx: &App) -> SharedString {
683 self.buffer.read(cx).title(cx).to_string().into()
684 }
685
686 fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
687 ItemSettings::get_global(cx)
688 .file_icons
689 .then(|| {
690 path_for_buffer(&self.buffer, 0, true, cx)
691 .and_then(|path| FileIcons::get_icon(Path::new(&*path), cx))
692 })
693 .flatten()
694 .map(Icon::from_path)
695 }
696
697 fn tab_content(&self, params: TabContentParams, _: &Window, cx: &App) -> AnyElement {
698 let label_color = if ItemSettings::get_global(cx).git_status {
699 self.buffer()
700 .read(cx)
701 .as_singleton()
702 .and_then(|buffer| {
703 let buffer = buffer.read(cx);
704 let path = buffer.project_path(cx)?;
705 let buffer_id = buffer.remote_id();
706 let project = self.project()?.read(cx);
707 let entry = project.entry_for_path(&path, cx)?;
708 let (repo, repo_path) = project
709 .git_store()
710 .read(cx)
711 .repository_and_path_for_buffer_id(buffer_id, cx)?;
712 let status = repo.read(cx).status_for_path(&repo_path)?.status;
713
714 Some(entry_git_aware_label_color(
715 status.summary(),
716 entry.is_ignored,
717 params.selected,
718 ))
719 })
720 .unwrap_or_else(|| entry_label_color(params.selected))
721 } else {
722 entry_label_color(params.selected)
723 };
724
725 let description = params.detail.and_then(|detail| {
726 let path = path_for_buffer(&self.buffer, detail, false, cx)?;
727 let description = path.trim();
728
729 if description.is_empty() {
730 return None;
731 }
732
733 Some(util::truncate_and_trailoff(description, MAX_TAB_TITLE_LEN))
734 });
735
736 // Whether the file was saved in the past but is now deleted.
737 let was_deleted: bool = self
738 .buffer()
739 .read(cx)
740 .as_singleton()
741 .and_then(|buffer| buffer.read(cx).file())
742 .is_some_and(|file| file.disk_state().is_deleted());
743
744 h_flex()
745 .gap_2()
746 .child(
747 Label::new(util::truncate_and_trailoff(
748 &self.title(cx),
749 MAX_TAB_TITLE_LEN,
750 ))
751 .color(label_color)
752 .when(params.preview, |this| this.italic())
753 .when(was_deleted, |this| this.strikethrough()),
754 )
755 .when_some(description, |this, description| {
756 this.child(
757 Label::new(description)
758 .size(LabelSize::XSmall)
759 .color(Color::Muted),
760 )
761 })
762 .into_any_element()
763 }
764
765 fn for_each_project_item(
766 &self,
767 cx: &App,
768 f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
769 ) {
770 self.buffer
771 .read(cx)
772 .for_each_buffer(&mut |buffer| f(buffer.entity_id(), buffer.read(cx)));
773 }
774
775 fn buffer_kind(&self, cx: &App) -> ItemBufferKind {
776 match self.buffer.read(cx).is_singleton() {
777 true => ItemBufferKind::Singleton,
778 false => ItemBufferKind::Multibuffer,
779 }
780 }
781
782 fn can_save_as(&self, cx: &App) -> bool {
783 self.buffer.read(cx).is_singleton()
784 }
785
786 fn can_split(&self) -> bool {
787 true
788 }
789
790 fn clone_on_split(
791 &self,
792 _workspace_id: Option<WorkspaceId>,
793 window: &mut Window,
794 cx: &mut Context<Self>,
795 ) -> Task<Option<Entity<Editor>>>
796 where
797 Self: Sized,
798 {
799 Task::ready(Some(cx.new(|cx| self.clone(window, cx))))
800 }
801
802 fn set_nav_history(
803 &mut self,
804 history: ItemNavHistory,
805 _window: &mut Window,
806 _: &mut Context<Self>,
807 ) {
808 self.nav_history = Some(history);
809 }
810
811 fn on_removed(&self, cx: &mut Context<Self>) {
812 self.report_editor_event(ReportEditorEvent::Closed, None, cx);
813 }
814
815 fn deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
816 let selection = self.selections.newest_anchor();
817 self.push_to_nav_history(selection.head(), None, true, false, cx);
818 }
819
820 fn workspace_deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
821 self.hide_hovered_link(cx);
822 }
823
824 fn is_dirty(&self, cx: &App) -> bool {
825 self.buffer().read(cx).read(cx).is_dirty()
826 }
827
828 fn capability(&self, cx: &App) -> Capability {
829 self.capability(cx)
830 }
831
832 // Note: this mirrors the logic in `Editor::toggle_read_only`, but is reachable
833 // without relying on focus-based action dispatch.
834 fn toggle_read_only(&mut self, window: &mut Window, cx: &mut Context<Self>) {
835 if let Some(buffer) = self.buffer.read(cx).as_singleton() {
836 buffer.update(cx, |buffer, cx| {
837 buffer.set_capability(
838 match buffer.capability() {
839 Capability::ReadWrite => Capability::Read,
840 Capability::Read => Capability::ReadWrite,
841 Capability::ReadOnly => Capability::ReadOnly,
842 },
843 cx,
844 );
845 });
846 }
847 cx.notify();
848 window.refresh();
849 }
850
851 fn has_deleted_file(&self, cx: &App) -> bool {
852 self.buffer().read(cx).read(cx).has_deleted_file()
853 }
854
855 fn has_conflict(&self, cx: &App) -> bool {
856 self.buffer().read(cx).read(cx).has_conflict()
857 }
858
859 fn can_save(&self, cx: &App) -> bool {
860 let buffer = &self.buffer().read(cx);
861 if let Some(buffer) = buffer.as_singleton() {
862 buffer.read(cx).project_path(cx).is_some()
863 } else {
864 true
865 }
866 }
867
868 fn save(
869 &mut self,
870 options: SaveOptions,
871 project: Entity<Project>,
872 window: &mut Window,
873 cx: &mut Context<Self>,
874 ) -> Task<Result<()>> {
875 // Add meta data tracking # of auto saves
876 if options.autosave {
877 self.report_editor_event(ReportEditorEvent::Saved { auto_saved: true }, None, cx);
878 } else {
879 self.report_editor_event(ReportEditorEvent::Saved { auto_saved: false }, None, cx);
880 }
881
882 let buffers = self.buffer().clone().read(cx).all_buffers();
883 let buffers = buffers
884 .into_iter()
885 .map(|handle| handle.read(cx).base_buffer().unwrap_or(handle.clone()))
886 .collect::<HashSet<_>>();
887
888 let buffers_to_save = if self.buffer.read(cx).is_singleton() && !options.autosave {
889 buffers
890 } else {
891 buffers
892 .into_iter()
893 .filter(|buffer| buffer.read(cx).is_dirty())
894 .collect()
895 };
896
897 let format_trigger = if options.force_format {
898 FormatTrigger::Manual
899 } else {
900 FormatTrigger::Save
901 };
902
903 cx.spawn_in(window, async move |this, cx| {
904 if options.format {
905 this.update_in(cx, |editor, window, cx| {
906 editor.perform_format(
907 project.clone(),
908 format_trigger,
909 FormatTarget::Buffers(buffers_to_save.clone()),
910 window,
911 cx,
912 )
913 })?
914 .await?;
915 }
916
917 if !buffers_to_save.is_empty() {
918 project
919 .update(cx, |project, cx| {
920 project.save_buffers(buffers_to_save.clone(), cx)
921 })
922 .await?;
923 }
924
925 Ok(())
926 })
927 }
928
929 fn save_as(
930 &mut self,
931 project: Entity<Project>,
932 path: ProjectPath,
933 _: &mut Window,
934 cx: &mut Context<Self>,
935 ) -> Task<Result<()>> {
936 let buffer = self
937 .buffer()
938 .read(cx)
939 .as_singleton()
940 .expect("cannot call save_as on an excerpt list");
941
942 let file_extension = path.path.extension().map(|a| a.to_string());
943 self.report_editor_event(
944 ReportEditorEvent::Saved { auto_saved: false },
945 file_extension,
946 cx,
947 );
948
949 project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
950 }
951
952 fn reload(
953 &mut self,
954 project: Entity<Project>,
955 window: &mut Window,
956 cx: &mut Context<Self>,
957 ) -> Task<Result<()>> {
958 let buffer = self.buffer().clone();
959 let buffers = self.buffer.read(cx).all_buffers();
960 let reload_buffers =
961 project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
962 cx.spawn_in(window, async move |this, cx| {
963 let transaction = reload_buffers.log_err().await;
964 this.update(cx, |editor, cx| {
965 editor.request_autoscroll(Autoscroll::fit(), cx)
966 })?;
967 buffer.update(cx, |buffer, cx| {
968 if let Some(transaction) = transaction
969 && !buffer.is_singleton()
970 {
971 buffer.push_transaction(&transaction.0, cx);
972 }
973 });
974 Ok(())
975 })
976 }
977
978 fn as_searchable(
979 &self,
980 handle: &Entity<Self>,
981 _: &App,
982 ) -> Option<Box<dyn SearchableItemHandle>> {
983 Some(Box::new(handle.clone()))
984 }
985
986 fn pixel_position_of_cursor(&self, _: &App) -> Option<gpui::Point<Pixels>> {
987 self.pixel_position_of_newest_cursor
988 }
989
990 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
991 if self.show_breadcrumbs && self.buffer().read(cx).is_singleton() {
992 ToolbarItemLocation::PrimaryLeft
993 } else {
994 ToolbarItemLocation::Hidden
995 }
996 }
997
998 // In a non-singleton case, the breadcrumbs are actually shown on sticky file headers of the multibuffer.
999 fn breadcrumbs(&self, cx: &App) -> Option<(Vec<HighlightedText>, Option<Font>)> {
1000 if self.buffer.read(cx).is_singleton() {
1001 let font = theme_settings::ThemeSettings::get_global(cx)
1002 .buffer_font
1003 .clone();
1004 Some((self.breadcrumbs_inner(cx)?, Some(font)))
1005 } else {
1006 None
1007 }
1008 }
1009
1010 fn added_to_workspace(
1011 &mut self,
1012 workspace: &mut Workspace,
1013 window: &mut Window,
1014 cx: &mut Context<Self>,
1015 ) {
1016 self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
1017 if let Some(workspace_entity) = &workspace.weak_handle().upgrade() {
1018 cx.subscribe(
1019 workspace_entity,
1020 |editor, _, event: &workspace::Event, _cx| {
1021 if let workspace::Event::ModalOpened = event {
1022 editor.mouse_context_menu.take();
1023 editor.inline_blame_popover.take();
1024 }
1025 },
1026 )
1027 .detach();
1028 }
1029
1030 // Load persisted folds if this editor doesn't already have folds.
1031 // This handles manually-opened files (not workspace restoration).
1032 let display_snapshot = self
1033 .display_map
1034 .update(cx, |display_map, cx| display_map.snapshot(cx));
1035 let has_folds = display_snapshot
1036 .folds_in_range(MultiBufferOffset(0)..display_snapshot.buffer_snapshot().len())
1037 .next()
1038 .is_some();
1039
1040 if !has_folds {
1041 if let Some(workspace_id) = workspace.database_id()
1042 && let Some(file_path) = self.buffer().read(cx).as_singleton().and_then(|buffer| {
1043 project::File::from_dyn(buffer.read(cx).file()).map(|file| file.abs_path(cx))
1044 })
1045 {
1046 self.load_folds_from_db(workspace_id, file_path, window, cx);
1047 }
1048 }
1049 }
1050
1051 fn pane_changed(&mut self, new_pane_id: EntityId, cx: &mut Context<Self>) {
1052 if self
1053 .highlighted_rows
1054 .get(&TypeId::of::<ActiveDebugLine>())
1055 .is_some_and(|lines| !lines.is_empty())
1056 && let Some(breakpoint_store) = self.breakpoint_store.as_ref()
1057 {
1058 breakpoint_store.update(cx, |store, _cx| {
1059 store.set_active_debug_pane_id(new_pane_id);
1060 });
1061 }
1062 }
1063
1064 fn to_item_events(event: &EditorEvent, f: &mut dyn FnMut(ItemEvent)) {
1065 match event {
1066 EditorEvent::Saved | EditorEvent::TitleChanged => {
1067 f(ItemEvent::UpdateTab);
1068 f(ItemEvent::UpdateBreadcrumbs);
1069 }
1070
1071 EditorEvent::Reparsed(_) => {
1072 f(ItemEvent::UpdateBreadcrumbs);
1073 }
1074
1075 EditorEvent::SelectionsChanged { local } if *local => {
1076 f(ItemEvent::UpdateBreadcrumbs);
1077 }
1078
1079 EditorEvent::BreadcrumbsChanged => {
1080 f(ItemEvent::UpdateBreadcrumbs);
1081 }
1082
1083 EditorEvent::DirtyChanged => {
1084 f(ItemEvent::UpdateTab);
1085 }
1086
1087 EditorEvent::BufferEdited => {
1088 f(ItemEvent::Edit);
1089 f(ItemEvent::UpdateBreadcrumbs);
1090 }
1091
1092 EditorEvent::BufferRangesUpdated { .. } | EditorEvent::BuffersRemoved { .. } => {
1093 f(ItemEvent::Edit);
1094 }
1095
1096 _ => {}
1097 }
1098 }
1099
1100 fn tab_extra_context_menu_actions(
1101 &self,
1102 _window: &mut Window,
1103 cx: &mut Context<Self>,
1104 ) -> Vec<(SharedString, Box<dyn gpui::Action>)> {
1105 let mut actions = Vec::new();
1106
1107 let is_markdown = self
1108 .buffer()
1109 .read(cx)
1110 .as_singleton()
1111 .and_then(|buffer| buffer.read(cx).language())
1112 .is_some_and(|language| language.name().as_ref() == "Markdown");
1113
1114 let is_svg = self
1115 .buffer()
1116 .read(cx)
1117 .as_singleton()
1118 .and_then(|buffer| buffer.read(cx).file())
1119 .is_some_and(|file| {
1120 std::path::Path::new(file.file_name(cx))
1121 .extension()
1122 .is_some_and(|ext| ext.eq_ignore_ascii_case("svg"))
1123 });
1124
1125 if is_markdown {
1126 actions.push((
1127 "Open Markdown Preview".into(),
1128 Box::new(OpenMarkdownPreview) as Box<dyn gpui::Action>,
1129 ));
1130 }
1131
1132 if is_svg {
1133 actions.push((
1134 "Open SVG Preview".into(),
1135 Box::new(OpenSvgPreview) as Box<dyn gpui::Action>,
1136 ));
1137 }
1138
1139 actions
1140 }
1141
1142 fn preserve_preview(&self, cx: &App) -> bool {
1143 self.buffer.read(cx).preserve_preview(cx)
1144 }
1145}
1146
1147impl SerializableItem for Editor {
1148 fn serialized_item_kind() -> &'static str {
1149 "Editor"
1150 }
1151
1152 fn cleanup(
1153 workspace_id: WorkspaceId,
1154 alive_items: Vec<ItemId>,
1155 _window: &mut Window,
1156 cx: &mut App,
1157 ) -> Task<Result<()>> {
1158 workspace::delete_unloaded_items(
1159 alive_items,
1160 workspace_id,
1161 "editors",
1162 &EditorDb::global(cx),
1163 cx,
1164 )
1165 }
1166
1167 fn deserialize(
1168 project: Entity<Project>,
1169 _workspace: WeakEntity<Workspace>,
1170 workspace_id: workspace::WorkspaceId,
1171 item_id: ItemId,
1172 window: &mut Window,
1173 cx: &mut App,
1174 ) -> Task<Result<Entity<Self>>> {
1175 let serialized_editor = match EditorDb::global(cx)
1176 .get_serialized_editor(item_id, workspace_id)
1177 .context("Failed to query editor state")
1178 {
1179 Ok(Some(serialized_editor)) => {
1180 if ProjectSettings::get_global(cx)
1181 .session
1182 .restore_unsaved_buffers
1183 {
1184 serialized_editor
1185 } else {
1186 SerializedEditor {
1187 abs_path: serialized_editor.abs_path,
1188 contents: None,
1189 language: None,
1190 mtime: None,
1191 }
1192 }
1193 }
1194 Ok(None) => {
1195 return Task::ready(Err(anyhow!(
1196 "Unable to deserialize editor: No entry in database for item_id: {item_id} and workspace_id {workspace_id:?}"
1197 )));
1198 }
1199 Err(error) => {
1200 return Task::ready(Err(error));
1201 }
1202 };
1203 log::debug!(
1204 "Deserialized editor {item_id:?} in workspace {workspace_id:?}, {serialized_editor:?}"
1205 );
1206
1207 match serialized_editor {
1208 SerializedEditor {
1209 abs_path: None,
1210 contents: Some(contents),
1211 language,
1212 ..
1213 } => window.spawn(cx, {
1214 let project = project.clone();
1215 async move |cx| {
1216 let language_registry =
1217 project.read_with(cx, |project, _| project.languages().clone());
1218
1219 let language = if let Some(language_name) = language {
1220 // We don't fail here, because we'd rather not set the language if the name changed
1221 // than fail to restore the buffer.
1222 language_registry
1223 .language_for_name(&language_name)
1224 .await
1225 .ok()
1226 } else {
1227 None
1228 };
1229
1230 // First create the empty buffer
1231 let buffer = project
1232 .update(cx, |project, cx| project.create_buffer(language, true, cx))
1233 .await
1234 .context("Failed to create buffer while deserializing editor")?;
1235
1236 // Then set the text so that the dirty bit is set correctly
1237 buffer.update(cx, |buffer, cx| {
1238 buffer.set_language_registry(language_registry);
1239 buffer.set_text(contents, cx);
1240 if let Some(entry) = buffer.peek_undo_stack() {
1241 buffer.forget_transaction(entry.transaction_id());
1242 }
1243 });
1244
1245 cx.update(|window, cx| {
1246 cx.new(|cx| {
1247 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1248
1249 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1250 editor
1251 })
1252 })
1253 }
1254 }),
1255 SerializedEditor {
1256 abs_path: Some(abs_path),
1257 contents,
1258 mtime,
1259 ..
1260 } => {
1261 let opened_buffer = project.update(cx, |project, cx| {
1262 let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1263 let project_path = ProjectPath {
1264 worktree_id: worktree.read(cx).id(),
1265 path: path,
1266 };
1267 Some(project.open_path(project_path, cx))
1268 });
1269
1270 match opened_buffer {
1271 Some(opened_buffer) => window.spawn(cx, async move |cx| {
1272 let (_, buffer) = opened_buffer
1273 .await
1274 .context("Failed to open path in project")?;
1275
1276 if let Some(contents) = contents {
1277 buffer.update(cx, |buffer, cx| {
1278 restore_serialized_buffer_contents(buffer, contents, mtime, cx);
1279 });
1280 }
1281
1282 cx.update(|window, cx| {
1283 cx.new(|cx| {
1284 let mut editor =
1285 Editor::for_buffer(buffer, Some(project), window, cx);
1286
1287 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1288 editor
1289 })
1290 })
1291 }),
1292 None => {
1293 // File is not in any worktree (e.g., opened as a standalone file).
1294 // Open the buffer directly via the project rather than through
1295 // workspace.open_abs_path(), which has the side effect of adding
1296 // the item to a pane. The caller (deserialize_to) will add the
1297 // returned item to the correct pane.
1298 window.spawn(cx, async move |cx| {
1299 let buffer = project
1300 .update(cx, |project, cx| project.open_local_buffer(&abs_path, cx))
1301 .await
1302 .with_context(|| {
1303 format!("Failed to open buffer for {abs_path:?}")
1304 })?;
1305
1306 if let Some(contents) = contents {
1307 buffer.update(cx, |buffer, cx| {
1308 restore_serialized_buffer_contents(buffer, contents, mtime, cx);
1309 });
1310 }
1311
1312 cx.update(|window, cx| {
1313 cx.new(|cx| {
1314 let mut editor =
1315 Editor::for_buffer(buffer, Some(project), window, cx);
1316 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1317 editor
1318 })
1319 })
1320 })
1321 }
1322 }
1323 }
1324 SerializedEditor {
1325 abs_path: None,
1326 contents: None,
1327 ..
1328 } => window.spawn(cx, async move |cx| {
1329 let buffer = project
1330 .update(cx, |project, cx| project.create_buffer(None, true, cx))
1331 .await
1332 .context("Failed to create buffer")?;
1333
1334 cx.update(|window, cx| {
1335 cx.new(|cx| {
1336 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1337
1338 editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1339 editor
1340 })
1341 })
1342 }),
1343 }
1344 }
1345
1346 fn serialize(
1347 &mut self,
1348 workspace: &mut Workspace,
1349 item_id: ItemId,
1350 closing: bool,
1351 window: &mut Window,
1352 cx: &mut Context<Self>,
1353 ) -> Option<Task<Result<()>>> {
1354 let buffer_serialization = self.buffer_serialization?;
1355 let project = self.project.clone()?;
1356
1357 let serialize_dirty_buffers = match buffer_serialization {
1358 // Always serialize dirty buffers, including for worktree-less windows.
1359 // This enables hot-exit functionality for empty windows and single files.
1360 BufferSerialization::All => true,
1361 BufferSerialization::NonDirtyBuffers => false,
1362 };
1363
1364 if closing && !serialize_dirty_buffers {
1365 return None;
1366 }
1367
1368 let workspace_id = workspace.database_id()?;
1369
1370 let buffer = self.buffer().read(cx).as_singleton()?;
1371
1372 let abs_path = buffer.read(cx).file().and_then(|file| {
1373 let worktree_id = file.worktree_id(cx);
1374 project
1375 .read(cx)
1376 .worktree_for_id(worktree_id, cx)
1377 .map(|worktree| worktree.read(cx).absolutize(file.path()))
1378 .or_else(|| {
1379 let full_path = file.full_path(cx);
1380 let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1381 project.read(cx).absolute_path(&project_path, cx)
1382 })
1383 });
1384
1385 let is_dirty = buffer.read(cx).is_dirty();
1386 let mtime = buffer.read(cx).saved_mtime();
1387
1388 let snapshot = buffer.read(cx).snapshot();
1389
1390 let db = EditorDb::global(cx);
1391 Some(cx.spawn_in(window, async move |_this, cx| {
1392 cx.background_spawn(async move {
1393 let (contents, language) = if serialize_dirty_buffers && is_dirty {
1394 let contents = snapshot.text();
1395 let language = snapshot.language().map(|lang| lang.name().to_string());
1396 (Some(contents), language)
1397 } else {
1398 (None, None)
1399 };
1400
1401 let editor = SerializedEditor {
1402 abs_path,
1403 contents,
1404 language,
1405 mtime,
1406 };
1407 log::debug!("Serializing editor {item_id:?} in workspace {workspace_id:?}");
1408 db.save_serialized_editor(item_id, workspace_id, editor)
1409 .await
1410 .context("failed to save serialized editor")
1411 })
1412 .await
1413 .context("failed to save contents of buffer")?;
1414
1415 Ok(())
1416 }))
1417 }
1418
1419 fn should_serialize(&self, event: &Self::Event) -> bool {
1420 self.should_serialize_buffer()
1421 && matches!(
1422 event,
1423 EditorEvent::Saved
1424 | EditorEvent::DirtyChanged
1425 | EditorEvent::BufferEdited
1426 | EditorEvent::FileHandleChanged
1427 )
1428 }
1429}
1430
1431#[derive(Debug, Default)]
1432struct EditorRestorationData {
1433 entries: HashMap<PathBuf, RestorationData>,
1434}
1435
1436#[derive(Default, Debug)]
1437pub struct RestorationData {
1438 pub scroll_position: (BufferRow, gpui::Point<ScrollOffset>),
1439 pub folds: Vec<Range<Point>>,
1440 pub selections: Vec<Range<Point>>,
1441}
1442
1443impl ProjectItem for Editor {
1444 type Item = Buffer;
1445
1446 fn project_item_kind() -> Option<ProjectItemKind> {
1447 Some(ProjectItemKind("Editor"))
1448 }
1449
1450 fn for_project_item(
1451 project: Entity<Project>,
1452 pane: Option<&Pane>,
1453 buffer: Entity<Buffer>,
1454 window: &mut Window,
1455 cx: &mut Context<Self>,
1456 ) -> Self {
1457 let mut editor = Self::for_buffer(buffer.clone(), Some(project), window, cx);
1458 let multibuffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1459
1460 if let Some(buffer_snapshot) = editor.buffer().read(cx).snapshot(cx).as_singleton()
1461 && WorkspaceSettings::get(None, cx).restore_on_file_reopen
1462 && let Some(restoration_data) = Self::project_item_kind()
1463 .and_then(|kind| pane.as_ref()?.project_item_restoration_data.get(&kind))
1464 .and_then(|data| data.downcast_ref::<EditorRestorationData>())
1465 .and_then(|data| {
1466 let file = project::File::from_dyn(buffer.read(cx).file())?;
1467 data.entries.get(&file.abs_path(cx))
1468 })
1469 {
1470 if !restoration_data.folds.is_empty() {
1471 editor.fold_ranges(
1472 clip_ranges(&restoration_data.folds, buffer_snapshot),
1473 false,
1474 window,
1475 cx,
1476 );
1477 }
1478 if !restoration_data.selections.is_empty() {
1479 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1480 s.select_ranges(clip_ranges(&restoration_data.selections, buffer_snapshot));
1481 });
1482 }
1483 let (top_row, offset) = restoration_data.scroll_position;
1484 let anchor = multibuffer_snapshot.anchor_before(Point::new(top_row, 0));
1485 editor.set_scroll_anchor(ScrollAnchor { anchor, offset }, window, cx);
1486 }
1487
1488 editor
1489 }
1490
1491 fn for_broken_project_item(
1492 abs_path: &Path,
1493 is_local: bool,
1494 e: &anyhow::Error,
1495 window: &mut Window,
1496 cx: &mut App,
1497 ) -> Option<InvalidItemView> {
1498 Some(InvalidItemView::new(abs_path, is_local, e, window, cx))
1499 }
1500}
1501
1502fn clip_ranges<'a>(
1503 original: impl IntoIterator<Item = &'a Range<Point>> + 'a,
1504 snapshot: &'a BufferSnapshot,
1505) -> Vec<Range<Point>> {
1506 original
1507 .into_iter()
1508 .map(|range| {
1509 snapshot.clip_point(range.start, Bias::Left)
1510 ..snapshot.clip_point(range.end, Bias::Right)
1511 })
1512 .collect()
1513}
1514
1515impl EventEmitter<SearchEvent> for Editor {}
1516
1517impl Editor {
1518 pub fn update_restoration_data(
1519 &self,
1520 cx: &mut Context<Self>,
1521 write: impl for<'a> FnOnce(&'a mut RestorationData) + 'static,
1522 ) {
1523 if self.mode.is_minimap() || !WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1524 return;
1525 }
1526
1527 let editor = cx.entity();
1528 cx.defer(move |cx| {
1529 editor.update(cx, |editor, cx| {
1530 let kind = Editor::project_item_kind()?;
1531 let pane = editor.workspace()?.read(cx).pane_for(&cx.entity())?;
1532 let buffer = editor.buffer().read(cx).as_singleton()?;
1533 let file_abs_path = project::File::from_dyn(buffer.read(cx).file())?.abs_path(cx);
1534 pane.update(cx, |pane, _| {
1535 let data = pane
1536 .project_item_restoration_data
1537 .entry(kind)
1538 .or_insert_with(|| Box::new(EditorRestorationData::default()) as Box<_>);
1539 let data = match data.downcast_mut::<EditorRestorationData>() {
1540 Some(data) => data,
1541 None => {
1542 *data = Box::new(EditorRestorationData::default());
1543 data.downcast_mut::<EditorRestorationData>()
1544 .expect("just written the type downcasted to")
1545 }
1546 };
1547
1548 let data = data.entries.entry(file_abs_path).or_default();
1549 write(data);
1550 Some(())
1551 })
1552 });
1553 });
1554 }
1555}
1556
1557impl SearchableItem for Editor {
1558 type Match = Range<Anchor>;
1559
1560 fn get_matches(&self, _window: &mut Window, _: &mut App) -> (Vec<Range<Anchor>>, SearchToken) {
1561 (
1562 self.background_highlights
1563 .get(&HighlightKey::BufferSearchHighlights)
1564 .map_or(Vec::new(), |(_color, ranges)| {
1565 ranges.iter().cloned().collect()
1566 }),
1567 SearchToken::default(),
1568 )
1569 }
1570
1571 fn clear_matches(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1572 if self
1573 .clear_background_highlights(HighlightKey::BufferSearchHighlights, cx)
1574 .is_some()
1575 {
1576 cx.emit(SearchEvent::MatchesInvalidated);
1577 }
1578 }
1579
1580 fn update_matches(
1581 &mut self,
1582 matches: &[Range<Anchor>],
1583 active_match_index: Option<usize>,
1584 _token: SearchToken,
1585 _: &mut Window,
1586 cx: &mut Context<Self>,
1587 ) {
1588 let existing_range = self
1589 .background_highlights
1590 .get(&HighlightKey::BufferSearchHighlights)
1591 .map(|(_, range)| range.as_ref());
1592 let updated = existing_range != Some(matches);
1593 self.highlight_background(
1594 HighlightKey::BufferSearchHighlights,
1595 matches,
1596 move |index, theme| {
1597 if active_match_index == Some(*index) {
1598 theme.colors().search_active_match_background
1599 } else {
1600 theme.colors().search_match_background
1601 }
1602 },
1603 cx,
1604 );
1605 if updated {
1606 cx.emit(SearchEvent::MatchesInvalidated);
1607 }
1608 }
1609
1610 fn has_filtered_search_ranges(&mut self) -> bool {
1611 self.has_background_highlights(HighlightKey::SearchWithinRange)
1612 }
1613
1614 fn toggle_filtered_search_ranges(
1615 &mut self,
1616 enabled: Option<FilteredSearchRange>,
1617 _: &mut Window,
1618 cx: &mut Context<Self>,
1619 ) {
1620 if self.has_filtered_search_ranges() {
1621 self.previous_search_ranges = self
1622 .clear_background_highlights(HighlightKey::SearchWithinRange, cx)
1623 .map(|(_, ranges)| ranges)
1624 }
1625
1626 if let Some(range) = enabled {
1627 let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1628
1629 if ranges.iter().any(|s| s.start != s.end) {
1630 self.set_search_within_ranges(&ranges, cx);
1631 } else if let Some(previous_search_ranges) = self.previous_search_ranges.take()
1632 && range != FilteredSearchRange::Selection
1633 {
1634 self.set_search_within_ranges(&previous_search_ranges, cx);
1635 }
1636 }
1637 }
1638
1639 fn supported_options(&self) -> SearchOptions {
1640 if self.in_project_search {
1641 SearchOptions {
1642 case: true,
1643 word: true,
1644 regex: true,
1645 replacement: false,
1646 selection: false,
1647 select_all: true,
1648 find_in_results: true,
1649 }
1650 } else {
1651 SearchOptions {
1652 case: true,
1653 word: true,
1654 regex: true,
1655 replacement: true,
1656 selection: true,
1657 select_all: true,
1658 find_in_results: false,
1659 }
1660 }
1661 }
1662
1663 fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
1664 let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1665 let snapshot = self.snapshot(window, cx);
1666 let selection = self.selections.newest_adjusted(&snapshot.display_snapshot);
1667 let buffer_snapshot = snapshot.buffer_snapshot();
1668
1669 match setting {
1670 SeedQuerySetting::Never => String::new(),
1671 SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1672 buffer_snapshot
1673 .text_for_range(selection.start..selection.end)
1674 .collect()
1675 }
1676 SeedQuerySetting::Selection => String::new(),
1677 SeedQuerySetting::Always => {
1678 let (range, kind) = buffer_snapshot
1679 .surrounding_word(selection.start, Some(CharScopeContext::Completion));
1680 if kind == Some(CharKind::Word) {
1681 let text: String = buffer_snapshot.text_for_range(range).collect();
1682 if !text.trim().is_empty() {
1683 return text;
1684 }
1685 }
1686 String::new()
1687 }
1688 }
1689 }
1690
1691 fn activate_match(
1692 &mut self,
1693 index: usize,
1694 matches: &[Range<Anchor>],
1695 _token: SearchToken,
1696 window: &mut Window,
1697 cx: &mut Context<Self>,
1698 ) {
1699 self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1700 let range = self.range_for_match(&matches[index]);
1701 let autoscroll = if EditorSettings::get_global(cx).search.center_on_match {
1702 Autoscroll::center()
1703 } else {
1704 Autoscroll::fit()
1705 };
1706 self.change_selections(
1707 SelectionEffects::scroll(autoscroll).from_search(true),
1708 window,
1709 cx,
1710 |s| {
1711 s.select_ranges([range]);
1712 },
1713 )
1714 }
1715
1716 fn select_matches(
1717 &mut self,
1718 matches: &[Self::Match],
1719 _token: SearchToken,
1720 window: &mut Window,
1721 cx: &mut Context<Self>,
1722 ) {
1723 self.unfold_ranges(matches, false, false, cx);
1724 self.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1725 s.select_ranges(matches.iter().cloned())
1726 });
1727 }
1728 fn replace(
1729 &mut self,
1730 identifier: &Self::Match,
1731 query: &SearchQuery,
1732 _token: SearchToken,
1733 window: &mut Window,
1734 cx: &mut Context<Self>,
1735 ) {
1736 let text = self.buffer.read(cx);
1737 let text = text.snapshot(cx);
1738 let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1739 let text: Cow<_> = if text.len() == 1 {
1740 text.first().cloned().unwrap().into()
1741 } else {
1742 let joined_chunks = text.join("");
1743 joined_chunks.into()
1744 };
1745
1746 if let Some(replacement) = query.replacement_for(&text) {
1747 self.transact(window, cx, |this, _, cx| {
1748 this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1749 });
1750 }
1751 }
1752 fn replace_all(
1753 &mut self,
1754 matches: &mut dyn Iterator<Item = &Self::Match>,
1755 query: &SearchQuery,
1756 _token: SearchToken,
1757 window: &mut Window,
1758 cx: &mut Context<Self>,
1759 ) {
1760 let text = self.buffer.read(cx);
1761 let text = text.snapshot(cx);
1762 let mut edits = vec![];
1763
1764 // A regex might have replacement variables so we cannot apply
1765 // the same replacement to all matches
1766 if query.is_regex() {
1767 edits = matches
1768 .filter_map(|m| {
1769 let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1770
1771 let text: Cow<_> = if text.len() == 1 {
1772 text.first().cloned().unwrap().into()
1773 } else {
1774 let joined_chunks = text.join("");
1775 joined_chunks.into()
1776 };
1777
1778 query
1779 .replacement_for(&text)
1780 .map(|replacement| (m.clone(), Arc::from(&*replacement)))
1781 })
1782 .collect();
1783 } else if let Some(replacement) = query.replacement().map(Arc::<str>::from) {
1784 edits = matches.map(|m| (m.clone(), replacement.clone())).collect();
1785 }
1786
1787 if !edits.is_empty() {
1788 self.transact(window, cx, |this, _, cx| {
1789 this.edit(edits, cx);
1790 });
1791 }
1792 }
1793 fn match_index_for_direction(
1794 &mut self,
1795 matches: &[Range<Anchor>],
1796 current_index: usize,
1797 direction: Direction,
1798 count: usize,
1799 _token: SearchToken,
1800 _: &mut Window,
1801 cx: &mut Context<Self>,
1802 ) -> usize {
1803 let buffer = self.buffer().read(cx).snapshot(cx);
1804 let current_index_position = if self.selections.disjoint_anchors_arc().len() == 1 {
1805 self.selections.newest_anchor().head()
1806 } else {
1807 matches[current_index].start
1808 };
1809
1810 let mut count = count % matches.len();
1811 if count == 0 {
1812 return current_index;
1813 }
1814 match direction {
1815 Direction::Next => {
1816 if matches[current_index]
1817 .start
1818 .cmp(¤t_index_position, &buffer)
1819 .is_gt()
1820 {
1821 count -= 1
1822 }
1823
1824 (current_index + count) % matches.len()
1825 }
1826 Direction::Prev => {
1827 if matches[current_index]
1828 .end
1829 .cmp(¤t_index_position, &buffer)
1830 .is_lt()
1831 {
1832 count -= 1;
1833 }
1834
1835 if current_index >= count {
1836 current_index - count
1837 } else {
1838 matches.len() - (count - current_index)
1839 }
1840 }
1841 }
1842 }
1843
1844 fn find_matches(
1845 &mut self,
1846 query: Arc<project::search::SearchQuery>,
1847 _: &mut Window,
1848 cx: &mut Context<Self>,
1849 ) -> Task<Vec<Range<Anchor>>> {
1850 let buffer = self.buffer().read(cx).snapshot(cx);
1851 let search_within_ranges = self
1852 .background_highlights
1853 .get(&HighlightKey::SearchWithinRange)
1854 .map_or(vec![], |(_color, ranges)| {
1855 ranges.iter().cloned().collect::<Vec<_>>()
1856 });
1857
1858 cx.background_spawn(async move {
1859 let mut ranges = Vec::new();
1860
1861 let search_within_ranges = if search_within_ranges.is_empty() {
1862 vec![buffer.anchor_before(MultiBufferOffset(0))..buffer.anchor_after(buffer.len())]
1863 } else {
1864 search_within_ranges
1865 };
1866
1867 for range in search_within_ranges {
1868 for (search_buffer, search_range, deleted_hunk_anchor) in
1869 buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1870 {
1871 ranges.extend(
1872 query
1873 .search(
1874 search_buffer,
1875 Some(search_range.start.0..search_range.end.0),
1876 )
1877 .await
1878 .into_iter()
1879 .filter_map(|match_range| {
1880 if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
1881 let start = search_buffer
1882 .anchor_after(search_range.start + match_range.start);
1883 let end = search_buffer
1884 .anchor_before(search_range.start + match_range.end);
1885 Some(
1886 deleted_hunk_anchor.with_diff_base_anchor(start)
1887 ..deleted_hunk_anchor.with_diff_base_anchor(end),
1888 )
1889 } else {
1890 let start = search_buffer
1891 .anchor_after(search_range.start + match_range.start);
1892 let end = search_buffer
1893 .anchor_before(search_range.start + match_range.end);
1894 buffer.buffer_anchor_range_to_anchor_range(start..end)
1895 }
1896 }),
1897 );
1898 }
1899 }
1900
1901 ranges
1902 })
1903 }
1904
1905 fn active_match_index(
1906 &mut self,
1907 direction: Direction,
1908 matches: &[Range<Anchor>],
1909 _token: SearchToken,
1910 _: &mut Window,
1911 cx: &mut Context<Self>,
1912 ) -> Option<usize> {
1913 active_match_index(
1914 direction,
1915 matches,
1916 &self.selections.newest_anchor().head(),
1917 &self.buffer().read(cx).snapshot(cx),
1918 )
1919 }
1920
1921 fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
1922 self.expect_bounds_change = self.last_bounds;
1923 }
1924
1925 fn set_search_is_case_sensitive(
1926 &mut self,
1927 case_sensitive: Option<bool>,
1928 _cx: &mut Context<Self>,
1929 ) {
1930 self.select_next_is_case_sensitive = case_sensitive;
1931 }
1932}
1933
1934pub fn active_match_index(
1935 direction: Direction,
1936 ranges: &[Range<Anchor>],
1937 cursor: &Anchor,
1938 buffer: &MultiBufferSnapshot,
1939) -> Option<usize> {
1940 if ranges.is_empty() {
1941 None
1942 } else {
1943 let r = ranges.binary_search_by(|probe| {
1944 if probe.end.cmp(cursor, buffer).is_lt() {
1945 Ordering::Less
1946 } else if probe.start.cmp(cursor, buffer).is_gt() {
1947 Ordering::Greater
1948 } else {
1949 Ordering::Equal
1950 }
1951 });
1952 match direction {
1953 Direction::Prev => match r {
1954 Ok(i) => Some(i),
1955 Err(i) => Some(i.saturating_sub(1)),
1956 },
1957 Direction::Next => match r {
1958 Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1959 },
1960 }
1961 }
1962}
1963
1964pub fn entry_label_color(selected: bool) -> Color {
1965 if selected {
1966 Color::Default
1967 } else {
1968 Color::Muted
1969 }
1970}
1971
1972pub fn entry_diagnostic_aware_icon_name_and_color(
1973 diagnostic_severity: Option<DiagnosticSeverity>,
1974) -> Option<(IconName, Color)> {
1975 match diagnostic_severity {
1976 Some(DiagnosticSeverity::ERROR) => Some((IconName::Close, Color::Error)),
1977 Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1978 _ => None,
1979 }
1980}
1981
1982pub fn entry_diagnostic_aware_icon_decoration_and_color(
1983 diagnostic_severity: Option<DiagnosticSeverity>,
1984) -> Option<(IconDecorationKind, Color)> {
1985 match diagnostic_severity {
1986 Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1987 Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1988 _ => None,
1989 }
1990}
1991
1992pub fn entry_git_aware_label_color(git_status: GitSummary, ignored: bool, selected: bool) -> Color {
1993 let tracked = git_status.index + git_status.worktree;
1994 if git_status.conflict > 0 {
1995 Color::Conflict
1996 } else if tracked.deleted > 0 {
1997 Color::Deleted
1998 } else if tracked.modified > 0 {
1999 Color::Modified
2000 } else if tracked.added > 0 || git_status.untracked > 0 {
2001 Color::Created
2002 } else if ignored {
2003 Color::Ignored
2004 } else {
2005 entry_label_color(selected)
2006 }
2007}
2008
2009fn path_for_buffer<'a>(
2010 buffer: &Entity<MultiBuffer>,
2011 height: usize,
2012 include_filename: bool,
2013 cx: &'a App,
2014) -> Option<Cow<'a, str>> {
2015 let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
2016 path_for_file(file, height, include_filename, cx)
2017}
2018
2019fn path_for_file<'a>(
2020 file: &'a Arc<dyn language::File>,
2021 mut height: usize,
2022 include_filename: bool,
2023 cx: &'a App,
2024) -> Option<Cow<'a, str>> {
2025 if project::File::from_dyn(Some(file)).is_none() {
2026 return None;
2027 }
2028
2029 let file = file.as_ref();
2030 // Ensure we always render at least the filename.
2031 height += 1;
2032
2033 let mut prefix = file.path().as_ref();
2034 while height > 0 {
2035 if let Some(parent) = prefix.parent() {
2036 prefix = parent;
2037 height -= 1;
2038 } else {
2039 break;
2040 }
2041 }
2042
2043 // The full_path method allocates, so avoid calling it if height is zero.
2044 if height > 0 {
2045 let mut full_path = file.full_path(cx);
2046 if !include_filename {
2047 if !full_path.pop() {
2048 return None;
2049 }
2050 }
2051 Some(full_path.to_string_lossy().into_owned().into())
2052 } else {
2053 let mut path = file.path().strip_prefix(prefix).ok()?;
2054 if !include_filename {
2055 path = path.parent()?;
2056 }
2057 Some(path.display(file.path_style(cx)))
2058 }
2059}
2060
2061/// Restores serialized buffer contents by overwriting the buffer with saved text.
2062/// This is somewhat wasteful since we load the whole buffer from disk then overwrite it,
2063/// but keeps implementation simple as we don't need to persist all metadata from loading
2064/// (git diff base, etc.).
2065fn restore_serialized_buffer_contents(
2066 buffer: &mut Buffer,
2067 contents: String,
2068 mtime: Option<MTime>,
2069 cx: &mut Context<Buffer>,
2070) {
2071 // If we did restore an mtime, store it on the buffer so that
2072 // the next edit will mark the buffer as dirty/conflicted.
2073 if mtime.is_some() {
2074 buffer.did_reload(buffer.version(), buffer.line_ending(), mtime, cx);
2075 }
2076 buffer.set_text(contents, cx);
2077 if let Some(entry) = buffer.peek_undo_stack() {
2078 buffer.forget_transaction(entry.transaction_id());
2079 }
2080}
2081
2082fn serialize_path_key(path_key: &PathKey) -> proto::PathKey {
2083 proto::PathKey {
2084 sort_prefix: path_key.sort_prefix,
2085 path: path_key.path.to_proto(),
2086 }
2087}
2088
2089fn deserialize_path_key(path_key: proto::PathKey) -> Option<PathKey> {
2090 Some(PathKey {
2091 sort_prefix: path_key.sort_prefix,
2092 path: RelPath::from_proto(&path_key.path).ok()?,
2093 })
2094}
2095
2096#[cfg(test)]
2097mod tests {
2098 use crate::editor_tests::init_test;
2099 use fs::Fs;
2100 use workspace::MultiWorkspace;
2101
2102 use super::*;
2103 use fs::MTime;
2104 use gpui::{App, VisualTestContext};
2105 use language::TestFile;
2106 use project::FakeFs;
2107 use serde_json::json;
2108 use std::path::{Path, PathBuf};
2109 use util::{path, rel_path::RelPath};
2110
2111 #[gpui::test]
2112 fn test_path_for_file(cx: &mut App) {
2113 let file: Arc<dyn language::File> = Arc::new(TestFile {
2114 path: RelPath::empty().into(),
2115 root_name: String::new(),
2116 local_root: None,
2117 });
2118 assert_eq!(path_for_file(&file, 0, false, cx), None);
2119 }
2120
2121 async fn deserialize_editor(
2122 item_id: ItemId,
2123 workspace_id: WorkspaceId,
2124 workspace: Entity<Workspace>,
2125 project: Entity<Project>,
2126 cx: &mut VisualTestContext,
2127 ) -> Entity<Editor> {
2128 workspace
2129 .update_in(cx, |workspace, window, cx| {
2130 let pane = workspace.active_pane();
2131 pane.update(cx, |_, cx| {
2132 Editor::deserialize(
2133 project.clone(),
2134 workspace.weak_handle(),
2135 workspace_id,
2136 item_id,
2137 window,
2138 cx,
2139 )
2140 })
2141 })
2142 .await
2143 .unwrap()
2144 }
2145
2146 #[gpui::test]
2147 async fn test_deserialize(cx: &mut gpui::TestAppContext) {
2148 init_test(cx, |_| {});
2149
2150 let fs = FakeFs::new(cx.executor());
2151 fs.insert_file(path!("/file.rs"), Default::default()).await;
2152
2153 // Test case 1: Deserialize with path and contents
2154 {
2155 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2156 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2157 MultiWorkspace::test_new(project.clone(), window, cx)
2158 });
2159 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2160 let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2161 let workspace_id = db.next_id().await.unwrap();
2162 let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2163 let item_id = 1234 as ItemId;
2164 let mtime = fs
2165 .metadata(Path::new(path!("/file.rs")))
2166 .await
2167 .unwrap()
2168 .unwrap()
2169 .mtime;
2170
2171 let serialized_editor = SerializedEditor {
2172 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2173 contents: Some("fn main() {}".to_string()),
2174 language: Some("Rust".to_string()),
2175 mtime: Some(mtime),
2176 };
2177
2178 editor_db
2179 .save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
2180 .await
2181 .unwrap();
2182
2183 let deserialized =
2184 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2185
2186 deserialized.update(cx, |editor, cx| {
2187 assert_eq!(editor.text(cx), "fn main() {}");
2188 assert!(editor.is_dirty(cx));
2189 assert!(!editor.has_conflict(cx));
2190 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2191 assert!(buffer.file().is_some());
2192 });
2193 }
2194
2195 // Test case 2: Deserialize with only path
2196 {
2197 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2198 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2199 MultiWorkspace::test_new(project.clone(), window, cx)
2200 });
2201 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2202 let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2203 let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2204
2205 let workspace_id = db.next_id().await.unwrap();
2206
2207 let item_id = 5678 as ItemId;
2208 let serialized_editor = SerializedEditor {
2209 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2210 contents: None,
2211 language: None,
2212 mtime: None,
2213 };
2214
2215 editor_db
2216 .save_serialized_editor(item_id, workspace_id, serialized_editor)
2217 .await
2218 .unwrap();
2219
2220 let deserialized =
2221 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2222
2223 deserialized.update(cx, |editor, cx| {
2224 assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
2225 assert!(!editor.is_dirty(cx));
2226 assert!(!editor.has_conflict(cx));
2227
2228 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2229 assert!(buffer.file().is_some());
2230 });
2231 }
2232
2233 // Test case 3: Deserialize with no path (untitled buffer, with content and language)
2234 {
2235 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2236 // Add Rust to the language, so that we can restore the language of the buffer
2237 project.read_with(cx, |project, _| {
2238 project.languages().add(languages::rust_lang())
2239 });
2240
2241 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2242 MultiWorkspace::test_new(project.clone(), window, cx)
2243 });
2244 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2245 let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2246 let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2247
2248 let workspace_id = db.next_id().await.unwrap();
2249
2250 let item_id = 9012 as ItemId;
2251 let serialized_editor = SerializedEditor {
2252 abs_path: None,
2253 contents: Some("hello".to_string()),
2254 language: Some("Rust".to_string()),
2255 mtime: None,
2256 };
2257
2258 editor_db
2259 .save_serialized_editor(item_id, workspace_id, serialized_editor)
2260 .await
2261 .unwrap();
2262
2263 let deserialized =
2264 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2265
2266 deserialized.update(cx, |editor, cx| {
2267 assert_eq!(editor.text(cx), "hello");
2268 assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
2269
2270 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2271 assert_eq!(
2272 buffer.language().map(|lang| lang.name()),
2273 Some("Rust".into())
2274 ); // Language should be set to Rust
2275 assert!(buffer.file().is_none()); // The buffer should not have an associated file
2276 });
2277 }
2278
2279 // Test case 4: Deserialize with path, content, and old mtime
2280 {
2281 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2282 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2283 MultiWorkspace::test_new(project.clone(), window, cx)
2284 });
2285 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2286 let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2287 let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2288
2289 let workspace_id = db.next_id().await.unwrap();
2290
2291 let item_id = 9345 as ItemId;
2292 let old_mtime = MTime::from_seconds_and_nanos(0, 50);
2293 let serialized_editor = SerializedEditor {
2294 abs_path: Some(PathBuf::from(path!("/file.rs"))),
2295 contents: Some("fn main() {}".to_string()),
2296 language: Some("Rust".to_string()),
2297 mtime: Some(old_mtime),
2298 };
2299
2300 editor_db
2301 .save_serialized_editor(item_id, workspace_id, serialized_editor)
2302 .await
2303 .unwrap();
2304
2305 let deserialized =
2306 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2307
2308 deserialized.update(cx, |editor, cx| {
2309 assert_eq!(editor.text(cx), "fn main() {}");
2310 assert!(editor.has_conflict(cx)); // The editor should have a conflict
2311 });
2312 }
2313
2314 // Test case 5: Deserialize with no path, no content, no language, and no old mtime (new, empty, unsaved buffer)
2315 {
2316 let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2317 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2318 MultiWorkspace::test_new(project.clone(), window, cx)
2319 });
2320 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2321 let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2322 let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2323
2324 let workspace_id = db.next_id().await.unwrap();
2325
2326 let item_id = 10000 as ItemId;
2327 let serialized_editor = SerializedEditor {
2328 abs_path: None,
2329 contents: None,
2330 language: None,
2331 mtime: None,
2332 };
2333
2334 editor_db
2335 .save_serialized_editor(item_id, workspace_id, serialized_editor)
2336 .await
2337 .unwrap();
2338
2339 let deserialized =
2340 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2341
2342 deserialized.update(cx, |editor, cx| {
2343 assert_eq!(editor.text(cx), "");
2344 assert!(!editor.is_dirty(cx));
2345 assert!(!editor.has_conflict(cx));
2346
2347 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2348 assert!(buffer.file().is_none());
2349 });
2350 }
2351
2352 // Test case 6: Deserialize with path and contents in an empty workspace (no worktree)
2353 // This tests the hot-exit scenario where a file is opened in an empty workspace
2354 // and has unsaved changes that should be restored.
2355 {
2356 let fs = FakeFs::new(cx.executor());
2357 fs.insert_file(path!("/standalone.rs"), "original content".into())
2358 .await;
2359
2360 // Create an empty project with no worktrees
2361 let project = Project::test(fs.clone(), [], cx).await;
2362 let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2363 MultiWorkspace::test_new(project.clone(), window, cx)
2364 });
2365 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2366 let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2367 let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2368
2369 let workspace_id = db.next_id().await.unwrap();
2370 let item_id = 11000 as ItemId;
2371
2372 let mtime = fs
2373 .metadata(Path::new(path!("/standalone.rs")))
2374 .await
2375 .unwrap()
2376 .unwrap()
2377 .mtime;
2378
2379 // Simulate serialized state: file with unsaved changes
2380 let serialized_editor = SerializedEditor {
2381 abs_path: Some(PathBuf::from(path!("/standalone.rs"))),
2382 contents: Some("modified content".to_string()),
2383 language: Some("Rust".to_string()),
2384 mtime: Some(mtime),
2385 };
2386
2387 editor_db
2388 .save_serialized_editor(item_id, workspace_id, serialized_editor)
2389 .await
2390 .unwrap();
2391
2392 let deserialized =
2393 deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2394
2395 deserialized.update(cx, |editor, cx| {
2396 // The editor should have the serialized contents, not the disk contents
2397 assert_eq!(editor.text(cx), "modified content");
2398 assert!(editor.is_dirty(cx));
2399 assert!(!editor.has_conflict(cx));
2400
2401 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2402 assert!(buffer.file().is_some());
2403 });
2404 }
2405 }
2406
2407 // Verify that renaming an open file emits EditorEvent::FileHandleChanged so that
2408 // the workspace re-serializes the editor with the updated path.
2409 #[gpui::test]
2410 async fn test_file_handle_changed_on_rename(cx: &mut gpui::TestAppContext) {
2411 use serde_json::json;
2412 use std::cell::RefCell;
2413 use std::rc::Rc;
2414 use util::rel_path::rel_path;
2415
2416 init_test(cx, |_| {});
2417
2418 let fs = FakeFs::new(cx.executor());
2419 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}" }))
2420 .await;
2421
2422 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
2423
2424 let buffer = project
2425 .update(cx, |project, cx| {
2426 project.open_local_buffer(path!("/root/file.rs"), cx)
2427 })
2428 .await
2429 .unwrap();
2430
2431 let received_file_handle_changed = Rc::new(RefCell::new(false));
2432 let (editor, cx) = cx.add_window_view({
2433 let project = project.clone();
2434 let received_file_handle_changed = received_file_handle_changed.clone();
2435 move |window, cx| {
2436 let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
2437 editor.set_should_serialize(true, cx);
2438 let entity = cx.entity();
2439 cx.subscribe_in(&entity, window, move |_, _, event: &EditorEvent, _, _| {
2440 if matches!(event, EditorEvent::FileHandleChanged) {
2441 *received_file_handle_changed.borrow_mut() = true;
2442 }
2443 })
2444 .detach();
2445 editor
2446 }
2447 });
2448
2449 cx.run_until_parked();
2450
2451 let (entry_id, worktree_id) = project.update(cx, |project, cx| {
2452 let worktree = project.worktrees(cx).next().unwrap();
2453 let worktree = worktree.read(cx);
2454 let entry = worktree.entry_for_path(rel_path("file.rs")).unwrap();
2455 (entry.id, worktree.id())
2456 });
2457
2458 project
2459 .update(cx, |project, cx| {
2460 project.rename_entry(entry_id, (worktree_id, rel_path("renamed.rs")).into(), cx)
2461 })
2462 .await
2463 .unwrap();
2464
2465 cx.run_until_parked();
2466
2467 assert!(
2468 *received_file_handle_changed.borrow(),
2469 "EditorEvent::FileHandleChanged must be emitted when the open file is renamed"
2470 );
2471
2472 editor.update(cx, |editor, cx| {
2473 let buffer = editor.buffer().read(cx).as_singleton().unwrap();
2474 let path = buffer.read(cx).file().unwrap().path();
2475 assert!(
2476 path.as_std_path().ends_with("renamed.rs"),
2477 "buffer path must reflect the renamed file, got {path:?}"
2478 );
2479 });
2480 }
2481
2482 // Regression test for https://github.com/zed-industries/zed/issues/35947
2483 // Verifies that deserializing a non-worktree editor does not add the item
2484 // to any pane as a side effect.
2485 #[gpui::test]
2486 async fn test_deserialize_non_worktree_file_does_not_add_to_pane(
2487 cx: &mut gpui::TestAppContext,
2488 ) {
2489 init_test(cx, |_| {});
2490
2491 let fs = FakeFs::new(cx.executor());
2492 fs.insert_tree(path!("/outside"), json!({ "settings.json": "{}" }))
2493 .await;
2494
2495 // Project with a different root — settings.json is NOT in any worktree
2496 let project = Project::test(fs.clone(), [], cx).await;
2497 let (multi_workspace, cx) =
2498 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2499 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2500 let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2501 let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2502
2503 let workspace_id = db.next_id().await.unwrap();
2504 let item_id = 99999 as ItemId;
2505
2506 let serialized_editor = SerializedEditor {
2507 abs_path: Some(PathBuf::from(path!("/outside/settings.json"))),
2508 contents: None,
2509 language: None,
2510 mtime: None,
2511 };
2512
2513 editor_db
2514 .save_serialized_editor(item_id, workspace_id, serialized_editor)
2515 .await
2516 .unwrap();
2517
2518 // Count items in all panes before deserialization
2519 let pane_items_before = workspace.read_with(cx, |workspace, cx| {
2520 workspace
2521 .panes()
2522 .iter()
2523 .map(|pane| pane.read(cx).items_len())
2524 .sum::<usize>()
2525 });
2526
2527 let deserialized =
2528 deserialize_editor(item_id, workspace_id, workspace.clone(), project, cx).await;
2529
2530 cx.run_until_parked();
2531
2532 // The editor should exist and have the file
2533 deserialized.update(cx, |editor, cx| {
2534 let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2535 assert!(buffer.file().is_some());
2536 });
2537
2538 // No items should have been added to any pane as a side effect
2539 let pane_items_after = workspace.read_with(cx, |workspace, cx| {
2540 workspace
2541 .panes()
2542 .iter()
2543 .map(|pane| pane.read(cx).items_len())
2544 .sum::<usize>()
2545 });
2546
2547 assert_eq!(
2548 pane_items_before, pane_items_after,
2549 "Editor::deserialize should not add items to panes as a side effect"
2550 );
2551 }
2552}