items.rs

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