items.rs

   1use crate::{
   2    Anchor, Autoscroll, Editor, EditorEvent, EditorSettings, ExcerptId, ExcerptRange, FormatTarget,
   3    MultiBuffer, MultiBufferSnapshot, NavigationData, ReportEditorEvent, SearchWithinRange,
   4    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_buffer_view::InvalidBufferView,
  46    item::{FollowableItem, Item, 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.is_singleton()).then(|| buffer.title(cx).into()),
 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((excerpt_id, _, _)) = buffer.as_singleton() else {
 368            return;
 369        };
 370        let position = buffer.anchor_in_excerpt(*excerpt_id, location).unwrap();
 371        let selection = Selection {
 372            id: 0,
 373            reversed: false,
 374            start: position,
 375            end: position,
 376            goal: SelectionGoal::None,
 377        };
 378        drop(buffer);
 379        self.set_selections_from_remote(vec![selection], None, window, cx);
 380        self.request_autoscroll_remotely(Autoscroll::fit(), cx);
 381    }
 382}
 383
 384async fn update_editor_from_message(
 385    this: WeakEntity<Editor>,
 386    project: Entity<Project>,
 387    message: proto::update_view::Editor,
 388    cx: &mut AsyncWindowContext,
 389) -> Result<()> {
 390    // Open all of the buffers of which excerpts were added to the editor.
 391    let inserted_excerpt_buffer_ids = message
 392        .inserted_excerpts
 393        .iter()
 394        .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
 395        .collect::<HashSet<_>>();
 396    let inserted_excerpt_buffers = project.update(cx, |project, cx| {
 397        inserted_excerpt_buffer_ids
 398            .into_iter()
 399            .map(|id| BufferId::new(id).map(|id| project.open_buffer_by_id(id, cx)))
 400            .collect::<Result<Vec<_>>>()
 401    })??;
 402    let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
 403
 404    // Update the editor's excerpts.
 405    this.update(cx, |editor, cx| {
 406        editor.buffer.update(cx, |multibuffer, cx| {
 407            let mut removed_excerpt_ids = message
 408                .deleted_excerpts
 409                .into_iter()
 410                .map(ExcerptId::from_proto)
 411                .collect::<Vec<_>>();
 412            removed_excerpt_ids.sort_by({
 413                let multibuffer = multibuffer.read(cx);
 414                move |a, b| a.cmp(b, &multibuffer)
 415            });
 416
 417            let mut insertions = message.inserted_excerpts.into_iter().peekable();
 418            while let Some(insertion) = insertions.next() {
 419                let Some(excerpt) = insertion.excerpt else {
 420                    continue;
 421                };
 422                let Some(previous_excerpt_id) = insertion.previous_excerpt_id else {
 423                    continue;
 424                };
 425                let buffer_id = BufferId::new(excerpt.buffer_id)?;
 426                let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
 427                    continue;
 428                };
 429
 430                let adjacent_excerpts = iter::from_fn(|| {
 431                    let insertion = insertions.peek()?;
 432                    if insertion.previous_excerpt_id.is_none()
 433                        && insertion.excerpt.as_ref()?.buffer_id == u64::from(buffer_id)
 434                    {
 435                        insertions.next()?.excerpt
 436                    } else {
 437                        None
 438                    }
 439                });
 440
 441                multibuffer.insert_excerpts_with_ids_after(
 442                    ExcerptId::from_proto(previous_excerpt_id),
 443                    buffer,
 444                    [excerpt]
 445                        .into_iter()
 446                        .chain(adjacent_excerpts)
 447                        .filter_map(deserialize_excerpt_range),
 448                    cx,
 449                );
 450            }
 451
 452            multibuffer.remove_excerpts(removed_excerpt_ids, cx);
 453            anyhow::Ok(())
 454        })
 455    })??;
 456
 457    // Deserialize the editor state.
 458    let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {
 459        let buffer = editor.buffer.read(cx).read(cx);
 460        let selections = message
 461            .selections
 462            .into_iter()
 463            .filter_map(|selection| deserialize_selection(&buffer, selection))
 464            .collect::<Vec<_>>();
 465        let pending_selection = message
 466            .pending_selection
 467            .and_then(|selection| deserialize_selection(&buffer, selection));
 468        let scroll_top_anchor = message
 469            .scroll_top_anchor
 470            .and_then(|anchor| deserialize_anchor(&buffer, anchor));
 471        anyhow::Ok((selections, pending_selection, scroll_top_anchor))
 472    })??;
 473
 474    // Wait until the buffer has received all of the operations referenced by
 475    // the editor's new state.
 476    this.update(cx, |editor, cx| {
 477        editor.buffer.update(cx, |buffer, cx| {
 478            buffer.wait_for_anchors(
 479                selections
 480                    .iter()
 481                    .chain(pending_selection.as_ref())
 482                    .flat_map(|selection| [selection.start, selection.end])
 483                    .chain(scroll_top_anchor),
 484                cx,
 485            )
 486        })
 487    })?
 488    .await?;
 489
 490    // Update the editor's state.
 491    this.update_in(cx, |editor, window, cx| {
 492        if !selections.is_empty() || pending_selection.is_some() {
 493            editor.set_selections_from_remote(selections, pending_selection, window, cx);
 494            editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
 495        } else if let Some(scroll_top_anchor) = scroll_top_anchor {
 496            editor.set_scroll_anchor_remote(
 497                ScrollAnchor {
 498                    anchor: scroll_top_anchor,
 499                    offset: point(message.scroll_x, message.scroll_y),
 500                },
 501                window,
 502                cx,
 503            );
 504        }
 505    })?;
 506    Ok(())
 507}
 508
 509fn serialize_excerpt(
 510    buffer_id: BufferId,
 511    id: &ExcerptId,
 512    range: &ExcerptRange<language::Anchor>,
 513) -> Option<proto::Excerpt> {
 514    Some(proto::Excerpt {
 515        id: id.to_proto(),
 516        buffer_id: buffer_id.into(),
 517        context_start: Some(serialize_text_anchor(&range.context.start)),
 518        context_end: Some(serialize_text_anchor(&range.context.end)),
 519        primary_start: Some(serialize_text_anchor(&range.primary.start)),
 520        primary_end: Some(serialize_text_anchor(&range.primary.end)),
 521    })
 522}
 523
 524fn serialize_selection(
 525    selection: &Selection<Anchor>,
 526    buffer: &MultiBufferSnapshot,
 527) -> proto::Selection {
 528    proto::Selection {
 529        id: selection.id as u64,
 530        start: Some(serialize_anchor(&selection.start, buffer)),
 531        end: Some(serialize_anchor(&selection.end, buffer)),
 532        reversed: selection.reversed,
 533    }
 534}
 535
 536fn serialize_anchor(anchor: &Anchor, buffer: &MultiBufferSnapshot) -> proto::EditorAnchor {
 537    proto::EditorAnchor {
 538        excerpt_id: buffer.latest_excerpt_id(anchor.excerpt_id).to_proto(),
 539        anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
 540    }
 541}
 542
 543fn deserialize_excerpt_range(
 544    excerpt: proto::Excerpt,
 545) -> Option<(ExcerptId, ExcerptRange<language::Anchor>)> {
 546    let context = {
 547        let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
 548        let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
 549        start..end
 550    };
 551    let primary = excerpt
 552        .primary_start
 553        .zip(excerpt.primary_end)
 554        .and_then(|(start, end)| {
 555            let start = language::proto::deserialize_anchor(start)?;
 556            let end = language::proto::deserialize_anchor(end)?;
 557            Some(start..end)
 558        })
 559        .unwrap_or_else(|| context.clone());
 560    Some((
 561        ExcerptId::from_proto(excerpt.id),
 562        ExcerptRange { context, primary },
 563    ))
 564}
 565
 566fn deserialize_selection(
 567    buffer: &MultiBufferSnapshot,
 568    selection: proto::Selection,
 569) -> Option<Selection<Anchor>> {
 570    Some(Selection {
 571        id: selection.id as usize,
 572        start: deserialize_anchor(buffer, selection.start?)?,
 573        end: deserialize_anchor(buffer, selection.end?)?,
 574        reversed: selection.reversed,
 575        goal: SelectionGoal::None,
 576    })
 577}
 578
 579fn deserialize_anchor(buffer: &MultiBufferSnapshot, anchor: proto::EditorAnchor) -> Option<Anchor> {
 580    let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
 581    Some(Anchor::in_buffer(
 582        excerpt_id,
 583        buffer.buffer_id_for_excerpt(excerpt_id)?,
 584        language::proto::deserialize_anchor(anchor.anchor?)?,
 585    ))
 586}
 587
 588impl Item for Editor {
 589    type Event = EditorEvent;
 590
 591    fn navigate(
 592        &mut self,
 593        data: Box<dyn std::any::Any>,
 594        window: &mut Window,
 595        cx: &mut Context<Self>,
 596    ) -> bool {
 597        if let Ok(data) = data.downcast::<NavigationData>() {
 598            let newest_selection = self.selections.newest::<Point>(cx);
 599            let buffer = self.buffer.read(cx).read(cx);
 600            let offset = if buffer.can_resolve(&data.cursor_anchor) {
 601                data.cursor_anchor.to_point(&buffer)
 602            } else {
 603                buffer.clip_point(data.cursor_position, Bias::Left)
 604            };
 605
 606            let mut scroll_anchor = data.scroll_anchor;
 607            if !buffer.can_resolve(&scroll_anchor.anchor) {
 608                scroll_anchor.anchor = buffer.anchor_before(
 609                    buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
 610                );
 611            }
 612
 613            drop(buffer);
 614
 615            if newest_selection.head() == offset {
 616                false
 617            } else {
 618                self.set_scroll_anchor(scroll_anchor, window, cx);
 619                self.change_selections(
 620                    SelectionEffects::default().nav_history(false),
 621                    window,
 622                    cx,
 623                    |s| s.select_ranges([offset..offset]),
 624                );
 625                true
 626            }
 627        } else {
 628            false
 629        }
 630    }
 631
 632    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
 633        let file_path = self
 634            .buffer()
 635            .read(cx)
 636            .as_singleton()?
 637            .read(cx)
 638            .file()
 639            .and_then(|f| f.as_local())?
 640            .abs_path(cx);
 641
 642        let file_path = file_path.compact().to_string_lossy().into_owned();
 643
 644        Some(file_path.into())
 645    }
 646
 647    fn telemetry_event_text(&self) -> Option<&'static str> {
 648        None
 649    }
 650
 651    fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
 652        if let Some(path) = path_for_buffer(&self.buffer, detail, true, cx) {
 653            path.to_string().into()
 654        } else {
 655            // Use the same logic as the displayed title for consistency
 656            self.buffer.read(cx).title(cx).to_string().into()
 657        }
 658    }
 659
 660    fn suggested_filename(&self, cx: &App) -> SharedString {
 661        self.buffer.read(cx).title(cx).to_string().into()
 662    }
 663
 664    fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
 665        ItemSettings::get_global(cx)
 666            .file_icons
 667            .then(|| {
 668                path_for_buffer(&self.buffer, 0, true, cx)
 669                    .and_then(|path| FileIcons::get_icon(Path::new(&*path), cx))
 670            })
 671            .flatten()
 672            .map(Icon::from_path)
 673    }
 674
 675    fn tab_content(&self, params: TabContentParams, _: &Window, cx: &App) -> AnyElement {
 676        let label_color = if ItemSettings::get_global(cx).git_status {
 677            self.buffer()
 678                .read(cx)
 679                .as_singleton()
 680                .and_then(|buffer| {
 681                    let buffer = buffer.read(cx);
 682                    let path = buffer.project_path(cx)?;
 683                    let buffer_id = buffer.remote_id();
 684                    let project = self.project()?.read(cx);
 685                    let entry = project.entry_for_path(&path, cx)?;
 686                    let (repo, repo_path) = project
 687                        .git_store()
 688                        .read(cx)
 689                        .repository_and_path_for_buffer_id(buffer_id, cx)?;
 690                    let status = repo.read(cx).status_for_path(&repo_path)?.status;
 691
 692                    Some(entry_git_aware_label_color(
 693                        status.summary(),
 694                        entry.is_ignored,
 695                        params.selected,
 696                    ))
 697                })
 698                .unwrap_or_else(|| entry_label_color(params.selected))
 699        } else {
 700            entry_label_color(params.selected)
 701        };
 702
 703        let description = params.detail.and_then(|detail| {
 704            let path = path_for_buffer(&self.buffer, detail, false, cx)?;
 705            let description = path.trim();
 706
 707            if description.is_empty() {
 708                return None;
 709            }
 710
 711            Some(util::truncate_and_trailoff(description, MAX_TAB_TITLE_LEN))
 712        });
 713
 714        // Whether the file was saved in the past but is now deleted.
 715        let was_deleted: bool = self
 716            .buffer()
 717            .read(cx)
 718            .as_singleton()
 719            .and_then(|buffer| buffer.read(cx).file())
 720            .is_some_and(|file| file.disk_state() == DiskState::Deleted);
 721
 722        h_flex()
 723            .gap_2()
 724            .child(
 725                Label::new(self.title(cx).to_string())
 726                    .color(label_color)
 727                    .when(params.preview, |this| this.italic())
 728                    .when(was_deleted, |this| this.strikethrough()),
 729            )
 730            .when_some(description, |this, description| {
 731                this.child(
 732                    Label::new(description)
 733                        .size(LabelSize::XSmall)
 734                        .color(Color::Muted),
 735                )
 736            })
 737            .into_any_element()
 738    }
 739
 740    fn for_each_project_item(
 741        &self,
 742        cx: &App,
 743        f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 744    ) {
 745        self.buffer
 746            .read(cx)
 747            .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
 748    }
 749
 750    fn is_singleton(&self, cx: &App) -> bool {
 751        self.buffer.read(cx).is_singleton()
 752    }
 753
 754    fn can_save_as(&self, cx: &App) -> bool {
 755        self.buffer.read(cx).is_singleton()
 756    }
 757
 758    fn clone_on_split(
 759        &self,
 760        _workspace_id: Option<WorkspaceId>,
 761        window: &mut Window,
 762        cx: &mut Context<Self>,
 763    ) -> Option<Entity<Editor>>
 764    where
 765        Self: Sized,
 766    {
 767        Some(cx.new(|cx| self.clone(window, cx)))
 768    }
 769
 770    fn set_nav_history(
 771        &mut self,
 772        history: ItemNavHistory,
 773        _window: &mut Window,
 774        _: &mut Context<Self>,
 775    ) {
 776        self.nav_history = Some(history);
 777    }
 778
 779    fn on_removed(&self, cx: &App) {
 780        self.report_editor_event(ReportEditorEvent::Closed, None, cx);
 781    }
 782
 783    fn deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 784        let selection = self.selections.newest_anchor();
 785        self.push_to_nav_history(selection.head(), None, true, false, cx);
 786    }
 787
 788    fn workspace_deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 789        self.hide_hovered_link(cx);
 790    }
 791
 792    fn is_dirty(&self, cx: &App) -> bool {
 793        self.buffer().read(cx).read(cx).is_dirty()
 794    }
 795
 796    fn has_deleted_file(&self, cx: &App) -> bool {
 797        self.buffer().read(cx).read(cx).has_deleted_file()
 798    }
 799
 800    fn has_conflict(&self, cx: &App) -> bool {
 801        self.buffer().read(cx).read(cx).has_conflict()
 802    }
 803
 804    fn can_save(&self, cx: &App) -> bool {
 805        let buffer = &self.buffer().read(cx);
 806        if let Some(buffer) = buffer.as_singleton() {
 807            buffer.read(cx).project_path(cx).is_some()
 808        } else {
 809            true
 810        }
 811    }
 812
 813    fn save(
 814        &mut self,
 815        options: SaveOptions,
 816        project: Entity<Project>,
 817        window: &mut Window,
 818        cx: &mut Context<Self>,
 819    ) -> Task<Result<()>> {
 820        // Add meta data tracking # of auto saves
 821        if options.autosave {
 822            self.report_editor_event(ReportEditorEvent::Saved { auto_saved: true }, None, cx);
 823        } else {
 824            self.report_editor_event(ReportEditorEvent::Saved { auto_saved: false }, None, cx);
 825        }
 826
 827        let buffers = self.buffer().clone().read(cx).all_buffers();
 828        let buffers = buffers
 829            .into_iter()
 830            .map(|handle| handle.read(cx).base_buffer().unwrap_or(handle.clone()))
 831            .collect::<HashSet<_>>();
 832
 833        // let mut buffers_to_save =
 834        let buffers_to_save = if self.buffer.read(cx).is_singleton() && !options.autosave {
 835            buffers
 836        } else {
 837            buffers
 838                .into_iter()
 839                .filter(|buffer| buffer.read(cx).is_dirty())
 840                .collect()
 841        };
 842
 843        cx.spawn_in(window, async move |this, cx| {
 844            if options.format {
 845                this.update_in(cx, |editor, window, cx| {
 846                    editor.perform_format(
 847                        project.clone(),
 848                        FormatTrigger::Save,
 849                        FormatTarget::Buffers(buffers_to_save.clone()),
 850                        window,
 851                        cx,
 852                    )
 853                })?
 854                .await?;
 855            }
 856
 857            if !buffers_to_save.is_empty() {
 858                project
 859                    .update(cx, |project, cx| {
 860                        project.save_buffers(buffers_to_save.clone(), cx)
 861                    })?
 862                    .await?;
 863            }
 864
 865            Ok(())
 866        })
 867    }
 868
 869    fn save_as(
 870        &mut self,
 871        project: Entity<Project>,
 872        path: ProjectPath,
 873        _: &mut Window,
 874        cx: &mut Context<Self>,
 875    ) -> Task<Result<()>> {
 876        let buffer = self
 877            .buffer()
 878            .read(cx)
 879            .as_singleton()
 880            .expect("cannot call save_as on an excerpt list");
 881
 882        let file_extension = path.path.extension().map(|a| a.to_string());
 883        self.report_editor_event(
 884            ReportEditorEvent::Saved { auto_saved: false },
 885            file_extension,
 886            cx,
 887        );
 888
 889        project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
 890    }
 891
 892    fn reload(
 893        &mut self,
 894        project: Entity<Project>,
 895        window: &mut Window,
 896        cx: &mut Context<Self>,
 897    ) -> Task<Result<()>> {
 898        let buffer = self.buffer().clone();
 899        let buffers = self.buffer.read(cx).all_buffers();
 900        let reload_buffers =
 901            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
 902        cx.spawn_in(window, async move |this, cx| {
 903            let transaction = reload_buffers.log_err().await;
 904            this.update(cx, |editor, cx| {
 905                editor.request_autoscroll(Autoscroll::fit(), cx)
 906            })?;
 907            buffer
 908                .update(cx, |buffer, cx| {
 909                    if let Some(transaction) = transaction
 910                        && !buffer.is_singleton()
 911                    {
 912                        buffer.push_transaction(&transaction.0, cx);
 913                    }
 914                })
 915                .ok();
 916            Ok(())
 917        })
 918    }
 919
 920    fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 921        Some(Box::new(handle.clone()))
 922    }
 923
 924    fn pixel_position_of_cursor(&self, _: &App) -> Option<gpui::Point<Pixels>> {
 925        self.pixel_position_of_newest_cursor
 926    }
 927
 928    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 929        if self.show_breadcrumbs {
 930            ToolbarItemLocation::PrimaryLeft
 931        } else {
 932            ToolbarItemLocation::Hidden
 933        }
 934    }
 935
 936    fn breadcrumbs(&self, variant: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 937        let cursor = self.selections.newest_anchor().head();
 938        let multibuffer = &self.buffer().read(cx);
 939        let (buffer_id, symbols) =
 940            multibuffer.symbols_containing(cursor, Some(variant.syntax()), cx)?;
 941        let buffer = multibuffer.buffer(buffer_id)?;
 942
 943        let buffer = buffer.read(cx);
 944        let text = self.breadcrumb_header.clone().unwrap_or_else(|| {
 945            buffer
 946                .snapshot()
 947                .resolve_file_path(
 948                    self.project
 949                        .as_ref()
 950                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 951                        .unwrap_or_default(),
 952                    cx,
 953                )
 954                .unwrap_or_else(|| {
 955                    if multibuffer.is_singleton() {
 956                        multibuffer.title(cx).to_string()
 957                    } else {
 958                        "untitled".to_string()
 959                    }
 960                })
 961        });
 962
 963        let settings = ThemeSettings::get_global(cx);
 964
 965        let mut breadcrumbs = vec![BreadcrumbText {
 966            text,
 967            highlights: None,
 968            font: Some(settings.buffer_font.clone()),
 969        }];
 970
 971        breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
 972            text: symbol.text,
 973            highlights: Some(symbol.highlight_ranges),
 974            font: Some(settings.buffer_font.clone()),
 975        }));
 976        Some(breadcrumbs)
 977    }
 978
 979    fn added_to_workspace(
 980        &mut self,
 981        workspace: &mut Workspace,
 982        _window: &mut Window,
 983        cx: &mut Context<Self>,
 984    ) {
 985        self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
 986        if let Some(workspace) = &workspace.weak_handle().upgrade() {
 987            cx.subscribe(workspace, |editor, _, event: &workspace::Event, _cx| {
 988                if let workspace::Event::ModalOpened = event {
 989                    editor.mouse_context_menu.take();
 990                    editor.inline_blame_popover.take();
 991                }
 992            })
 993            .detach();
 994        }
 995    }
 996
 997    fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
 998        match event {
 999            EditorEvent::Saved | EditorEvent::TitleChanged => {
1000                f(ItemEvent::UpdateTab);
1001                f(ItemEvent::UpdateBreadcrumbs);
1002            }
1003
1004            EditorEvent::Reparsed(_) => {
1005                f(ItemEvent::UpdateBreadcrumbs);
1006            }
1007
1008            EditorEvent::SelectionsChanged { local } if *local => {
1009                f(ItemEvent::UpdateBreadcrumbs);
1010            }
1011
1012            EditorEvent::BreadcrumbsChanged => {
1013                f(ItemEvent::UpdateBreadcrumbs);
1014            }
1015
1016            EditorEvent::DirtyChanged => {
1017                f(ItemEvent::UpdateTab);
1018            }
1019
1020            EditorEvent::BufferEdited => {
1021                f(ItemEvent::Edit);
1022                f(ItemEvent::UpdateBreadcrumbs);
1023            }
1024
1025            EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
1026                f(ItemEvent::Edit);
1027            }
1028
1029            _ => {}
1030        }
1031    }
1032
1033    fn preserve_preview(&self, cx: &App) -> bool {
1034        self.buffer.read(cx).preserve_preview(cx)
1035    }
1036}
1037
1038impl SerializableItem for Editor {
1039    fn serialized_item_kind() -> &'static str {
1040        "Editor"
1041    }
1042
1043    fn cleanup(
1044        workspace_id: WorkspaceId,
1045        alive_items: Vec<ItemId>,
1046        _window: &mut Window,
1047        cx: &mut App,
1048    ) -> Task<Result<()>> {
1049        workspace::delete_unloaded_items(alive_items, workspace_id, "editors", &DB, cx)
1050    }
1051
1052    fn deserialize(
1053        project: Entity<Project>,
1054        workspace: WeakEntity<Workspace>,
1055        workspace_id: workspace::WorkspaceId,
1056        item_id: ItemId,
1057        window: &mut Window,
1058        cx: &mut App,
1059    ) -> Task<Result<Entity<Self>>> {
1060        let serialized_editor = match DB
1061            .get_serialized_editor(item_id, workspace_id)
1062            .context("Failed to query editor state")
1063        {
1064            Ok(Some(serialized_editor)) => {
1065                if ProjectSettings::get_global(cx)
1066                    .session
1067                    .restore_unsaved_buffers
1068                {
1069                    serialized_editor
1070                } else {
1071                    SerializedEditor {
1072                        abs_path: serialized_editor.abs_path,
1073                        contents: None,
1074                        language: None,
1075                        mtime: None,
1076                    }
1077                }
1078            }
1079            Ok(None) => {
1080                return Task::ready(Err(anyhow!("No path or contents found for buffer")));
1081            }
1082            Err(error) => {
1083                return Task::ready(Err(error));
1084            }
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
1115                    // Then set the text so that the dirty bit is set correctly
1116                    buffer.update(cx, |buffer, cx| {
1117                        buffer.set_language_registry(language_registry);
1118                        if let Some(language) = language {
1119                            buffer.set_language(Some(language), cx);
1120                        }
1121                        buffer.set_text(contents, cx);
1122                        if let Some(entry) = buffer.peek_undo_stack() {
1123                            buffer.forget_transaction(entry.transaction_id());
1124                        }
1125                    })?;
1126
1127                    cx.update(|window, cx| {
1128                        cx.new(|cx| {
1129                            let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1130
1131                            editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1132                            editor
1133                        })
1134                    })
1135                }
1136            }),
1137            SerializedEditor {
1138                abs_path: Some(abs_path),
1139                contents,
1140                mtime,
1141                ..
1142            } => {
1143                let opened_buffer = project.update(cx, |project, cx| {
1144                    let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1145                    let project_path = ProjectPath {
1146                        worktree_id: worktree.read(cx).id(),
1147                        path: path,
1148                    };
1149                    Some(project.open_path(project_path, cx))
1150                });
1151
1152                match opened_buffer {
1153                    Some(opened_buffer) => {
1154                        window.spawn(cx, async move |cx| {
1155                            let (_, buffer) = opened_buffer.await?;
1156
1157                            // This is a bit wasteful: we're loading the whole buffer from
1158                            // disk and then overwrite the content.
1159                            // But for now, it keeps the implementation of the content serialization
1160                            // simple, because we don't have to persist all of the metadata that we get
1161                            // by loading the file (git diff base, ...).
1162                            if let Some(buffer_text) = contents {
1163                                buffer.update(cx, |buffer, cx| {
1164                                    // If we did restore an mtime, we want to store it on the buffer
1165                                    // so that the next edit will mark the buffer as dirty/conflicted.
1166                                    if mtime.is_some() {
1167                                        buffer.did_reload(
1168                                            buffer.version(),
1169                                            buffer.line_ending(),
1170                                            mtime,
1171                                            cx,
1172                                        );
1173                                    }
1174                                    buffer.set_text(buffer_text, cx);
1175                                    if let Some(entry) = buffer.peek_undo_stack() {
1176                                        buffer.forget_transaction(entry.transaction_id());
1177                                    }
1178                                })?;
1179                            }
1180
1181                            cx.update(|window, cx| {
1182                                cx.new(|cx| {
1183                                    let mut editor =
1184                                        Editor::for_buffer(buffer, Some(project), window, cx);
1185
1186                                    editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1187                                    editor
1188                                })
1189                            })
1190                        })
1191                    }
1192                    None => {
1193                        let open_by_abs_path = workspace.update(cx, |workspace, cx| {
1194                            workspace.open_abs_path(
1195                                abs_path.clone(),
1196                                OpenOptions {
1197                                    visible: Some(OpenVisible::None),
1198                                    ..Default::default()
1199                                },
1200                                window,
1201                                cx,
1202                            )
1203                        });
1204                        window.spawn(cx, async move |cx| {
1205                            let editor = open_by_abs_path?.await?.downcast::<Editor>().with_context(|| format!("Failed to downcast to Editor after opening abs path {abs_path:?}"))?;
1206                            editor.update_in(cx, |editor, window, cx| {
1207                                editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1208                            })?;
1209                            Ok(editor)
1210                        })
1211                    }
1212                }
1213            }
1214            SerializedEditor {
1215                abs_path: None,
1216                contents: None,
1217                ..
1218            } => window.spawn(cx, async move |cx| {
1219                let buffer = project
1220                    .update(cx, |project, cx| project.create_buffer(true, cx))?
1221                    .await?;
1222
1223                cx.update(|window, cx| {
1224                    cx.new(|cx| {
1225                        let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1226
1227                        editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1228                        editor
1229                    })
1230                })
1231            }),
1232        }
1233    }
1234
1235    fn serialize(
1236        &mut self,
1237        workspace: &mut Workspace,
1238        item_id: ItemId,
1239        closing: bool,
1240        window: &mut Window,
1241        cx: &mut Context<Self>,
1242    ) -> Option<Task<Result<()>>> {
1243        if self.mode.is_minimap() {
1244            return None;
1245        }
1246        let mut serialize_dirty_buffers = self.serialize_dirty_buffers;
1247
1248        let project = self.project.clone()?;
1249        if project.read(cx).visible_worktrees(cx).next().is_none() {
1250            // If we don't have a worktree, we don't serialize, because
1251            // projects without worktrees aren't deserialized.
1252            serialize_dirty_buffers = false;
1253        }
1254
1255        if closing && !serialize_dirty_buffers {
1256            return None;
1257        }
1258
1259        let workspace_id = workspace.database_id()?;
1260
1261        let buffer = self.buffer().read(cx).as_singleton()?;
1262
1263        let abs_path = buffer.read(cx).file().and_then(|file| {
1264            let worktree_id = file.worktree_id(cx);
1265            project
1266                .read(cx)
1267                .worktree_for_id(worktree_id, cx)
1268                .map(|worktree| worktree.read(cx).absolutize(file.path()))
1269                .or_else(|| {
1270                    let full_path = file.full_path(cx);
1271                    let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1272                    project.read(cx).absolute_path(&project_path, cx)
1273                })
1274        });
1275
1276        let is_dirty = buffer.read(cx).is_dirty();
1277        let mtime = buffer.read(cx).saved_mtime();
1278
1279        let snapshot = buffer.read(cx).snapshot();
1280
1281        Some(cx.spawn_in(window, async move |_this, cx| {
1282            cx.background_spawn(async move {
1283                let (contents, language) = if serialize_dirty_buffers && is_dirty {
1284                    let contents = snapshot.text();
1285                    let language = snapshot.language().map(|lang| lang.name().to_string());
1286                    (Some(contents), language)
1287                } else {
1288                    (None, None)
1289                };
1290
1291                let editor = SerializedEditor {
1292                    abs_path,
1293                    contents,
1294                    language,
1295                    mtime,
1296                };
1297                log::debug!("Serializing editor {item_id:?} in workspace {workspace_id:?}");
1298                DB.save_serialized_editor(item_id, workspace_id, editor)
1299                    .await
1300                    .context("failed to save serialized editor")
1301            })
1302            .await
1303            .context("failed to save contents of buffer")?;
1304
1305            Ok(())
1306        }))
1307    }
1308
1309    fn should_serialize(&self, event: &Self::Event) -> bool {
1310        matches!(
1311            event,
1312            EditorEvent::Saved | EditorEvent::DirtyChanged | EditorEvent::BufferEdited
1313        )
1314    }
1315}
1316
1317#[derive(Debug, Default)]
1318struct EditorRestorationData {
1319    entries: HashMap<PathBuf, RestorationData>,
1320}
1321
1322#[derive(Default, Debug)]
1323pub struct RestorationData {
1324    pub scroll_position: (BufferRow, gpui::Point<ScrollOffset>),
1325    pub folds: Vec<Range<Point>>,
1326    pub selections: Vec<Range<Point>>,
1327}
1328
1329impl ProjectItem for Editor {
1330    type Item = Buffer;
1331
1332    fn project_item_kind() -> Option<ProjectItemKind> {
1333        Some(ProjectItemKind("Editor"))
1334    }
1335
1336    fn for_project_item(
1337        project: Entity<Project>,
1338        pane: Option<&Pane>,
1339        buffer: Entity<Buffer>,
1340        window: &mut Window,
1341        cx: &mut Context<Self>,
1342    ) -> Self {
1343        let mut editor = Self::for_buffer(buffer.clone(), Some(project), window, cx);
1344        if let Some((excerpt_id, buffer_id, snapshot)) =
1345            editor.buffer().read(cx).snapshot(cx).as_singleton()
1346            && WorkspaceSettings::get(None, cx).restore_on_file_reopen
1347            && let Some(restoration_data) = Self::project_item_kind()
1348                .and_then(|kind| pane.as_ref()?.project_item_restoration_data.get(&kind))
1349                .and_then(|data| data.downcast_ref::<EditorRestorationData>())
1350                .and_then(|data| {
1351                    let file = project::File::from_dyn(buffer.read(cx).file())?;
1352                    data.entries.get(&file.abs_path(cx))
1353                })
1354        {
1355            editor.fold_ranges(
1356                clip_ranges(&restoration_data.folds, snapshot),
1357                false,
1358                window,
1359                cx,
1360            );
1361            if !restoration_data.selections.is_empty() {
1362                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1363                    s.select_ranges(clip_ranges(&restoration_data.selections, snapshot));
1364                });
1365            }
1366            let (top_row, offset) = restoration_data.scroll_position;
1367            let anchor = Anchor::in_buffer(
1368                *excerpt_id,
1369                buffer_id,
1370                snapshot.anchor_before(Point::new(top_row, 0)),
1371            );
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<InvalidBufferView> {
1385        Some(InvalidBufferView::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).buffer_snapshot;
1540        let selection = self.selections.newest_adjusted(cx);
1541
1542        match setting {
1543            SeedQuerySetting::Never => String::new(),
1544            SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1545                let text: String = snapshot
1546                    .text_for_range(selection.start..selection.end)
1547                    .collect();
1548                if text.contains('\n') {
1549                    String::new()
1550                } else {
1551                    text
1552                }
1553            }
1554            SeedQuerySetting::Selection => String::new(),
1555            SeedQuerySetting::Always => {
1556                let (range, kind) =
1557                    snapshot.surrounding_word(selection.start, Some(CharScopeContext::Completion));
1558                if kind == Some(CharKind::Word) {
1559                    let text: String = snapshot.text_for_range(range).collect();
1560                    if !text.trim().is_empty() {
1561                        return text;
1562                    }
1563                }
1564                String::new()
1565            }
1566        }
1567    }
1568
1569    fn activate_match(
1570        &mut self,
1571        index: usize,
1572        matches: &[Range<Anchor>],
1573        window: &mut Window,
1574        cx: &mut Context<Self>,
1575    ) {
1576        self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1577        let range = self.range_for_match(&matches[index]);
1578        self.change_selections(Default::default(), window, cx, |s| {
1579            s.select_ranges([range]);
1580        })
1581    }
1582
1583    fn select_matches(
1584        &mut self,
1585        matches: &[Self::Match],
1586        window: &mut Window,
1587        cx: &mut Context<Self>,
1588    ) {
1589        self.unfold_ranges(matches, false, false, cx);
1590        self.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1591            s.select_ranges(matches.iter().cloned())
1592        });
1593    }
1594    fn replace(
1595        &mut self,
1596        identifier: &Self::Match,
1597        query: &SearchQuery,
1598        window: &mut Window,
1599        cx: &mut Context<Self>,
1600    ) {
1601        let text = self.buffer.read(cx);
1602        let text = text.snapshot(cx);
1603        let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1604        let text: Cow<_> = if text.len() == 1 {
1605            text.first().cloned().unwrap().into()
1606        } else {
1607            let joined_chunks = text.join("");
1608            joined_chunks.into()
1609        };
1610
1611        if let Some(replacement) = query.replacement_for(&text) {
1612            self.transact(window, cx, |this, _, cx| {
1613                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1614            });
1615        }
1616    }
1617    fn replace_all(
1618        &mut self,
1619        matches: &mut dyn Iterator<Item = &Self::Match>,
1620        query: &SearchQuery,
1621        window: &mut Window,
1622        cx: &mut Context<Self>,
1623    ) {
1624        let text = self.buffer.read(cx);
1625        let text = text.snapshot(cx);
1626        let mut edits = vec![];
1627
1628        for m in matches {
1629            let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1630
1631            let text: Cow<_> = if text.len() == 1 {
1632                text.first().cloned().unwrap().into()
1633            } else {
1634                let joined_chunks = text.join("");
1635                joined_chunks.into()
1636            };
1637
1638            if let Some(replacement) = query.replacement_for(&text) {
1639                edits.push((m.clone(), Arc::from(&*replacement)));
1640            }
1641        }
1642
1643        if !edits.is_empty() {
1644            self.transact(window, cx, |this, _, cx| {
1645                this.edit(edits, cx);
1646            });
1647        }
1648    }
1649    fn match_index_for_direction(
1650        &mut self,
1651        matches: &[Range<Anchor>],
1652        current_index: usize,
1653        direction: Direction,
1654        count: usize,
1655        _: &mut Window,
1656        cx: &mut Context<Self>,
1657    ) -> usize {
1658        let buffer = self.buffer().read(cx).snapshot(cx);
1659        let current_index_position = if self.selections.disjoint_anchors_arc().len() == 1 {
1660            self.selections.newest_anchor().head()
1661        } else {
1662            matches[current_index].start
1663        };
1664
1665        let mut count = count % matches.len();
1666        if count == 0 {
1667            return current_index;
1668        }
1669        match direction {
1670            Direction::Next => {
1671                if matches[current_index]
1672                    .start
1673                    .cmp(&current_index_position, &buffer)
1674                    .is_gt()
1675                {
1676                    count -= 1
1677                }
1678
1679                (current_index + count) % matches.len()
1680            }
1681            Direction::Prev => {
1682                if matches[current_index]
1683                    .end
1684                    .cmp(&current_index_position, &buffer)
1685                    .is_lt()
1686                {
1687                    count -= 1;
1688                }
1689
1690                if current_index >= count {
1691                    current_index - count
1692                } else {
1693                    matches.len() - (count - current_index)
1694                }
1695            }
1696        }
1697    }
1698
1699    fn find_matches(
1700        &mut self,
1701        query: Arc<project::search::SearchQuery>,
1702        _: &mut Window,
1703        cx: &mut Context<Self>,
1704    ) -> Task<Vec<Range<Anchor>>> {
1705        let buffer = self.buffer().read(cx).snapshot(cx);
1706        let search_within_ranges = self
1707            .background_highlights
1708            .get(&HighlightKey::Type(TypeId::of::<SearchWithinRange>()))
1709            .map_or(vec![], |(_color, ranges)| {
1710                ranges.iter().cloned().collect::<Vec<_>>()
1711            });
1712
1713        cx.background_spawn(async move {
1714            let mut ranges = Vec::new();
1715
1716            let search_within_ranges = if search_within_ranges.is_empty() {
1717                vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())]
1718            } else {
1719                search_within_ranges
1720            };
1721
1722            for range in search_within_ranges {
1723                for (search_buffer, search_range, excerpt_id, deleted_hunk_anchor) in
1724                    buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1725                {
1726                    ranges.extend(
1727                        query
1728                            .search(search_buffer, Some(search_range.clone()))
1729                            .await
1730                            .into_iter()
1731                            .map(|match_range| {
1732                                if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
1733                                    let start = search_buffer
1734                                        .anchor_after(search_range.start + match_range.start);
1735                                    let end = search_buffer
1736                                        .anchor_before(search_range.start + match_range.end);
1737                                    deleted_hunk_anchor.with_diff_base_anchor(start)
1738                                        ..deleted_hunk_anchor.with_diff_base_anchor(end)
1739                                } else {
1740                                    let start = search_buffer
1741                                        .anchor_after(search_range.start + match_range.start);
1742                                    let end = search_buffer
1743                                        .anchor_before(search_range.start + match_range.end);
1744                                    Anchor::range_in_buffer(
1745                                        excerpt_id,
1746                                        search_buffer.remote_id(),
1747                                        start..end,
1748                                    )
1749                                }
1750                            }),
1751                    );
1752                }
1753            }
1754
1755            ranges
1756        })
1757    }
1758
1759    fn active_match_index(
1760        &mut self,
1761        direction: Direction,
1762        matches: &[Range<Anchor>],
1763        _: &mut Window,
1764        cx: &mut Context<Self>,
1765    ) -> Option<usize> {
1766        active_match_index(
1767            direction,
1768            matches,
1769            &self.selections.newest_anchor().head(),
1770            &self.buffer().read(cx).snapshot(cx),
1771        )
1772    }
1773
1774    fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
1775        self.expect_bounds_change = self.last_bounds;
1776    }
1777}
1778
1779pub fn active_match_index(
1780    direction: Direction,
1781    ranges: &[Range<Anchor>],
1782    cursor: &Anchor,
1783    buffer: &MultiBufferSnapshot,
1784) -> Option<usize> {
1785    if ranges.is_empty() {
1786        None
1787    } else {
1788        let r = ranges.binary_search_by(|probe| {
1789            if probe.end.cmp(cursor, buffer).is_lt() {
1790                Ordering::Less
1791            } else if probe.start.cmp(cursor, buffer).is_gt() {
1792                Ordering::Greater
1793            } else {
1794                Ordering::Equal
1795            }
1796        });
1797        match direction {
1798            Direction::Prev => match r {
1799                Ok(i) => Some(i),
1800                Err(i) => Some(i.saturating_sub(1)),
1801            },
1802            Direction::Next => match r {
1803                Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1804            },
1805        }
1806    }
1807}
1808
1809pub fn entry_label_color(selected: bool) -> Color {
1810    if selected {
1811        Color::Default
1812    } else {
1813        Color::Muted
1814    }
1815}
1816
1817pub fn entry_diagnostic_aware_icon_name_and_color(
1818    diagnostic_severity: Option<DiagnosticSeverity>,
1819) -> Option<(IconName, Color)> {
1820    match diagnostic_severity {
1821        Some(DiagnosticSeverity::ERROR) => Some((IconName::Close, Color::Error)),
1822        Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1823        _ => None,
1824    }
1825}
1826
1827pub fn entry_diagnostic_aware_icon_decoration_and_color(
1828    diagnostic_severity: Option<DiagnosticSeverity>,
1829) -> Option<(IconDecorationKind, Color)> {
1830    match diagnostic_severity {
1831        Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1832        Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1833        _ => None,
1834    }
1835}
1836
1837pub fn entry_git_aware_label_color(git_status: GitSummary, ignored: bool, selected: bool) -> Color {
1838    let tracked = git_status.index + git_status.worktree;
1839    if ignored {
1840        Color::Ignored
1841    } else if git_status.conflict > 0 {
1842        Color::Conflict
1843    } else if tracked.modified > 0 {
1844        Color::Modified
1845    } else if tracked.added > 0 || git_status.untracked > 0 {
1846        Color::Created
1847    } else {
1848        entry_label_color(selected)
1849    }
1850}
1851
1852fn path_for_buffer<'a>(
1853    buffer: &Entity<MultiBuffer>,
1854    height: usize,
1855    include_filename: bool,
1856    cx: &'a App,
1857) -> Option<Cow<'a, str>> {
1858    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1859    path_for_file(file.as_ref(), height, include_filename, cx)
1860}
1861
1862fn path_for_file<'a>(
1863    file: &'a dyn language::File,
1864    mut height: usize,
1865    include_filename: bool,
1866    cx: &'a App,
1867) -> Option<Cow<'a, str>> {
1868    // Ensure we always render at least the filename.
1869    height += 1;
1870
1871    let mut prefix = file.path().as_ref();
1872    while height > 0 {
1873        if let Some(parent) = prefix.parent() {
1874            prefix = parent;
1875            height -= 1;
1876        } else {
1877            break;
1878        }
1879    }
1880
1881    // The full_path method allocates, so avoid calling it if height is zero.
1882    if height > 0 {
1883        let mut full_path = file.full_path(cx);
1884        if !include_filename {
1885            if !full_path.pop() {
1886                return None;
1887            }
1888        }
1889        Some(full_path.to_string_lossy().into_owned().into())
1890    } else {
1891        let mut path = file.path().strip_prefix(prefix).ok()?;
1892        if !include_filename {
1893            path = path.parent()?;
1894        }
1895        Some(path.display(file.path_style(cx)))
1896    }
1897}
1898
1899#[cfg(test)]
1900mod tests {
1901    use crate::editor_tests::init_test;
1902    use fs::Fs;
1903
1904    use super::*;
1905    use fs::MTime;
1906    use gpui::{App, VisualTestContext};
1907    use language::{LanguageMatcher, TestFile};
1908    use project::FakeFs;
1909    use std::path::{Path, PathBuf};
1910    use util::{path, rel_path::RelPath};
1911
1912    #[gpui::test]
1913    fn test_path_for_file(cx: &mut App) {
1914        let file = TestFile {
1915            path: RelPath::empty().into(),
1916            root_name: String::new(),
1917            local_root: None,
1918        };
1919        assert_eq!(path_for_file(&file, 0, false, cx), None);
1920    }
1921
1922    async fn deserialize_editor(
1923        item_id: ItemId,
1924        workspace_id: WorkspaceId,
1925        workspace: Entity<Workspace>,
1926        project: Entity<Project>,
1927        cx: &mut VisualTestContext,
1928    ) -> Entity<Editor> {
1929        workspace
1930            .update_in(cx, |workspace, window, cx| {
1931                let pane = workspace.active_pane();
1932                pane.update(cx, |_, cx| {
1933                    Editor::deserialize(
1934                        project.clone(),
1935                        workspace.weak_handle(),
1936                        workspace_id,
1937                        item_id,
1938                        window,
1939                        cx,
1940                    )
1941                })
1942            })
1943            .await
1944            .unwrap()
1945    }
1946
1947    fn rust_language() -> Arc<language::Language> {
1948        Arc::new(language::Language::new(
1949            language::LanguageConfig {
1950                name: "Rust".into(),
1951                matcher: LanguageMatcher {
1952                    path_suffixes: vec!["rs".to_string()],
1953                    ..Default::default()
1954                },
1955                ..Default::default()
1956            },
1957            Some(tree_sitter_rust::LANGUAGE.into()),
1958        ))
1959    }
1960
1961    #[gpui::test]
1962    async fn test_deserialize(cx: &mut gpui::TestAppContext) {
1963        init_test(cx, |_| {});
1964
1965        let fs = FakeFs::new(cx.executor());
1966        fs.insert_file(path!("/file.rs"), Default::default()).await;
1967
1968        // Test case 1: Deserialize with path and contents
1969        {
1970            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1971            let (workspace, cx) =
1972                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1973            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1974            let item_id = 1234 as ItemId;
1975            let mtime = fs
1976                .metadata(Path::new(path!("/file.rs")))
1977                .await
1978                .unwrap()
1979                .unwrap()
1980                .mtime;
1981
1982            let serialized_editor = SerializedEditor {
1983                abs_path: Some(PathBuf::from(path!("/file.rs"))),
1984                contents: Some("fn main() {}".to_string()),
1985                language: Some("Rust".to_string()),
1986                mtime: Some(mtime),
1987            };
1988
1989            DB.save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
1990                .await
1991                .unwrap();
1992
1993            let deserialized =
1994                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1995
1996            deserialized.update(cx, |editor, cx| {
1997                assert_eq!(editor.text(cx), "fn main() {}");
1998                assert!(editor.is_dirty(cx));
1999                assert!(!editor.has_conflict(cx));
2000                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2001                assert!(buffer.file().is_some());
2002            });
2003        }
2004
2005        // Test case 2: Deserialize with only path
2006        {
2007            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2008            let (workspace, cx) =
2009                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2010
2011            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2012
2013            let item_id = 5678 as ItemId;
2014            let serialized_editor = SerializedEditor {
2015                abs_path: Some(PathBuf::from(path!("/file.rs"))),
2016                contents: None,
2017                language: None,
2018                mtime: None,
2019            };
2020
2021            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2022                .await
2023                .unwrap();
2024
2025            let deserialized =
2026                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2027
2028            deserialized.update(cx, |editor, cx| {
2029                assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
2030                assert!(!editor.is_dirty(cx));
2031                assert!(!editor.has_conflict(cx));
2032
2033                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2034                assert!(buffer.file().is_some());
2035            });
2036        }
2037
2038        // Test case 3: Deserialize with no path (untitled buffer, with content and language)
2039        {
2040            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2041            // Add Rust to the language, so that we can restore the language of the buffer
2042            project.read_with(cx, |project, _| project.languages().add(rust_language()));
2043
2044            let (workspace, cx) =
2045                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2046
2047            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2048
2049            let item_id = 9012 as ItemId;
2050            let serialized_editor = SerializedEditor {
2051                abs_path: None,
2052                contents: Some("hello".to_string()),
2053                language: Some("Rust".to_string()),
2054                mtime: None,
2055            };
2056
2057            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2058                .await
2059                .unwrap();
2060
2061            let deserialized =
2062                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2063
2064            deserialized.update(cx, |editor, cx| {
2065                assert_eq!(editor.text(cx), "hello");
2066                assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
2067
2068                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2069                assert_eq!(
2070                    buffer.language().map(|lang| lang.name()),
2071                    Some("Rust".into())
2072                ); // Language should be set to Rust
2073                assert!(buffer.file().is_none()); // The buffer should not have an associated file
2074            });
2075        }
2076
2077        // Test case 4: Deserialize with path, content, and old mtime
2078        {
2079            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2080            let (workspace, cx) =
2081                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2082
2083            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2084
2085            let item_id = 9345 as ItemId;
2086            let old_mtime = MTime::from_seconds_and_nanos(0, 50);
2087            let serialized_editor = SerializedEditor {
2088                abs_path: Some(PathBuf::from(path!("/file.rs"))),
2089                contents: Some("fn main() {}".to_string()),
2090                language: Some("Rust".to_string()),
2091                mtime: Some(old_mtime),
2092            };
2093
2094            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2095                .await
2096                .unwrap();
2097
2098            let deserialized =
2099                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2100
2101            deserialized.update(cx, |editor, cx| {
2102                assert_eq!(editor.text(cx), "fn main() {}");
2103                assert!(editor.has_conflict(cx)); // The editor should have a conflict
2104            });
2105        }
2106
2107        // Test case 5: Deserialize with no path, no content, no language, and no old mtime (new, empty, unsaved buffer)
2108        {
2109            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2110            let (workspace, cx) =
2111                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2112
2113            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2114
2115            let item_id = 10000 as ItemId;
2116            let serialized_editor = SerializedEditor {
2117                abs_path: None,
2118                contents: None,
2119                language: None,
2120                mtime: None,
2121            };
2122
2123            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2124                .await
2125                .unwrap();
2126
2127            let deserialized =
2128                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2129
2130            deserialized.update(cx, |editor, cx| {
2131                assert_eq!(editor.text(cx), "");
2132                assert!(!editor.is_dirty(cx));
2133                assert!(!editor.has_conflict(cx));
2134
2135                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2136                assert!(buffer.file().is_none());
2137            });
2138        }
2139    }
2140}