items.rs

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