items.rs

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