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