items.rs

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