items.rs

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