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