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    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, 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 act_as_type<'a>(
 592        &'a self,
 593        type_id: TypeId,
 594        self_handle: &'a Entity<Self>,
 595        cx: &'a App,
 596    ) -> Option<gpui::AnyEntity> {
 597        if TypeId::of::<Self>() == type_id {
 598            Some(self_handle.clone().into())
 599        } else if TypeId::of::<MultiBuffer>() == type_id {
 600            Some(self_handle.read(cx).buffer.clone().into())
 601        } else {
 602            None
 603        }
 604    }
 605
 606    fn navigate(
 607        &mut self,
 608        data: Box<dyn std::any::Any>,
 609        window: &mut Window,
 610        cx: &mut Context<Self>,
 611    ) -> bool {
 612        if let Ok(data) = data.downcast::<NavigationData>() {
 613            let newest_selection = self.selections.newest::<Point>(&self.display_snapshot(cx));
 614            let buffer = self.buffer.read(cx).read(cx);
 615            let offset = if buffer.can_resolve(&data.cursor_anchor) {
 616                data.cursor_anchor.to_point(&buffer)
 617            } else {
 618                buffer.clip_point(data.cursor_position, Bias::Left)
 619            };
 620
 621            let mut scroll_anchor = data.scroll_anchor;
 622            if !buffer.can_resolve(&scroll_anchor.anchor) {
 623                scroll_anchor.anchor = buffer.anchor_before(
 624                    buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
 625                );
 626            }
 627
 628            drop(buffer);
 629
 630            if newest_selection.head() == offset {
 631                false
 632            } else {
 633                self.set_scroll_anchor(scroll_anchor, window, cx);
 634                self.change_selections(
 635                    SelectionEffects::default().nav_history(false),
 636                    window,
 637                    cx,
 638                    |s| s.select_ranges([offset..offset]),
 639                );
 640                true
 641            }
 642        } else {
 643            false
 644        }
 645    }
 646
 647    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
 648        let file_path = self
 649            .buffer()
 650            .read(cx)
 651            .as_singleton()?
 652            .read(cx)
 653            .file()
 654            .and_then(|f| f.as_local())?
 655            .abs_path(cx);
 656
 657        let file_path = file_path.compact().to_string_lossy().into_owned();
 658
 659        Some(file_path.into())
 660    }
 661
 662    fn telemetry_event_text(&self) -> Option<&'static str> {
 663        None
 664    }
 665
 666    fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
 667        if let Some(path) = path_for_buffer(&self.buffer, detail, true, cx) {
 668            path.to_string().into()
 669        } else {
 670            // Use the same logic as the displayed title for consistency
 671            self.buffer.read(cx).title(cx).to_string().into()
 672        }
 673    }
 674
 675    fn suggested_filename(&self, cx: &App) -> SharedString {
 676        self.buffer.read(cx).title(cx).to_string().into()
 677    }
 678
 679    fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
 680        ItemSettings::get_global(cx)
 681            .file_icons
 682            .then(|| {
 683                path_for_buffer(&self.buffer, 0, true, cx)
 684                    .and_then(|path| FileIcons::get_icon(Path::new(&*path), cx))
 685            })
 686            .flatten()
 687            .map(Icon::from_path)
 688    }
 689
 690    fn tab_content(&self, params: TabContentParams, _: &Window, cx: &App) -> AnyElement {
 691        let label_color = if ItemSettings::get_global(cx).git_status {
 692            self.buffer()
 693                .read(cx)
 694                .as_singleton()
 695                .and_then(|buffer| {
 696                    let buffer = buffer.read(cx);
 697                    let path = buffer.project_path(cx)?;
 698                    let buffer_id = buffer.remote_id();
 699                    let project = self.project()?.read(cx);
 700                    let entry = project.entry_for_path(&path, cx)?;
 701                    let (repo, repo_path) = project
 702                        .git_store()
 703                        .read(cx)
 704                        .repository_and_path_for_buffer_id(buffer_id, cx)?;
 705                    let status = repo.read(cx).status_for_path(&repo_path)?.status;
 706
 707                    Some(entry_git_aware_label_color(
 708                        status.summary(),
 709                        entry.is_ignored,
 710                        params.selected,
 711                    ))
 712                })
 713                .unwrap_or_else(|| entry_label_color(params.selected))
 714        } else {
 715            entry_label_color(params.selected)
 716        };
 717
 718        let description = params.detail.and_then(|detail| {
 719            let path = path_for_buffer(&self.buffer, detail, false, cx)?;
 720            let description = path.trim();
 721
 722            if description.is_empty() {
 723                return None;
 724            }
 725
 726            Some(util::truncate_and_trailoff(description, MAX_TAB_TITLE_LEN))
 727        });
 728
 729        // Whether the file was saved in the past but is now deleted.
 730        let was_deleted: bool = self
 731            .buffer()
 732            .read(cx)
 733            .as_singleton()
 734            .and_then(|buffer| buffer.read(cx).file())
 735            .is_some_and(|file| file.disk_state() == DiskState::Deleted);
 736
 737        h_flex()
 738            .gap_2()
 739            .child(
 740                Label::new(self.title(cx).to_string())
 741                    .color(label_color)
 742                    .when(params.preview, |this| this.italic())
 743                    .when(was_deleted, |this| this.strikethrough()),
 744            )
 745            .when_some(description, |this, description| {
 746                this.child(
 747                    Label::new(description)
 748                        .size(LabelSize::XSmall)
 749                        .color(Color::Muted),
 750                )
 751            })
 752            .into_any_element()
 753    }
 754
 755    fn for_each_project_item(
 756        &self,
 757        cx: &App,
 758        f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 759    ) {
 760        self.buffer
 761            .read(cx)
 762            .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
 763    }
 764
 765    fn buffer_kind(&self, cx: &App) -> ItemBufferKind {
 766        match self.buffer.read(cx).is_singleton() {
 767            true => ItemBufferKind::Singleton,
 768            false => ItemBufferKind::Multibuffer,
 769        }
 770    }
 771
 772    fn can_save_as(&self, cx: &App) -> bool {
 773        self.buffer.read(cx).is_singleton()
 774    }
 775
 776    fn can_split(&self) -> bool {
 777        true
 778    }
 779
 780    fn clone_on_split(
 781        &self,
 782        _workspace_id: Option<WorkspaceId>,
 783        window: &mut Window,
 784        cx: &mut Context<Self>,
 785    ) -> Task<Option<Entity<Editor>>>
 786    where
 787        Self: Sized,
 788    {
 789        Task::ready(Some(cx.new(|cx| self.clone(window, cx))))
 790    }
 791
 792    fn set_nav_history(
 793        &mut self,
 794        history: ItemNavHistory,
 795        _window: &mut Window,
 796        _: &mut Context<Self>,
 797    ) {
 798        self.nav_history = Some(history);
 799    }
 800
 801    fn on_removed(&self, cx: &App) {
 802        self.report_editor_event(ReportEditorEvent::Closed, None, cx);
 803    }
 804
 805    fn deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 806        let selection = self.selections.newest_anchor();
 807        self.push_to_nav_history(selection.head(), None, true, false, cx);
 808    }
 809
 810    fn workspace_deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 811        self.hide_hovered_link(cx);
 812    }
 813
 814    fn is_dirty(&self, cx: &App) -> bool {
 815        self.buffer().read(cx).read(cx).is_dirty()
 816    }
 817
 818    fn has_deleted_file(&self, cx: &App) -> bool {
 819        self.buffer().read(cx).read(cx).has_deleted_file()
 820    }
 821
 822    fn has_conflict(&self, cx: &App) -> bool {
 823        self.buffer().read(cx).read(cx).has_conflict()
 824    }
 825
 826    fn can_save(&self, cx: &App) -> bool {
 827        let buffer = &self.buffer().read(cx);
 828        if let Some(buffer) = buffer.as_singleton() {
 829            buffer.read(cx).project_path(cx).is_some()
 830        } else {
 831            true
 832        }
 833    }
 834
 835    fn save(
 836        &mut self,
 837        options: SaveOptions,
 838        project: Entity<Project>,
 839        window: &mut Window,
 840        cx: &mut Context<Self>,
 841    ) -> Task<Result<()>> {
 842        // Add meta data tracking # of auto saves
 843        if options.autosave {
 844            self.report_editor_event(ReportEditorEvent::Saved { auto_saved: true }, None, cx);
 845        } else {
 846            self.report_editor_event(ReportEditorEvent::Saved { auto_saved: false }, None, cx);
 847        }
 848
 849        let buffers = self.buffer().clone().read(cx).all_buffers();
 850        let buffers = buffers
 851            .into_iter()
 852            .map(|handle| handle.read(cx).base_buffer().unwrap_or(handle.clone()))
 853            .collect::<HashSet<_>>();
 854
 855        // let mut buffers_to_save =
 856        let buffers_to_save = if self.buffer.read(cx).is_singleton() && !options.autosave {
 857            buffers
 858        } else {
 859            buffers
 860                .into_iter()
 861                .filter(|buffer| buffer.read(cx).is_dirty())
 862                .collect()
 863        };
 864
 865        cx.spawn_in(window, async move |this, cx| {
 866            if options.format {
 867                this.update_in(cx, |editor, window, cx| {
 868                    editor.perform_format(
 869                        project.clone(),
 870                        FormatTrigger::Save,
 871                        FormatTarget::Buffers(buffers_to_save.clone()),
 872                        window,
 873                        cx,
 874                    )
 875                })?
 876                .await?;
 877            }
 878
 879            if !buffers_to_save.is_empty() {
 880                project
 881                    .update(cx, |project, cx| {
 882                        project.save_buffers(buffers_to_save.clone(), cx)
 883                    })?
 884                    .await?;
 885            }
 886
 887            Ok(())
 888        })
 889    }
 890
 891    fn save_as(
 892        &mut self,
 893        project: Entity<Project>,
 894        path: ProjectPath,
 895        _: &mut Window,
 896        cx: &mut Context<Self>,
 897    ) -> Task<Result<()>> {
 898        let buffer = self
 899            .buffer()
 900            .read(cx)
 901            .as_singleton()
 902            .expect("cannot call save_as on an excerpt list");
 903
 904        let file_extension = path.path.extension().map(|a| a.to_string());
 905        self.report_editor_event(
 906            ReportEditorEvent::Saved { auto_saved: false },
 907            file_extension,
 908            cx,
 909        );
 910
 911        project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
 912    }
 913
 914    fn reload(
 915        &mut self,
 916        project: Entity<Project>,
 917        window: &mut Window,
 918        cx: &mut Context<Self>,
 919    ) -> Task<Result<()>> {
 920        let buffer = self.buffer().clone();
 921        let buffers = self.buffer.read(cx).all_buffers();
 922        let reload_buffers =
 923            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
 924        cx.spawn_in(window, async move |this, cx| {
 925            let transaction = reload_buffers.log_err().await;
 926            this.update(cx, |editor, cx| {
 927                editor.request_autoscroll(Autoscroll::fit(), cx)
 928            })?;
 929            buffer
 930                .update(cx, |buffer, cx| {
 931                    if let Some(transaction) = transaction
 932                        && !buffer.is_singleton()
 933                    {
 934                        buffer.push_transaction(&transaction.0, cx);
 935                    }
 936                })
 937                .ok();
 938            Ok(())
 939        })
 940    }
 941
 942    fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 943        Some(Box::new(handle.clone()))
 944    }
 945
 946    fn pixel_position_of_cursor(&self, _: &App) -> Option<gpui::Point<Pixels>> {
 947        self.pixel_position_of_newest_cursor
 948    }
 949
 950    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 951        if self.show_breadcrumbs {
 952            ToolbarItemLocation::PrimaryLeft
 953        } else {
 954            ToolbarItemLocation::Hidden
 955        }
 956    }
 957
 958    fn breadcrumbs(&self, variant: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 959        let cursor = self.selections.newest_anchor().head();
 960        let multibuffer = self.buffer().read(cx);
 961        let (buffer_id, symbols) = multibuffer
 962            .read(cx)
 963            .symbols_containing(cursor, Some(variant.syntax()))?;
 964        let buffer = multibuffer.buffer(buffer_id)?;
 965
 966        let buffer = buffer.read(cx);
 967        let text = self.breadcrumb_header.clone().unwrap_or_else(|| {
 968            buffer
 969                .snapshot()
 970                .resolve_file_path(
 971                    self.project
 972                        .as_ref()
 973                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 974                        .unwrap_or_default(),
 975                    cx,
 976                )
 977                .unwrap_or_else(|| {
 978                    if multibuffer.is_singleton() {
 979                        multibuffer.title(cx).to_string()
 980                    } else {
 981                        "untitled".to_string()
 982                    }
 983                })
 984        });
 985
 986        let settings = ThemeSettings::get_global(cx);
 987
 988        let mut breadcrumbs = vec![BreadcrumbText {
 989            text,
 990            highlights: None,
 991            font: Some(settings.buffer_font.clone()),
 992        }];
 993
 994        breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
 995            text: symbol.text,
 996            highlights: Some(symbol.highlight_ranges),
 997            font: Some(settings.buffer_font.clone()),
 998        }));
 999        Some(breadcrumbs)
