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