items.rs

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