1000    }
1001
1002    fn added_to_workspace(
1003        &mut self,
1004        workspace: &mut Workspace,
1005        _window: &mut Window,
1006        cx: &mut Context<Self>,
1007    ) {
1008        self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
1009        if let Some(workspace) = &workspace.weak_handle().upgrade() {
1010            cx.subscribe(workspace, |editor, _, event: &workspace::Event, _cx| {
1011                if let workspace::Event::ModalOpened = event {
1012                    editor.mouse_context_menu.take();
1013                    editor.inline_blame_popover.take();
1014                }
1015            })
1016            .detach();
1017        }
1018    }
1019
1020    fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
1021        match event {
1022            EditorEvent::Saved | EditorEvent::TitleChanged => {
1023                f(ItemEvent::UpdateTab);
1024                f(ItemEvent::UpdateBreadcrumbs);
1025            }
1026
1027            EditorEvent::Reparsed(_) => {
1028                f(ItemEvent::UpdateBreadcrumbs);
1029            }
1030
1031            EditorEvent::SelectionsChanged { local } if *local => {
1032                f(ItemEvent::UpdateBreadcrumbs);
1033            }
1034
1035            EditorEvent::BreadcrumbsChanged => {
1036                f(ItemEvent::UpdateBreadcrumbs);
1037            }
1038
1039            EditorEvent::DirtyChanged => {
1040                f(ItemEvent::UpdateTab);
1041            }
1042
1043            EditorEvent::BufferEdited => {
1044                f(ItemEvent::Edit);
1045                f(ItemEvent::UpdateBreadcrumbs);
1046            }
1047
1048            EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
1049                f(ItemEvent::Edit);
1050            }
1051
1052            _ => {}
1053        }
1054    }
1055
1056    fn preserve_preview(&self, cx: &App) -> bool {
1057        self.buffer.read(cx).preserve_preview(cx)
1058    }
1059}
1060
1061impl SerializableItem for Editor {
1062    fn serialized_item_kind() -> &'static str {
1063        "Editor"
1064    }
1065
1066    fn cleanup(
1067        workspace_id: WorkspaceId,
1068        alive_items: Vec<ItemId>,
1069        _window: &mut Window,
1070        cx: &mut App,
1071    ) -> Task<Result<()>> {
1072        workspace::delete_unloaded_items(alive_items, workspace_id, "editors", &DB, cx)
1073    }
1074
1075    fn deserialize(
1076        project: Entity<Project>,
1077        workspace: WeakEntity<Workspace>,
1078        workspace_id: workspace::WorkspaceId,
1079        item_id: ItemId,
1080        window: &mut Window,
1081        cx: &mut App,
1082    ) -> Task<Result<Entity<Self>>> {
1083        let serialized_editor = match DB
1084            .get_serialized_editor(item_id, workspace_id)
1085            .context("Failed to query editor state")
1086        {
1087            Ok(Some(serialized_editor)) => {
1088                if ProjectSettings::get_global(cx)
1089                    .session
1090                    .restore_unsaved_buffers
1091                {
1092                    serialized_editor
1093                } else {
1094                    SerializedEditor {
1095                        abs_path: serialized_editor.abs_path,
1096                        contents: None,
1097                        language: None,
1098                        mtime: None,
1099                    }
1100                }
1101            }
1102            Ok(None) => {
1103                return Task::ready(Err(anyhow!(
1104                    "Unable to deserialize editor: No entry in database for item_id: {item_id} and workspace_id {workspace_id:?}"
1105                )));
1106            }
1107            Err(error) => {
1108                return Task::ready(Err(error));
1109            }
1110        };
1111        log::debug!(
1112            "Deserialized editor {item_id:?} in workspace {workspace_id:?}, {serialized_editor:?}"
1113        );
1114
1115        match serialized_editor {
1116            SerializedEditor {
1117                abs_path: None,
1118                contents: Some(contents),
1119                language,
1120                ..
1121            } => window.spawn(cx, {
1122                let project = project.clone();
1123                async move |cx| {
1124                    let language_registry =
1125                        project.read_with(cx, |project, _| project.languages().clone())?;
1126
1127                    let language = if let Some(language_name) = language {
1128                        // We don't fail here, because we'd rather not set the language if the name changed
1129                        // than fail to restore the buffer.
1130                        language_registry
1131                            .language_for_name(&language_name)
1132                            .await
1133                            .ok()
1134                    } else {
1135                        None
1136                    };
1137
1138                    // First create the empty buffer
1139                    let buffer = project
1140                        .update(cx, |project, cx| project.create_buffer(true, cx))?
1141                        .await
1142                        .context("Failed to create buffer while deserializing editor")?;
1143
1144                    // Then set the text so that the dirty bit is set correctly
1145                    buffer.update(cx, |buffer, cx| {
1146                        buffer.set_language_registry(language_registry);
1147                        if let Some(language) = language {
1148                            buffer.set_language(Some(language), cx);
1149                        }
1150                        buffer.set_text(contents, cx);
1151                        if let Some(entry) = buffer.peek_undo_stack() {
1152                            buffer.forget_transaction(entry.transaction_id());
1153                        }
1154                    })?;
1155
1156                    cx.update(|window, cx| {
1157                        cx.new(|cx| {
1158                            let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1159
1160                            editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1161                            editor
1162                        })
1163                    })
1164                }
1165            }),
1166            SerializedEditor {
1167                abs_path: Some(abs_path),
1168                contents,
1169                mtime,
1170                ..
1171            } => {
1172                let opened_buffer = project.update(cx, |project, cx| {
1173                    let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1174                    let project_path = ProjectPath {
1175                        worktree_id: worktree.read(cx).id(),
1176                        path: path,
1177                    };
1178                    Some(project.open_path(project_path, cx))
1179                });
1180
1181                match opened_buffer {
1182                    Some(opened_buffer) => {
1183                        window.spawn(cx, async move |cx| {
1184                            let (_, buffer) = opened_buffer
1185                                .await
1186                                .context("Failed to open path in project")?;
1187
1188                            // This is a bit wasteful: we're loading the whole buffer from
1189                            // disk and then overwrite the content.
1190                            // But for now, it keeps the implementation of the content serialization
1191                            // simple, because we don't have to persist all of the metadata that we get
1192                            // by loading the file (git diff base, ...).
1193                            if let Some(buffer_text) = contents {
1194                                buffer.update(cx, |buffer, cx| {
1195                                    // If we did restore an mtime, we want to store it on the buffer
1196                                    // so that the next edit will mark the buffer as dirty/conflicted.
1197                                    if mtime.is_some() {
1198                                        buffer.did_reload(
1199                                            buffer.version(),
1200                                            buffer.line_ending(),
1201                                            mtime,
1202                                            cx,
1203                                        );
1204                                    }
1205                                    buffer.set_text(buffer_text, cx);
1206                                    if let Some(entry) = buffer.peek_undo_stack() {
1207                                        buffer.forget_transaction(entry.transaction_id());
1208                                    }
1209                                })?;
1210                            }
1211
1212                            cx.update(|window, cx| {
1213                                cx.new(|cx| {
1214                                    let mut editor =
1215                                        Editor::for_buffer(buffer, Some(project), window, cx);
1216
1217                                    editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1218                                    editor
1219                                })
1220                            })
1221                        })
1222                    }
1223                    None => {
1224                        let open_by_abs_path = workspace.update(cx, |workspace, cx| {
1225                            workspace.open_abs_path(
1226                                abs_path.clone(),
1227                                OpenOptions {
1228                                    visible: Some(OpenVisible::None),
1229                                    ..Default::default()
1230                                },
1231                                window,
1232                                cx,
1233                            )
1234                        });
1235                        window.spawn(cx, async move |cx| {
1236                            let editor = open_by_abs_path?.await?.downcast::<Editor>().with_context(|| format!("Failed to downcast to Editor after opening abs path {abs_path:?}"))?;
1237                            editor.update_in(cx, |editor, window, cx| {
1238                                editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1239                            })?;
1240                            Ok(editor)
1241                        })
1242                    }
1243                }
1244            }
1245            SerializedEditor {
1246                abs_path: None,
1247                contents: None,
1248                ..
1249            } => window.spawn(cx, async move |cx| {
1250                let buffer = project
1251                    .update(cx, |project, cx| project.create_buffer(true, cx))?
1252                    .await
1253                    .context("Failed to create buffer")?;
1254
1255                cx.update(|window, cx| {
1256                    cx.new(|cx| {
1257                        let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1258
1259                        editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1260                        editor
1261                    })
1262                })
1263            }),
1264        }
1265    }
1266
1267    fn serialize(
1268        &mut self,
1269        workspace: &mut Workspace,
1270        item_id: ItemId,
1271        closing: bool,
1272        window: &mut Window,
1273        cx: &mut Context<Self>,
1274    ) -> Option<Task<Result<()>>> {
1275        let buffer_serialization = self.buffer_serialization?;
1276        let project = self.project.clone()?;
1277
1278        let serialize_dirty_buffers = match buffer_serialization {
1279            // If we don't have a worktree, we don't serialize, because
1280            // projects without worktrees aren't deserialized.
1281            BufferSerialization::All => project.read(cx).visible_worktrees(cx).next().is_some(),
1282            BufferSerialization::NonDirtyBuffers => false,
1283        };
1284
1285        if closing && !serialize_dirty_buffers {
1286            return None;
1287        }
1288
1289        let workspace_id = workspace.database_id()?;
1290
1291        let buffer = self.buffer().read(cx).as_singleton()?;
1292
1293        let abs_path = buffer.read(cx).file().and_then(|file| {
1294            let worktree_id = file.worktree_id(cx);
1295            project
1296                .read(cx)
1297                .worktree_for_id(worktree_id, cx)
1298                .map(|worktree| worktree.read(cx).absolutize(file.path()))
1299                .or_else(|| {
1300                    let full_path = file.full_path(cx);
1301                    let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1302                    project.read(cx).absolute_path(&project_path, cx)
1303                })
1304        });
1305
1306        let is_dirty = buffer.read(cx).is_dirty();
1307        let mtime = buffer.read(cx).saved_mtime();
1308
1309        let snapshot = buffer.read(cx).snapshot();
1310
1311        Some(cx.spawn_in(window, async move |_this, cx| {
1312            cx.background_spawn(async move {
1313                let (contents, language) = if serialize_dirty_buffers && is_dirty {
1314                    let contents = snapshot.text();
1315                    let language = snapshot.language().map(|lang| lang.name().to_string());
1316                    (Some(contents), language)
1317                } else {
1318                    (None, None)
1319                };
1320
1321                let editor = SerializedEditor {
1322                    abs_path,
1323                    contents,
1324                    language,
1325                    mtime,
1326                };
1327                log::debug!("Serializing editor {item_id:?} in workspace {workspace_id:?}");
1328                DB.save_serialized_editor(item_id, workspace_id, editor)
1329                    .await
1330                    .context("failed to save serialized editor")
1331            })
1332            .await
1333            .context("failed to save contents of buffer")?;
1334
1335            Ok(())
1336        }))
1337    }
1338
1339    fn should_serialize(&self, event: &Self::Event) -> bool {
1340        self.should_serialize_buffer()
1341            && matches!(
1342                event,
1343                EditorEvent::Saved | EditorEvent::DirtyChanged | EditorEvent::BufferEdited
1344            )
1345    }
1346}
1347
1348#[derive(Debug, Default)]
1349struct EditorRestorationData {
1350    entries: HashMap<PathBuf, RestorationData>,
1351}
1352
1353#[derive(Default, Debug)]
1354pub struct RestorationData {
1355    pub scroll_position: (BufferRow, gpui::Point<ScrollOffset>),
1356    pub folds: Vec<Range<Point>>,
1357    pub selections: Vec<Range<Point>>,
1358}
1359
1360impl ProjectItem for Editor {
1361    type Item = Buffer;
1362
1363    fn project_item_kind() -> Option<ProjectItemKind> {
1364        Some(ProjectItemKind("Editor"))
1365    }
1366
1367    fn for_project_item(
1368        project: Entity<Project>,
1369        pane: Option<&Pane>,
1370        buffer: Entity<Buffer>,
1371        window: &mut Window,
1372        cx: &mut Context<Self>,
1373    ) -> Self {
1374        let mut editor = Self::for_buffer(buffer.clone(), Some(project), window, cx);
1375        if let Some((excerpt_id, buffer_id, snapshot)) =
1376            editor.buffer().read(cx).snapshot(cx).as_singleton()
1377            && WorkspaceSettings::get(None, cx).restore_on_file_reopen
1378            && let Some(restoration_data) = Self::project_item_kind()
1379                .and_then(|kind| pane.as_ref()?.project_item_restoration_data.get(&kind))
1380                .and_then(|data| data.downcast_ref::<EditorRestorationData>())
1381                .and_then(|data| {
1382                    let file = project::File::from_dyn(buffer.read(cx).file())?;
1383                    data.entries.get(&file.abs_path(cx))
1384                })
1385        {
1386            editor.fold_ranges(
1387                clip_ranges(&restoration_data.folds, snapshot),
1388                false,
1389                window,
1390                cx,
1391            );
1392            if !restoration_data.selections.is_empty() {
1393                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1394                    s.select_ranges(clip_ranges(&restoration_data.selections, snapshot));
1395                });
1396            }
1397            let (top_row, offset) = restoration_data.scroll_position;
1398            let anchor = Anchor::in_buffer(
1399                *excerpt_id,
1400                buffer_id,
1401                snapshot.anchor_before(Point::new(top_row, 0)),
1402            );
1403            editor.set_scroll_anchor(ScrollAnchor { anchor, offset }, window, cx);
1404        }
1405
1406        editor
1407    }
1408
1409    fn for_broken_project_item(
1410        abs_path: &Path,
1411        is_local: bool,
1412        e: &anyhow::Error,
1413        window: &mut Window,
1414        cx: &mut App,
1415    ) -> Option<InvalidItemView> {
1416        Some(InvalidItemView::new(abs_path, is_local, e, window, cx))
1417    }
1418}
1419
1420fn clip_ranges<'a>(
1421    original: impl IntoIterator<Item = &'a Range<Point>> + 'a,
1422    snapshot: &'a BufferSnapshot,
1423) -> Vec<Range<Point>> {
1424    original
1425        .into_iter()
1426        .map(|range| {
1427            snapshot.clip_point(range.start, Bias::Left)
1428                ..snapshot.clip_point(range.end, Bias::Right)
1429        })
1430        .collect()
1431}
1432
1433impl EventEmitter<SearchEvent> for Editor {}
1434
1435impl Editor {
1436    pub fn update_restoration_data(
1437        &self,
1438        cx: &mut Context<Self>,
1439        write: impl for<'a> FnOnce(&'a mut RestorationData) + 'static,
1440    ) {
1441        if self.mode.is_minimap() || !WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1442            return;
1443        }
1444
1445        let editor = cx.entity();
1446        cx.defer(move |cx| {
1447            editor.update(cx, |editor, cx| {
1448                let kind = Editor::project_item_kind()?;
1449                let pane = editor.workspace()?.read(cx).pane_for(&cx.entity())?;
1450                let buffer = editor.buffer().read(cx).as_singleton()?;
1451                let file_abs_path = project::File::from_dyn(buffer.read(cx).file())?.abs_path(cx);
1452                pane.update(cx, |pane, _| {
1453                    let data = pane
1454                        .project_item_restoration_data
1455                        .entry(kind)
1456                        .or_insert_with(|| Box::new(EditorRestorationData::default()) as Box<_>);
1457                    let data = match data.downcast_mut::<EditorRestorationData>() {
1458                        Some(data) => data,
1459                        None => {
1460                            *data = Box::new(EditorRestorationData::default());
1461                            data.downcast_mut::<EditorRestorationData>()
1462                                .expect("just written the type downcasted to")
1463                        }
1464                    };
1465
1466                    let data = data.entries.entry(file_abs_path).or_default();
1467                    write(data);
1468                    Some(())
1469                })
1470            });
1471        });
1472    }
1473}
1474
1475pub(crate) enum BufferSearchHighlights {}
1476impl SearchableItem for Editor {
1477    type Match = Range<Anchor>;
1478
1479    fn get_matches(&self, _window: &mut Window, _: &mut App) -> Vec<Range<Anchor>> {
1480        self.background_highlights
1481            .get(&HighlightKey::Type(TypeId::of::<BufferSearchHighlights>()))
1482            .map_or(Vec::new(), |(_color, ranges)| {
1483                ranges.iter().cloned().collect()
1484            })
1485    }
1486
1487    fn clear_matches(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1488        if self
1489            .clear_background_highlights::<BufferSearchHighlights>(cx)
1490            .is_some()
1491        {
1492            cx.emit(SearchEvent::MatchesInvalidated);
1493        }
1494    }
1495
1496    fn update_matches(
1497        &mut self,
1498        matches: &[Range<Anchor>],
1499        _: &mut Window,
1500        cx: &mut Context<Self>,
1501    ) {
1502        let existing_range = self
1503            .background_highlights
1504            .get(&HighlightKey::Type(TypeId::of::<BufferSearchHighlights>()))
1505            .map(|(_, range)| range.as_ref());
1506        let updated = existing_range != Some(matches);
1507        self.highlight_background::<BufferSearchHighlights>(
1508            matches,
1509            |theme| theme.colors().search_match_background,
1510            cx,
1511        );
1512        if updated {
1513            cx.emit(SearchEvent::MatchesInvalidated);
1514        }
1515    }
1516
1517    fn has_filtered_search_ranges(&mut self) -> bool {
1518        self.has_background_highlights::<SearchWithinRange>()
1519    }
1520
1521    fn toggle_filtered_search_ranges(
1522        &mut self,
1523        enabled: Option<FilteredSearchRange>,
1524        _: &mut Window,
1525        cx: &mut Context<Self>,
1526    ) {
1527        if self.has_filtered_search_ranges() {
1528            self.previous_search_ranges = self
1529                .clear_background_highlights::<SearchWithinRange>(cx)
1530                .map(|(_, ranges)| ranges)
1531        }
1532
1533        if let Some(range) = enabled {
1534            let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1535
1536            if ranges.iter().any(|s| s.start != s.end) {
1537                self.set_search_within_ranges(&ranges, cx);
1538            } else if let Some(previous_search_ranges) = self.previous_search_ranges.take()
1539                && range != FilteredSearchRange::Selection
1540            {
1541                self.set_search_within_ranges(&previous_search_ranges, cx);
1542            }
1543        }
1544    }
1545
1546    fn supported_options(&self) -> SearchOptions {
1547        if self.in_project_search {
1548            SearchOptions {
1549                case: true,
1550                word: true,
1551                regex: true,
1552                replacement: false,
1553                selection: false,
1554                find_in_results: true,
1555            }
1556        } else {
1557            SearchOptions {
1558                case: true,
1559                word: true,
1560                regex: true,
1561                replacement: true,
1562                selection: true,
1563                find_in_results: false,
1564            }
1565        }
1566    }
1567
1568    fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
1569        let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1570        let snapshot = self.snapshot(window, cx);
1571        let selection = self.selections.newest_adjusted(&snapshot.display_snapshot);
1572        let buffer_snapshot = snapshot.buffer_snapshot();
1573
1574        match setting {
1575            SeedQuerySetting::Never => String::new(),
1576            SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1577                let text: String = buffer_snapshot
1578                    .text_for_range(selection.start..selection.end)
1579                    .collect();
1580                if text.contains('\n') {
1581                    String::new()
1582                } else {
1583                    text
1584                }
1585            }
1586            SeedQuerySetting::Selection => String::new(),
1587            SeedQuerySetting::Always => {
1588                let (range, kind) = buffer_snapshot
1589                    .surrounding_word(selection.start, Some(CharScopeContext::Completion));
1590                if kind == Some(CharKind::Word) {
1591                    let text: String = buffer_snapshot.text_for_range(range).collect();
1592                    if !text.trim().is_empty() {
1593                        return text;
1594                    }
1595                }
1596                String::new()
1597            }
1598        }
1599    }
1600
1601    fn activate_match(
1602        &mut self,
1603        index: usize,
1604        matches: &[Range<Anchor>],
1605        window: &mut Window,
1606        cx: &mut Context<Self>,
1607    ) {
1608        self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1609        let range = self.range_for_match(&matches[index]);
1610        let autoscroll = if EditorSettings::get_global(cx).search.center_on_match {
1611            Autoscroll::center()
1612        } else {
1613            Autoscroll::fit()
1614        };
1615        self.change_selections(SelectionEffects::scroll(autoscroll), window, cx, |s| {
1616            s.select_ranges([range]);
1617        })
1618    }
1619
1620    fn select_matches(
1621        &mut self,
1622        matches: &[Self::Match],
1623        window: &mut Window,
1624        cx: &mut Context<Self>,
1625    ) {
1626        self.unfold_ranges(matches, false, false, cx);
1627        self.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1628            s.select_ranges(matches.iter().cloned())
1629        });
1630    }
1631    fn replace(
1632        &mut self,
1633        identifier: &Self::Match,
1634        query: &SearchQuery,
1635        window: &mut Window,
1636        cx: &mut Context<Self>,
1637    ) {
1638        let text = self.buffer.read(cx);
1639        let text = text.snapshot(cx);
1640        let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1641        let text: Cow<_> = if text.len() == 1 {
1642            text.first().cloned().unwrap().into()
1643        } else {
1644            let joined_chunks = text.join("");
1645            joined_chunks.into()
1646        };
1647
1648        if let Some(replacement) = query.replacement_for(&text) {
1649            self.transact(window, cx, |this, _, cx| {
1650                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1651            });
1652        }
1653    }
1654    fn replace_all(
1655        &mut self,
1656        matches: &mut dyn Iterator<Item = &Self::Match>,
1657        query: &SearchQuery,
1658        window: &mut Window,
1659        cx: &mut Context<Self>,
1660    ) {
1661        let text = self.buffer.read(cx);
1662        let text = text.snapshot(cx);
1663        let mut edits = vec![];
1664
1665        for m in matches {
1666            let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1667
1668            let text: Cow<_> = if text.len() == 1 {
1669                text.first().cloned().unwrap().into()
1670            } else {
1671                let joined_chunks = text.join("");
1672                joined_chunks.into()
1673            };
1674
1675            if let Some(replacement) = query.replacement_for(&text) {
1676                edits.push((m.clone(), Arc::from(&*replacement)));
1677            }
1678        }
1679
1680        if !edits.is_empty() {
1681            self.transact(window, cx, |this, _, cx| {
1682                this.edit(edits, cx);
1683            });
1684        }
1685    }
1686    fn match_index_for_direction(
1687        &mut self,
1688        matches: &[Range<Anchor>],
1689        current_index: usize,
1690        direction: Direction,
1691        count: usize,
1692        _: &mut Window,
1693        cx: &mut Context<Self>,
1694    ) -> usize {
1695        let buffer = self.buffer().read(cx).snapshot(cx);
1696        let current_index_position = if self.selections.disjoint_anchors_arc().len() == 1 {
1697            self.selections.newest_anchor().head()
1698        } else {
1699            matches[current_index].start
1700        };
1701
1702        let mut count = count % matches.len();
1703        if count == 0 {
1704            return current_index;
1705        }
1706        match direction {
1707            Direction::Next => {
1708                if matches[current_index]
1709                    .start
1710                    .cmp(&current_index_position, &buffer)
1711                    .is_gt()
1712                {
1713                    count -= 1
1714                }
1715
1716                (current_index + count) % matches.len()
1717            }
1718            Direction::Prev => {
1719                if matches[current_index]
1720                    .end
1721                    .cmp(&current_index_position, &buffer)
1722                    .is_lt()
1723                {
1724                    count -= 1;
1725                }
1726
1727                if current_index >= count {
1728                    current_index - count
1729                } else {
1730                    matches.len() - (count - current_index)
1731                }
1732            }
1733        }
1734    }
1735
1736    fn find_matches(
1737        &mut self,
1738        query: Arc<project::search::SearchQuery>,
1739        _: &mut Window,
1740        cx: &mut Context<Self>,
1741    ) -> Task<Vec<Range<Anchor>>> {
1742        let buffer = self.buffer().read(cx).snapshot(cx);
1743        let search_within_ranges = self
1744            .background_highlights
1745            .get(&HighlightKey::Type(TypeId::of::<SearchWithinRange>()))
1746            .map_or(vec![], |(_color, ranges)| {
1747                ranges.iter().cloned().collect::<Vec<_>>()
1748            });
1749
1750        cx.background_spawn(async move {
1751            let mut ranges = Vec::new();
1752
1753            let search_within_ranges = if search_within_ranges.is_empty() {
1754                vec![buffer.anchor_before(MultiBufferOffset(0))..buffer.anchor_after(buffer.len())]
1755            } else {
1756                search_within_ranges
1757            };
1758
1759            for range in search_within_ranges {
1760                for (search_buffer, search_range, excerpt_id, deleted_hunk_anchor) in
1761                    buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1762                {
1763                    ranges.extend(
1764                        query
1765                            .search(
1766                                search_buffer,
1767                                Some(search_range.start.0..search_range.end.0),
1768                            )
1769                            .await
1770                            .into_iter()
1771                            .map(|match_range| {
1772                                if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
1773                                    let start = search_buffer
1774                                        .anchor_after(search_range.start + match_range.start);
1775                                    let end = search_buffer
1776                                        .anchor_before(search_range.start + match_range.end);
1777                                    deleted_hunk_anchor.with_diff_base_anchor(start)
1778                                        ..deleted_hunk_anchor.with_diff_base_anchor(end)
1779                                } else {
1780                                    let start = search_buffer
1781                                        .anchor_after(search_range.start + match_range.start);
1782                                    let end = search_buffer
1783                                        .anchor_before(search_range.start + match_range.end);
1784                                    Anchor::range_in_buffer(
1785                                        excerpt_id,
1786                                        search_buffer.remote_id(),
1787                                        start..end,
1788                                    )
1789                                }
1790                            }),
1791                    );
1792                }
1793            }
1794
1795            ranges
1796        })
1797    }
1798
1799    fn active_match_index(
1800        &mut self,
1801        direction: Direction,
1802        matches: &[Range<Anchor>],
1803        _: &mut Window,
1804        cx: &mut Context<Self>,
1805    ) -> Option<usize> {
1806        active_match_index(
1807            direction,
1808            matches,
1809            &self.selections.newest_anchor().head(),
1810            &self.buffer().read(cx).snapshot(cx),
1811        )
1812    }
1813
1814    fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
1815        self.expect_bounds_change = self.last_bounds;
1816    }
1817
1818    fn set_search_is_case_sensitive(
1819        &mut self,
1820        case_sensitive: Option<bool>,
1821        _cx: &mut Context<Self>,
1822    ) {
1823        self.select_next_is_case_sensitive = case_sensitive;
1824    }
1825}
1826
1827pub fn active_match_index(
1828    direction: Direction,
1829    ranges: &[Range<Anchor>],
1830    cursor: &Anchor,
1831    buffer: &MultiBufferSnapshot,
1832) -> Option<usize> {
1833    if ranges.is_empty() {
1834        None
1835    } else {
1836        let r = ranges.binary_search_by(|probe| {
1837            if probe.end.cmp(cursor, buffer).is_lt() {
1838                Ordering::Less
1839            } else if probe.start.cmp(cursor, buffer).is_gt() {
1840                Ordering::Greater
1841            } else {
1842                Ordering::Equal
1843            }
1844        });
1845        match direction {
1846            Direction::Prev => match r {
1847                Ok(i) => Some(i),
1848                Err(i) => Some(i.saturating_sub(1)),
1849            },
1850            Direction::Next => match r {
1851                Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1852            },
1853        }
1854    }
1855}
1856
1857pub fn entry_label_color(selected: bool) -> Color {
1858    if selected {
1859        Color::Default
1860    } else {
1861        Color::Muted
1862    }
1863}
1864
1865pub fn entry_diagnostic_aware_icon_name_and_color(
1866    diagnostic_severity: Option<DiagnosticSeverity>,
1867) -> Option<(IconName, Color)> {
1868    match diagnostic_severity {
1869        Some(DiagnosticSeverity::ERROR) => Some((IconName::Close, Color::Error)),
1870        Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1871        _ => None,
1872    }
1873}
1874
1875pub fn entry_diagnostic_aware_icon_decoration_and_color(
1876    diagnostic_severity: Option<DiagnosticSeverity>,
1877) -> Option<(IconDecorationKind, Color)> {
1878    match diagnostic_severity {
1879        Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1880        Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1881        _ => None,
1882    }
1883}
1884
1885pub fn entry_git_aware_label_color(git_status: GitSummary, ignored: bool, selected: bool) -> Color {
1886    let tracked = git_status.index + git_status.worktree;
1887    if ignored {
1888        Color::Ignored
1889    } else if git_status.conflict > 0 {
1890        Color::Conflict
1891    } else if tracked.modified > 0 {
1892        Color::Modified
1893    } else if tracked.added > 0 || git_status.untracked > 0 {
1894        Color::Created
1895    } else {
1896        entry_label_color(selected)
1897    }
1898}
1899
1900fn path_for_buffer<'a>(
1901    buffer: &Entity<MultiBuffer>,
1902    height: usize,
1903    include_filename: bool,
1904    cx: &'a App,
1905) -> Option<Cow<'a, str>> {
1906    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1907    path_for_file(file.as_ref(), height, include_filename, cx)
1908}
1909
1910fn path_for_file<'a>(
1911    file: &'a dyn language::File,
1912    mut height: usize,
1913    include_filename: bool,
1914    cx: &'a App,
1915) -> Option<Cow<'a, str>> {
1916    // Ensure we always render at least the filename.
1917    height += 1;
1918
1919    let mut prefix = file.path().as_ref();
1920    while height > 0 {
1921        if let Some(parent) = prefix.parent() {
1922            prefix = parent;
1923            height -= 1;
1924        } else {
1925            break;
1926        }
1927    }
1928
1929    // The full_path method allocates, so avoid calling it if height is zero.
1930    if height > 0 {
1931        let mut full_path = file.full_path(cx);
1932        if !include_filename {
1933            if !full_path.pop() {
1934                return None;
1935            }
1936        }
1937        Some(full_path.to_string_lossy().into_owned().into())
1938    } else {
1939        let mut path = file.path().strip_prefix(prefix).ok()?;
1940        if !include_filename {
1941            path = path.parent()?;
1942        }
1943        Some(path.display(file.path_style(cx)))
1944    }
1945}
1946
1947#[cfg(test)]
1948mod tests {
1949    use crate::editor_tests::init_test;
1950    use fs::Fs;
1951
1952    use super::*;
1953    use fs::MTime;
1954    use gpui::{App, VisualTestContext};
1955    use language::{LanguageMatcher, TestFile};
1956    use project::FakeFs;
1957    use std::path::{Path, PathBuf};
1958    use util::{path, rel_path::RelPath};
1959
1960    #[gpui::test]
1961    fn test_path_for_file(cx: &mut App) {
1962        let file = TestFile {
1963            path: RelPath::empty().into(),
1964            root_name: String::new(),
1965            local_root: None,
1966        };
1967        assert_eq!(path_for_file(&file, 0, false, cx), None);
1968    }
1969
1970    async fn deserialize_editor(
1971        item_id: ItemId,
1972        workspace_id: WorkspaceId,
1973        workspace: Entity<Workspace>,
1974        project: Entity<Project>,
1975        cx: &mut VisualTestContext,
1976    ) -> Entity<Editor> {
1977        workspace
1978            .update_in(cx, |workspace, window, cx| {
1979                let pane = workspace.active_pane();
1980                pane.update(cx, |_, cx| {
1981                    Editor::deserialize(
1982                        project.clone(),
1983                        workspace.weak_handle(),
1984                        workspace_id,
1985                        item_id,
1986                        window,
1987                        cx,
1988                    )
1989                })
1990            })
1991            .await
1992            .unwrap()
1993    }
1994
1995    fn rust_language() -> Arc<language::Language> {
1996        Arc::new(language::Language::new(
1997            language::LanguageConfig {
1998                name: "Rust".into(),
1999                matcher: LanguageMatcher {
2000                    path_suffixes: vec!["rs".to_string()],
2001                    ..Default::default()
2002                },
2003                ..Default::default()
2004            },
2005            Some(tree_sitter_rust::LANGUAGE.into()),
2006        ))
2007    }
2008
2009    #[gpui::test]
2010    async fn test_deserialize(cx: &mut gpui::TestAppContext) {
2011        init_test(cx, |_| {});
2012
2013        let fs = FakeFs::new(cx.executor());
2014        fs.insert_file(path!("/file.rs"), Default::default()).await;
2015
2016        // Test case 1: Deserialize with path and contents
2017        {
2018            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2019            let (workspace, cx) =
2020                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2021            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2022            let item_id = 1234 as ItemId;
2023            let mtime = fs
2024                .metadata(Path::new(path!("/file.rs")))
2025                .await
2026                .unwrap()
2027                .unwrap()
2028                .mtime;
2029
2030            let serialized_editor = SerializedEditor {
2031                abs_path: Some(PathBuf::from(path!("/file.rs"))),
2032                contents: Some("fn main() {}".to_string()),
2033                language: Some("Rust".to_string()),
2034                mtime: Some(mtime),
2035            };
2036
2037            DB.save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
2038                .await
2039                .unwrap();
2040
2041            let deserialized =
2042                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2043
2044            deserialized.update(cx, |editor, cx| {
2045                assert_eq!(editor.text(cx), "fn main() {}");
2046                assert!(editor.is_dirty(cx));
2047                assert!(!editor.has_conflict(cx));
2048                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2049                assert!(buffer.file().is_some());
2050            });
2051        }
2052
2053        // Test case 2: Deserialize with only path
2054        {
2055            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2056            let (workspace, cx) =
2057                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2058
2059            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2060
2061            let item_id = 5678 as ItemId;
2062            let serialized_editor = SerializedEditor {
2063                abs_path: Some(PathBuf::from(path!("/file.rs"))),
2064                contents: None,
2065                language: None,
2066                mtime: None,
2067            };
2068
2069            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2070                .await
2071                .unwrap();
2072
2073            let deserialized =
2074                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2075
2076            deserialized.update(cx, |editor, cx| {
2077                assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
2078                assert!(!editor.is_dirty(cx));
2079                assert!(!editor.has_conflict(cx));
2080
2081                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2082                assert!(buffer.file().is_some());
2083            });
2084        }
2085
2086        // Test case 3: Deserialize with no path (untitled buffer, with content and language)
2087        {
2088            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2089            // Add Rust to the language, so that we can restore the language of the buffer
2090            project.read_with(cx, |project, _| project.languages().add(rust_language()));
2091
2092            let (workspace, cx) =
2093                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2094
2095            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2096
2097            let item_id = 9012 as ItemId;
2098            let serialized_editor = SerializedEditor {
2099                abs_path: None,
2100                contents: Some("hello".to_string()),
2101                language: Some("Rust".to_string()),
2102                mtime: None,
2103            };
2104
2105            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2106                .await
2107                .unwrap();
2108
2109            let deserialized =
2110                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2111
2112            deserialized.update(cx, |editor, cx| {
2113                assert_eq!(editor.text(cx), "hello");
2114                assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
2115
2116                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2117                assert_eq!(
2118                    buffer.language().map(|lang| lang.name()),
2119                    Some("Rust".into())
2120                ); // Language should be set to Rust
2121                assert!(buffer.file().is_none()); // The buffer should not have an associated file
2122            });
2123        }
2124
2125        // Test case 4: Deserialize with path, content, and old mtime
2126        {
2127            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2128            let (workspace, cx) =
2129                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2130
2131            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2132
2133            let item_id = 9345 as ItemId;
2134            let old_mtime = MTime::from_seconds_and_nanos(0, 50);
2135            let serialized_editor = SerializedEditor {
2136                abs_path: Some(PathBuf::from(path!("/file.rs"))),
2137                contents: Some("fn main() {}".to_string()),
2138                language: Some("Rust".to_string()),
2139                mtime: Some(old_mtime),
2140            };
2141
2142            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2143                .await
2144                .unwrap();
2145
2146            let deserialized =
2147                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2148
2149            deserialized.update(cx, |editor, cx| {
2150                assert_eq!(editor.text(cx), "fn main() {}");
2151                assert!(editor.has_conflict(cx)); // The editor should have a conflict
2152            });
2153        }
2154
2155        // Test case 5: Deserialize with no path, no content, no language, and no old mtime (new, empty, unsaved buffer)
2156        {
2157            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2158            let (workspace, cx) =
2159                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2160
2161            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2162
2163            let item_id = 10000 as ItemId;
2164            let serialized_editor = SerializedEditor {
2165                abs_path: None,
2166                contents: None,
2167                language: None,
2168                mtime: None,
2169            };
2170
2171            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2172                .await
2173                .unwrap();
2174
2175            let deserialized =
2176                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2177
2178            deserialized.update(cx, |editor, cx| {
2179                assert_eq!(editor.text(cx), "");
2180                assert!(!editor.is_dirty(cx));
2181                assert!(!editor.has_conflict(cx));
2182
2183                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2184                assert!(buffer.file().is_none());
2185            });
2186        }
2187    }
2188}