items.rs

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