items.rs

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