items.rs

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