items.rs

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