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