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