items.rs

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