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