items.rs

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