items.rs

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