items.rs

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