items.rs

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