items.rs

   1use crate::{
   2    ActiveDebugLine, Anchor, Autoscroll, BufferSerialization, Capability, Editor, EditorEvent,
   3    EditorSettings, ExcerptRange, FormatTarget, MultiBuffer, MultiBufferSnapshot, NavigationData,
   4    ReportEditorEvent, SelectionEffects, ToPoint as _,
   5    display_map::HighlightKey,
   6    editor_settings::SeedQuerySetting,
   7    persistence::{EditorDb, SerializedEditor},
   8    scroll::{ScrollAnchor, ScrollOffset},
   9};
  10use anyhow::{Context as _, Result, anyhow};
  11use collections::{HashMap, HashSet};
  12use file_icons::FileIcons;
  13use fs::MTime;
  14use futures::future::try_join_all;
  15use git::status::GitSummary;
  16use gpui::{
  17    AnyElement, App, AsyncWindowContext, Context, Entity, EntityId, EventEmitter, Font,
  18    IntoElement, ParentElement, Pixels, SharedString, Styled, Task, WeakEntity, Window, point,
  19};
  20use language::{
  21    Bias, Buffer, BufferRow, CharKind, CharScopeContext, HighlightedText, LocalFile, Point,
  22    SelectionGoal, proto::serialize_anchor as serialize_text_anchor,
  23};
  24use lsp::DiagnosticSeverity;
  25use multi_buffer::{MultiBufferOffset, PathKey};
  26use project::{
  27    File, Project, ProjectItem as _, ProjectPath, lsp_store::FormatTrigger,
  28    project_settings::ProjectSettings, search::SearchQuery,
  29};
  30use rpc::proto::{self, update_view};
  31use settings::Settings;
  32use std::{
  33    any::{Any, TypeId},
  34    borrow::Cow,
  35    cmp::{self, Ordering},
  36    ops::Range,
  37    path::{Path, PathBuf},
  38    sync::Arc,
  39};
  40use text::{BufferId, BufferSnapshot, Selection};
  41use ui::{IconDecorationKind, prelude::*};
  42use util::{ResultExt, TryFutureExt, paths::PathExt, rel_path::RelPath};
  43use workspace::item::{Dedup, ItemSettings, SerializableItem, TabContentParams};
  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, SearchToken, SearchableItem,
  50        SearchableItemHandle,
  51    },
  52};
  53use workspace::{
  54    Pane, WorkspaceSettings,
  55    item::{FollowEvent, ProjectItemKind},
  56    searchable::SearchOptions,
  57};
  58use zed_actions::preview::{
  59    markdown::OpenPreview as OpenMarkdownPreview, svg::OpenPreview as OpenSvgPreview,
  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            .path_excerpts
  86            .iter()
  87            .map(|excerpt| excerpt.buffer_id)
  88            .collect::<HashSet<_>>();
  89
  90        let buffers = project.update(cx, |project, cx| {
  91            buffer_ids
  92                .iter()
  93                .map(|id| BufferId::new(*id).map(|id| project.open_buffer_by_id(id, cx)))
  94                .collect::<Result<Vec<_>>>()
  95        });
  96
  97        Some(window.spawn(cx, async move |cx| {
  98            let mut buffers = futures::future::try_join_all(buffers?)
  99                .await
 100                .debug_assert_ok("leaders don't share views for unshared buffers")?;
 101
 102            let editor = cx.update(|window, cx| {
 103                let multibuffer = cx.new(|cx| {
 104                    let mut multibuffer;
 105                    if state.singleton && buffers.len() == 1 {
 106                        multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
 107                    } else {
 108                        multibuffer = MultiBuffer::new(project.read(cx).capability());
 109                        for path_with_ranges in state.path_excerpts {
 110                            let Some(path_key) =
 111                                path_with_ranges.path_key.and_then(deserialize_path_key)
 112                            else {
 113                                continue;
 114                            };
 115                            let Some(buffer_id) = BufferId::new(path_with_ranges.buffer_id).ok()
 116                            else {
 117                                continue;
 118                            };
 119                            let Some(buffer) =
 120                                buffers.iter().find(|b| b.read(cx).remote_id() == buffer_id)
 121                            else {
 122                                continue;
 123                            };
 124                            let buffer_snapshot = buffer.read(cx).snapshot();
 125                            let ranges = path_with_ranges
 126                                .ranges
 127                                .into_iter()
 128                                .filter_map(deserialize_excerpt_range)
 129                                .collect::<Vec<_>>();
 130                            multibuffer.update_path_excerpts(
 131                                path_key,
 132                                buffer.clone(),
 133                                &buffer_snapshot,
 134                                &ranges,
 135                                cx,
 136                            );
 137                        }
 138                    };
 139
 140                    if let Some(title) = &state.title {
 141                        multibuffer = multibuffer.with_title(title.clone())
 142                    }
 143
 144                    multibuffer
 145                });
 146
 147                cx.new(|cx| {
 148                    let mut editor =
 149                        Editor::for_multibuffer(multibuffer, Some(project.clone()), window, cx);
 150                    editor.remote_id = Some(remote_id);
 151                    editor
 152                })
 153            })?;
 154
 155            editor.update(cx, |editor, cx| editor.text(cx));
 156            update_editor_from_message(
 157                editor.downgrade(),
 158                project,
 159                proto::update_view::Editor {
 160                    selections: state.selections,
 161                    pending_selection: state.pending_selection,
 162                    scroll_top_anchor: state.scroll_top_anchor,
 163                    scroll_x: state.scroll_x,
 164                    scroll_y: state.scroll_y,
 165                    ..Default::default()
 166                },
 167                cx,
 168            )
 169            .await?;
 170
 171            Ok(editor)
 172        }))
 173    }
 174
 175    fn set_leader_id(
 176        &mut self,
 177        leader_id: Option<CollaboratorId>,
 178        window: &mut Window,
 179        cx: &mut Context<Self>,
 180    ) {
 181        self.leader_id = leader_id;
 182        if self.leader_id.is_some() {
 183            self.buffer.update(cx, |buffer, cx| {
 184                buffer.remove_active_selections(cx);
 185            });
 186        } else if self.focus_handle.is_focused(window) {
 187            self.buffer.update(cx, |buffer, cx| {
 188                buffer.set_active_selections(
 189                    &self.selections.disjoint_anchors_arc(),
 190                    self.selections.line_mode(),
 191                    self.cursor_shape,
 192                    cx,
 193                );
 194            });
 195        }
 196        cx.notify();
 197    }
 198
 199    fn to_state_proto(&self, _: &mut Window, cx: &mut App) -> Option<proto::view::Variant> {
 200        let is_private = self
 201            .buffer
 202            .read(cx)
 203            .as_singleton()
 204            .and_then(|buffer| buffer.read(cx).file())
 205            .is_some_and(|file| file.is_private());
 206        if is_private {
 207            return None;
 208        }
 209
 210        let display_snapshot = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 211        let scroll_anchor = self.scroll_manager.native_anchor(&display_snapshot, cx);
 212        let buffer = self.buffer.read(cx);
 213        let snapshot = buffer.snapshot(cx);
 214        let mut path_excerpts: Vec<proto::PathExcerpts> = Vec::new();
 215        for excerpt in snapshot.excerpts() {
 216            if let Some(prev_entry) = path_excerpts.last_mut()
 217                && prev_entry.buffer_id == excerpt.context.start.buffer_id.to_proto()
 218            {
 219                prev_entry.ranges.push(serialize_excerpt_range(excerpt));
 220            } else if let Some(path_key) = snapshot.path_for_buffer(excerpt.context.start.buffer_id)
 221            {
 222                path_excerpts.push(proto::PathExcerpts {
 223                    path_key: Some(serialize_path_key(path_key)),
 224                    buffer_id: excerpt.context.start.buffer_id.to_proto(),
 225                    ranges: vec![serialize_excerpt_range(excerpt)],
 226                });
 227            }
 228        }
 229
 230        Some(proto::view::Variant::Editor(proto::view::Editor {
 231            singleton: buffer.is_singleton(),
 232            title: buffer.explicit_title().map(ToOwned::to_owned),
 233            excerpts: Vec::new(),
 234            scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
 235            scroll_x: scroll_anchor.offset.x,
 236            scroll_y: scroll_anchor.offset.y,
 237            selections: self
 238                .selections
 239                .disjoint_anchors_arc()
 240                .iter()
 241                .map(serialize_selection)
 242                .collect(),
 243            pending_selection: self
 244                .selections
 245                .pending_anchor()
 246                .as_ref()
 247                .copied()
 248                .map(serialize_selection),
 249            path_excerpts,
 250        }))
 251    }
 252
 253    fn to_follow_event(event: &EditorEvent) -> Option<workspace::item::FollowEvent> {
 254        match event {
 255            EditorEvent::Edited { .. } => Some(FollowEvent::Unfollow),
 256            EditorEvent::SelectionsChanged { local }
 257            | EditorEvent::ScrollPositionChanged { local, .. } => {
 258                if *local {
 259                    Some(FollowEvent::Unfollow)
 260                } else {
 261                    None
 262                }
 263            }
 264            _ => None,
 265        }
 266    }
 267
 268    fn add_event_to_update_proto(
 269        &self,
 270        event: &EditorEvent,
 271        update: &mut Option<proto::update_view::Variant>,
 272        _: &mut Window,
 273        cx: &mut App,
 274    ) -> bool {
 275        let update =
 276            update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
 277
 278        match update {
 279            proto::update_view::Variant::Editor(update) => match event {
 280                EditorEvent::BufferRangesUpdated {
 281                    buffer,
 282                    path_key,
 283                    ranges,
 284                } => {
 285                    let buffer_id = buffer.read(cx).remote_id().to_proto();
 286                    let path_key = serialize_path_key(path_key);
 287                    let ranges = ranges
 288                        .iter()
 289                        .cloned()
 290                        .map(serialize_excerpt_range)
 291                        .collect::<Vec<_>>();
 292                    update.updated_paths.push(proto::PathExcerpts {
 293                        path_key: Some(path_key),
 294                        buffer_id,
 295                        ranges,
 296                    });
 297                    true
 298                }
 299                EditorEvent::BuffersRemoved { removed_buffer_ids } => {
 300                    update
 301                        .deleted_buffers
 302                        .extend(removed_buffer_ids.iter().copied().map(BufferId::to_proto));
 303                    true
 304                }
 305                EditorEvent::ScrollPositionChanged { autoscroll, .. } if !autoscroll => {
 306                    let display_snapshot = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 307                    let scroll_anchor = self.scroll_manager.native_anchor(&display_snapshot, cx);
 308                    update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
 309                    update.scroll_x = scroll_anchor.offset.x;
 310                    update.scroll_y = scroll_anchor.offset.y;
 311                    true
 312                }
 313                EditorEvent::SelectionsChanged { .. } => {
 314                    update.selections = self
 315                        .selections
 316                        .disjoint_anchors_arc()
 317                        .iter()
 318                        .map(serialize_selection)
 319                        .collect();
 320                    update.pending_selection = self
 321                        .selections
 322                        .pending_anchor()
 323                        .as_ref()
 324                        .copied()
 325                        .map(serialize_selection);
 326                    true
 327                }
 328                _ => false,
 329            },
 330        }
 331    }
 332
 333    fn apply_update_proto(
 334        &mut self,
 335        project: &Entity<Project>,
 336        message: update_view::Variant,
 337        window: &mut Window,
 338        cx: &mut Context<Self>,
 339    ) -> Task<Result<()>> {
 340        let update_view::Variant::Editor(message) = message;
 341        let project = project.clone();
 342        cx.spawn_in(window, async move |this, cx| {
 343            update_editor_from_message(this, project, message, cx).await
 344        })
 345    }
 346
 347    fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
 348        true
 349    }
 350
 351    fn dedup(&self, existing: &Self, _: &Window, cx: &App) -> Option<Dedup> {
 352        let self_singleton = self.buffer.read(cx).as_singleton()?;
 353        let other_singleton = existing.buffer.read(cx).as_singleton()?;
 354        if self_singleton == other_singleton {
 355            Some(Dedup::KeepExisting)
 356        } else {
 357            None
 358        }
 359    }
 360
 361    fn update_agent_location(
 362        &mut self,
 363        location: language::Anchor,
 364        window: &mut Window,
 365        cx: &mut Context<Self>,
 366    ) {
 367        let buffer = self.buffer.read(cx);
 368        let buffer = buffer.read(cx);
 369        let Some(position) = buffer.anchor_in_excerpt(location) else {
 370            return;
 371        };
 372        let selection = Selection {
 373            id: 0,
 374            reversed: false,
 375            start: position,
 376            end: position,
 377            goal: SelectionGoal::None,
 378        };
 379        drop(buffer);
 380        self.set_selections_from_remote(vec![selection], None, window, cx);
 381        self.request_autoscroll_remotely(Autoscroll::fit(), cx);
 382    }
 383}
 384
 385async fn update_editor_from_message(
 386    this: WeakEntity<Editor>,
 387    project: Entity<Project>,
 388    message: proto::update_view::Editor,
 389    cx: &mut AsyncWindowContext,
 390) -> Result<()> {
 391    // Open all of the buffers of which excerpts were added to the editor.
 392    let inserted_excerpt_buffer_ids = message
 393        .updated_paths
 394        .iter()
 395        .map(|insertion| insertion.buffer_id)
 396        .collect::<HashSet<_>>();
 397    let inserted_excerpt_buffers = project.update(cx, |project, cx| {
 398        inserted_excerpt_buffer_ids
 399            .into_iter()
 400            .map(|id| BufferId::new(id).map(|id| project.open_buffer_by_id(id, cx)))
 401            .collect::<Result<Vec<_>>>()
 402    })?;
 403    let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
 404
 405    // Update the editor's excerpts.
 406    let buffer_snapshot = this.update(cx, |editor, cx| {
 407        editor.buffer.update(cx, |multibuffer, cx| {
 408            for path_with_excerpts in message.updated_paths {
 409                let Some(path_key) = path_with_excerpts.path_key.and_then(deserialize_path_key)
 410                else {
 411                    continue;
 412                };
 413                let ranges = path_with_excerpts
 414                    .ranges
 415                    .into_iter()
 416                    .filter_map(deserialize_excerpt_range)
 417                    .collect::<Vec<_>>();
 418                let Some(buffer) = BufferId::new(path_with_excerpts.buffer_id)
 419                    .ok()
 420                    .and_then(|buffer_id| project.read(cx).buffer_for_id(buffer_id, cx))
 421                else {
 422                    continue;
 423                };
 424
 425                let buffer_snapshot = buffer.read(cx).snapshot();
 426                multibuffer.update_path_excerpts(path_key, buffer, &buffer_snapshot, &ranges, cx);
 427            }
 428
 429            for buffer_id in message
 430                .deleted_buffers
 431                .into_iter()
 432                .filter_map(|buffer_id| BufferId::new(buffer_id).ok())
 433            {
 434                multibuffer.remove_excerpts_for_buffer(buffer_id, cx);
 435            }
 436
 437            multibuffer.snapshot(cx)
 438        })
 439    })?;
 440
 441    // Deserialize the editor state.
 442    let selections = message
 443        .selections
 444        .into_iter()
 445        .filter_map(|selection| deserialize_selection(selection, &buffer_snapshot))
 446        .collect::<Vec<_>>();
 447    let pending_selection = message
 448        .pending_selection
 449        .and_then(|selection| deserialize_selection(selection, &buffer_snapshot));
 450    let scroll_top_anchor = message
 451        .scroll_top_anchor
 452        .and_then(|selection| deserialize_anchor(selection, &buffer_snapshot));
 453
 454    // Wait until the buffer has received all of the operations referenced by
 455    // the editor's new state.
 456    this.update(cx, |editor, cx| {
 457        editor.buffer.update(cx, |buffer, cx| {
 458            buffer.wait_for_anchors(
 459                selections
 460                    .iter()
 461                    .chain(pending_selection.as_ref())
 462                    .flat_map(|selection| [selection.start, selection.end])
 463                    .chain(scroll_top_anchor),
 464                cx,
 465            )
 466        })
 467    })?
 468    .await?;
 469
 470    // Update the editor's state.
 471    this.update_in(cx, |editor, window, cx| {
 472        if !selections.is_empty() || pending_selection.is_some() {
 473            editor.set_selections_from_remote(selections, pending_selection, window, cx);
 474            editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
 475        } else if let Some(scroll_top_anchor) = scroll_top_anchor {
 476            editor.set_scroll_anchor_remote(
 477                ScrollAnchor {
 478                    anchor: scroll_top_anchor,
 479                    offset: point(message.scroll_x, message.scroll_y),
 480                },
 481                window,
 482                cx,
 483            );
 484        }
 485    })?;
 486    Ok(())
 487}
 488
 489fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
 490    proto::Selection {
 491        id: selection.id as u64,
 492        start: Some(serialize_anchor(&selection.start)),
 493        end: Some(serialize_anchor(&selection.end)),
 494        reversed: selection.reversed,
 495    }
 496}
 497
 498fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
 499    match anchor {
 500        Anchor::Min => proto::EditorAnchor {
 501            excerpt_id: None,
 502            anchor: Some(proto::Anchor {
 503                replica_id: 0,
 504                timestamp: 0,
 505                offset: 0,
 506                bias: proto::Bias::Left as i32,
 507                buffer_id: None,
 508            }),
 509        },
 510        Anchor::Excerpt(_) => proto::EditorAnchor {
 511            excerpt_id: None,
 512            anchor: anchor.raw_text_anchor().map(|a| serialize_text_anchor(&a)),
 513        },
 514        Anchor::Max => proto::EditorAnchor {
 515            excerpt_id: None,
 516            anchor: Some(proto::Anchor {
 517                replica_id: u32::MAX,
 518                timestamp: u32::MAX,
 519                offset: u64::MAX,
 520                bias: proto::Bias::Right as i32,
 521                buffer_id: None,
 522            }),
 523        },
 524    }
 525}
 526
 527fn serialize_excerpt_range(range: ExcerptRange<language::Anchor>) -> proto::ExcerptRange {
 528    let context_start = language::proto::serialize_anchor(&range.context.start);
 529    let context_end = language::proto::serialize_anchor(&range.context.end);
 530    let primary_start = language::proto::serialize_anchor(&range.primary.start);
 531    let primary_end = language::proto::serialize_anchor(&range.primary.end);
 532    proto::ExcerptRange {
 533        context_start: Some(context_start),
 534        context_end: Some(context_end),
 535        primary_start: Some(primary_start),
 536        primary_end: Some(primary_end),
 537    }
 538}
 539
 540fn deserialize_excerpt_range(
 541    excerpt_range: proto::ExcerptRange,
 542) -> Option<ExcerptRange<language::Anchor>> {
 543    let context = {
 544        let start = language::proto::deserialize_anchor(excerpt_range.context_start?)?;
 545        let end = language::proto::deserialize_anchor(excerpt_range.context_end?)?;
 546        start..end
 547    };
 548    let primary = excerpt_range
 549        .primary_start
 550        .zip(excerpt_range.primary_end)
 551        .and_then(|(start, end)| {
 552            let start = language::proto::deserialize_anchor(start)?;
 553            let end = language::proto::deserialize_anchor(end)?;
 554            Some(start..end)
 555        })
 556        .unwrap_or_else(|| context.clone());
 557    Some(ExcerptRange { context, primary })
 558}
 559
 560fn deserialize_selection(
 561    selection: proto::Selection,
 562    buffer: &MultiBufferSnapshot,
 563) -> Option<Selection<Anchor>> {
 564    Some(Selection {
 565        id: selection.id as usize,
 566        start: deserialize_anchor(selection.start?, buffer)?,
 567        end: deserialize_anchor(selection.end?, buffer)?,
 568        reversed: selection.reversed,
 569        goal: SelectionGoal::None,
 570    })
 571}
 572
 573fn deserialize_anchor(anchor: proto::EditorAnchor, buffer: &MultiBufferSnapshot) -> Option<Anchor> {
 574    let anchor = anchor.anchor?;
 575    if let Some(buffer_id) = anchor.buffer_id
 576        && BufferId::new(buffer_id).is_ok()
 577    {
 578        let text_anchor = language::proto::deserialize_anchor(anchor)?;
 579        buffer.anchor_in_buffer(text_anchor)
 580    } else {
 581        match proto::Bias::from_i32(anchor.bias)? {
 582            proto::Bias::Left => Some(Anchor::Min),
 583            proto::Bias::Right => Some(Anchor::Max),
 584        }
 585    }
 586}
 587
 588impl Item for Editor {
 589    type Event = EditorEvent;
 590
 591    fn act_as_type<'a>(
 592        &'a self,
 593        type_id: TypeId,
 594        self_handle: &'a Entity<Self>,
 595        cx: &'a App,
 596    ) -> Option<gpui::AnyEntity> {
 597        if TypeId::of::<Self>() == type_id {
 598            Some(self_handle.clone().into())
 599        } else if TypeId::of::<MultiBuffer>() == type_id {
 600            Some(self_handle.read(cx).buffer.clone().into())
 601        } else {
 602            None
 603        }
 604    }
 605
 606    fn navigate(
 607        &mut self,
 608        data: Arc<dyn Any + Send>,
 609        window: &mut Window,
 610        cx: &mut Context<Self>,
 611    ) -> bool {
 612        if let Some(data) = data.downcast_ref::<NavigationData>() {
 613            let newest_selection = self.selections.newest::<Point>(&self.display_snapshot(cx));
 614            let buffer = self.buffer.read(cx).read(cx);
 615            let offset = if buffer.can_resolve(&data.cursor_anchor) {
 616                data.cursor_anchor.to_point(&buffer)
 617            } else {
 618                buffer.clip_point(data.cursor_position, Bias::Left)
 619            };
 620
 621            let mut scroll_anchor = data.scroll_anchor;
 622            if !buffer.can_resolve(&scroll_anchor.anchor) {
 623                scroll_anchor.anchor = buffer.anchor_before(
 624                    buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
 625                );
 626            }
 627
 628            drop(buffer);
 629
 630            if newest_selection.head() == offset {
 631                false
 632            } else {
 633                self.set_scroll_anchor(scroll_anchor, window, cx);
 634                self.change_selections(
 635                    SelectionEffects::default().nav_history(false),
 636                    window,
 637                    cx,
 638                    |s| s.select_ranges([offset..offset]),
 639                );
 640                true
 641            }
 642        } else {
 643            false
 644        }
 645    }
 646
 647    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
 648        let multi_buffer = self.buffer().read(cx);
 649        if let Some(file) = multi_buffer
 650            .as_singleton()
 651            .and_then(|buffer| buffer.read(cx).file())
 652            .and_then(|file| File::from_dyn(Some(file)))
 653        {
 654            Some(
 655                file.worktree
 656                    .read(cx)
 657                    .absolutize(&file.path)
 658                    .compact()
 659                    .to_string_lossy()
 660                    .into_owned()
 661                    .into(),
 662            )
 663        } else {
 664            let title = multi_buffer.title(cx);
 665            (!title.is_empty()).then(|| title.to_string().into())
 666        }
 667    }
 668
 669    fn telemetry_event_text(&self) -> Option<&'static str> {
 670        None
 671    }
 672
 673    fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
 674        if let Some(path) = path_for_buffer(&self.buffer, detail, true, cx) {
 675            path.to_string().into()
 676        } else {
 677            // Use the same logic as the displayed title for consistency
 678            self.buffer.read(cx).title(cx).to_string().into()
 679        }
 680    }
 681
 682    fn suggested_filename(&self, cx: &App) -> SharedString {
 683        self.buffer.read(cx).title(cx).to_string().into()
 684    }
 685
 686    fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
 687        ItemSettings::get_global(cx)
 688            .file_icons
 689            .then(|| {
 690                path_for_buffer(&self.buffer, 0, true, cx)
 691                    .and_then(|path| FileIcons::get_icon(Path::new(&*path), cx))
 692            })
 693            .flatten()
 694            .map(Icon::from_path)
 695    }
 696
 697    fn tab_content(&self, params: TabContentParams, _: &Window, cx: &App) -> AnyElement {
 698        let label_color = if ItemSettings::get_global(cx).git_status {
 699            self.buffer()
 700                .read(cx)
 701                .as_singleton()
 702                .and_then(|buffer| {
 703                    let buffer = buffer.read(cx);
 704                    let path = buffer.project_path(cx)?;
 705                    let buffer_id = buffer.remote_id();
 706                    let project = self.project()?.read(cx);
 707                    let entry = project.entry_for_path(&path, cx)?;
 708                    let (repo, repo_path) = project
 709                        .git_store()
 710                        .read(cx)
 711                        .repository_and_path_for_buffer_id(buffer_id, cx)?;
 712                    let status = repo.read(cx).status_for_path(&repo_path)?.status;
 713
 714                    Some(entry_git_aware_label_color(
 715                        status.summary(),
 716                        entry.is_ignored,
 717                        params.selected,
 718                    ))
 719                })
 720                .unwrap_or_else(|| entry_label_color(params.selected))
 721        } else {
 722            entry_label_color(params.selected)
 723        };
 724
 725        let description = params.detail.and_then(|detail| {
 726            let path = path_for_buffer(&self.buffer, detail, false, cx)?;
 727            let description = path.trim();
 728
 729            if description.is_empty() {
 730                return None;
 731            }
 732
 733            Some(util::truncate_and_trailoff(description, MAX_TAB_TITLE_LEN))
 734        });
 735
 736        // Whether the file was saved in the past but is now deleted.
 737        let was_deleted: bool = self
 738            .buffer()
 739            .read(cx)
 740            .as_singleton()
 741            .and_then(|buffer| buffer.read(cx).file())
 742            .is_some_and(|file| file.disk_state().is_deleted());
 743
 744        h_flex()
 745            .gap_2()
 746            .child(
 747                Label::new(util::truncate_and_trailoff(
 748                    &self.title(cx),
 749                    MAX_TAB_TITLE_LEN,
 750                ))
 751                .color(label_color)
 752                .when(params.preview, |this| this.italic())
 753                .when(was_deleted, |this| this.strikethrough()),
 754            )
 755            .when_some(description, |this, description| {
 756                this.child(
 757                    Label::new(description)
 758                        .size(LabelSize::XSmall)
 759                        .color(Color::Muted),
 760                )
 761            })
 762            .into_any_element()
 763    }
 764
 765    fn for_each_project_item(
 766        &self,
 767        cx: &App,
 768        f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 769    ) {
 770        self.buffer
 771            .read(cx)
 772            .for_each_buffer(&mut |buffer| f(buffer.entity_id(), buffer.read(cx)));
 773    }
 774
 775    fn buffer_kind(&self, cx: &App) -> ItemBufferKind {
 776        match self.buffer.read(cx).is_singleton() {
 777            true => ItemBufferKind::Singleton,
 778            false => ItemBufferKind::Multibuffer,
 779        }
 780    }
 781
 782    fn can_save_as(&self, cx: &App) -> bool {
 783        self.buffer.read(cx).is_singleton()
 784    }
 785
 786    fn can_split(&self) -> bool {
 787        true
 788    }
 789
 790    fn clone_on_split(
 791        &self,
 792        _workspace_id: Option<WorkspaceId>,
 793        window: &mut Window,
 794        cx: &mut Context<Self>,
 795    ) -> Task<Option<Entity<Editor>>>
 796    where
 797        Self: Sized,
 798    {
 799        Task::ready(Some(cx.new(|cx| self.clone(window, cx))))
 800    }
 801
 802    fn set_nav_history(
 803        &mut self,
 804        history: ItemNavHistory,
 805        _window: &mut Window,
 806        _: &mut Context<Self>,
 807    ) {
 808        self.nav_history = Some(history);
 809    }
 810
 811    fn on_removed(&self, cx: &mut Context<Self>) {
 812        self.report_editor_event(ReportEditorEvent::Closed, None, cx);
 813    }
 814
 815    fn deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 816        let selection = self.selections.newest_anchor();
 817        self.push_to_nav_history(selection.head(), None, true, false, cx);
 818    }
 819
 820    fn workspace_deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 821        self.hide_hovered_link(cx);
 822    }
 823
 824    fn is_dirty(&self, cx: &App) -> bool {
 825        self.buffer().read(cx).read(cx).is_dirty()
 826    }
 827
 828    fn capability(&self, cx: &App) -> Capability {
 829        self.capability(cx)
 830    }
 831
 832    // Note: this mirrors the logic in `Editor::toggle_read_only`, but is reachable
 833    // without relying on focus-based action dispatch.
 834    fn toggle_read_only(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 835        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
 836            buffer.update(cx, |buffer, cx| {
 837                buffer.set_capability(
 838                    match buffer.capability() {
 839                        Capability::ReadWrite => Capability::Read,
 840                        Capability::Read => Capability::ReadWrite,
 841                        Capability::ReadOnly => Capability::ReadOnly,
 842                    },
 843                    cx,
 844                );
 845            });
 846        }
 847        cx.notify();
 848        window.refresh();
 849    }
 850
 851    fn has_deleted_file(&self, cx: &App) -> bool {
 852        self.buffer().read(cx).read(cx).has_deleted_file()
 853    }
 854
 855    fn has_conflict(&self, cx: &App) -> bool {
 856        self.buffer().read(cx).read(cx).has_conflict()
 857    }
 858
 859    fn can_save(&self, cx: &App) -> bool {
 860        let buffer = &self.buffer().read(cx);
 861        if let Some(buffer) = buffer.as_singleton() {
 862            buffer.read(cx).project_path(cx).is_some()
 863        } else {
 864            true
 865        }
 866    }
 867
 868    fn save(
 869        &mut self,
 870        options: SaveOptions,
 871        project: Entity<Project>,
 872        window: &mut Window,
 873        cx: &mut Context<Self>,
 874    ) -> Task<Result<()>> {
 875        // Add meta data tracking # of auto saves
 876        if options.autosave {
 877            self.report_editor_event(ReportEditorEvent::Saved { auto_saved: true }, None, cx);
 878        } else {
 879            self.report_editor_event(ReportEditorEvent::Saved { auto_saved: false }, None, cx);
 880        }
 881
 882        let buffers = self.buffer().clone().read(cx).all_buffers();
 883        let buffers = buffers
 884            .into_iter()
 885            .map(|handle| handle.read(cx).base_buffer().unwrap_or(handle.clone()))
 886            .collect::<HashSet<_>>();
 887
 888        let buffers_to_save = if self.buffer.read(cx).is_singleton() && !options.autosave {
 889            buffers
 890        } else {
 891            buffers
 892                .into_iter()
 893                .filter(|buffer| buffer.read(cx).is_dirty())
 894                .collect()
 895        };
 896
 897        let format_trigger = if options.force_format {
 898            FormatTrigger::Manual
 899        } else {
 900            FormatTrigger::Save
 901        };
 902
 903        cx.spawn_in(window, async move |this, cx| {
 904            if options.format {
 905                this.update_in(cx, |editor, window, cx| {
 906                    editor.perform_format(
 907                        project.clone(),
 908                        format_trigger,
 909                        FormatTarget::Buffers(buffers_to_save.clone()),
 910                        window,
 911                        cx,
 912                    )
 913                })?
 914                .await?;
 915            }
 916
 917            if !buffers_to_save.is_empty() {
 918                project
 919                    .update(cx, |project, cx| {
 920                        project.save_buffers(buffers_to_save.clone(), cx)
 921                    })
 922                    .await?;
 923            }
 924
 925            Ok(())
 926        })
 927    }
 928
 929    fn save_as(
 930        &mut self,
 931        project: Entity<Project>,
 932        path: ProjectPath,
 933        _: &mut Window,
 934        cx: &mut Context<Self>,
 935    ) -> Task<Result<()>> {
 936        let buffer = self
 937            .buffer()
 938            .read(cx)
 939            .as_singleton()
 940            .expect("cannot call save_as on an excerpt list");
 941
 942        let file_extension = path.path.extension().map(|a| a.to_string());
 943        self.report_editor_event(
 944            ReportEditorEvent::Saved { auto_saved: false },
 945            file_extension,
 946            cx,
 947        );
 948
 949        project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
 950    }
 951
 952    fn reload(
 953        &mut self,
 954        project: Entity<Project>,
 955        window: &mut Window,
 956        cx: &mut Context<Self>,
 957    ) -> Task<Result<()>> {
 958        let buffer = self.buffer().clone();
 959        let buffers = self.buffer.read(cx).all_buffers();
 960        let reload_buffers =
 961            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
 962        cx.spawn_in(window, async move |this, cx| {
 963            let transaction = reload_buffers.log_err().await;
 964            this.update(cx, |editor, cx| {
 965                editor.request_autoscroll(Autoscroll::fit(), cx)
 966            })?;
 967            buffer.update(cx, |buffer, cx| {
 968                if let Some(transaction) = transaction
 969                    && !buffer.is_singleton()
 970                {
 971                    buffer.push_transaction(&transaction.0, cx);
 972                }
 973            });
 974            Ok(())
 975        })
 976    }
 977
 978    fn as_searchable(
 979        &self,
 980        handle: &Entity<Self>,
 981        _: &App,
 982    ) -> Option<Box<dyn SearchableItemHandle>> {
 983        Some(Box::new(handle.clone()))
 984    }
 985
 986    fn pixel_position_of_cursor(&self, _: &App) -> Option<gpui::Point<Pixels>> {
 987        self.pixel_position_of_newest_cursor
 988    }
 989
 990    fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
 991        if self.show_breadcrumbs && self.buffer().read(cx).is_singleton() {
 992            ToolbarItemLocation::PrimaryLeft
 993        } else {
 994            ToolbarItemLocation::Hidden
 995        }
 996    }
 997
 998    // In a non-singleton case, the breadcrumbs are actually shown on sticky file headers of the multibuffer.
 999    fn breadcrumbs(&self, cx: &App) -> Option<(Vec<HighlightedText>, Option<Font>)> {
1000        if self.buffer.read(cx).is_singleton() {
1001            let font = theme_settings::ThemeSettings::get_global(cx)
1002                .buffer_font
1003                .clone();
1004            Some((self.breadcrumbs_inner(cx)?, Some(font)))
1005        } else {
1006            None
1007        }
1008    }
1009
1010    fn added_to_workspace(
1011        &mut self,
1012        workspace: &mut Workspace,
1013        window: &mut Window,
1014        cx: &mut Context<Self>,
1015    ) {
1016        self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
1017        if let Some(workspace_entity) = &workspace.weak_handle().upgrade() {
1018            cx.subscribe(
1019                workspace_entity,
1020                |editor, _, event: &workspace::Event, cx| {
1021                    if let workspace::Event::ModalOpened = event {
1022                        editor.mouse_context_menu.take();
1023                        editor.hide_blame_popover(true, cx);
1024                    }
1025                },
1026            )
1027            .detach();
1028        }
1029
1030        // Load persisted folds if this editor doesn't already have folds.
1031        // This handles manually-opened files (not workspace restoration).
1032        let display_snapshot = self
1033            .display_map
1034            .update(cx, |display_map, cx| display_map.snapshot(cx));
1035        let has_folds = display_snapshot
1036            .folds_in_range(MultiBufferOffset(0)..display_snapshot.buffer_snapshot().len())
1037            .next()
1038            .is_some();
1039
1040        if !has_folds {
1041            if let Some(workspace_id) = workspace.database_id()
1042                && let Some(file_path) = self.buffer().read(cx).as_singleton().and_then(|buffer| {
1043                    project::File::from_dyn(buffer.read(cx).file()).map(|file| file.abs_path(cx))
1044                })
1045            {
1046                self.load_folds_from_db(workspace_id, file_path, window, cx);
1047            }
1048        }
1049    }
1050
1051    fn pane_changed(&mut self, new_pane_id: EntityId, cx: &mut Context<Self>) {
1052        if self
1053            .highlighted_rows
1054            .get(&TypeId::of::<ActiveDebugLine>())
1055            .is_some_and(|lines| !lines.is_empty())
1056            && let Some(breakpoint_store) = self.breakpoint_store.as_ref()
1057        {
1058            breakpoint_store.update(cx, |store, _cx| {
1059                store.set_active_debug_pane_id(new_pane_id);
1060            });
1061        }
1062    }
1063
1064    fn to_item_events(event: &EditorEvent, f: &mut dyn FnMut(ItemEvent)) {
1065        match event {
1066            EditorEvent::Saved | EditorEvent::TitleChanged => {
1067                f(ItemEvent::UpdateTab);
1068                f(ItemEvent::UpdateBreadcrumbs);
1069            }
1070
1071            EditorEvent::Reparsed(_) => {
1072                f(ItemEvent::UpdateBreadcrumbs);
1073            }
1074
1075            EditorEvent::SelectionsChanged { local } if *local => {
1076                f(ItemEvent::UpdateBreadcrumbs);
1077            }
1078
1079            EditorEvent::BreadcrumbsChanged => {
1080                f(ItemEvent::UpdateBreadcrumbs);
1081            }
1082
1083            EditorEvent::DirtyChanged => {
1084                f(ItemEvent::UpdateTab);
1085            }
1086
1087            EditorEvent::BufferEdited => {
1088                f(ItemEvent::Edit);
1089                f(ItemEvent::UpdateBreadcrumbs);
1090            }
1091
1092            EditorEvent::BufferRangesUpdated { .. } | EditorEvent::BuffersRemoved { .. } => {
1093                f(ItemEvent::Edit);
1094            }
1095
1096            _ => {}
1097        }
1098    }
1099
1100    fn tab_extra_context_menu_actions(
1101        &self,
1102        _window: &mut Window,
1103        cx: &mut Context<Self>,
1104    ) -> Vec<(SharedString, Box<dyn gpui::Action>)> {
1105        let mut actions = Vec::new();
1106
1107        let is_markdown = self
1108            .buffer()
1109            .read(cx)
1110            .as_singleton()
1111            .and_then(|buffer| buffer.read(cx).language())
1112            .is_some_and(|language| language.name().as_ref() == "Markdown");
1113
1114        let is_svg = self
1115            .buffer()
1116            .read(cx)
1117            .as_singleton()
1118            .and_then(|buffer| buffer.read(cx).file())
1119            .is_some_and(|file| {
1120                std::path::Path::new(file.file_name(cx))
1121                    .extension()
1122                    .is_some_and(|ext| ext.eq_ignore_ascii_case("svg"))
1123            });
1124
1125        if is_markdown {
1126            actions.push((
1127                "Open Markdown Preview".into(),
1128                Box::new(OpenMarkdownPreview) as Box<dyn gpui::Action>,
1129            ));
1130        }
1131
1132        if is_svg {
1133            actions.push((
1134                "Open SVG Preview".into(),
1135                Box::new(OpenSvgPreview) as Box<dyn gpui::Action>,
1136            ));
1137        }
1138
1139        actions
1140    }
1141
1142    fn preserve_preview(&self, cx: &App) -> bool {
1143        self.buffer.read(cx).preserve_preview(cx)
1144    }
1145}
1146
1147impl SerializableItem for Editor {
1148    fn serialized_item_kind() -> &'static str {
1149        "Editor"
1150    }
1151
1152    fn cleanup(
1153        workspace_id: WorkspaceId,
1154        alive_items: Vec<ItemId>,
1155        _window: &mut Window,
1156        cx: &mut App,
1157    ) -> Task<Result<()>> {
1158        workspace::delete_unloaded_items(
1159            alive_items,
1160            workspace_id,
1161            "editors",
1162            &EditorDb::global(cx),
1163            cx,
1164        )
1165    }
1166
1167    fn deserialize(
1168        project: Entity<Project>,
1169        _workspace: WeakEntity<Workspace>,
1170        workspace_id: workspace::WorkspaceId,
1171        item_id: ItemId,
1172        window: &mut Window,
1173        cx: &mut App,
1174    ) -> Task<Result<Entity<Self>>> {
1175        let serialized_editor = match EditorDb::global(cx)
1176            .get_serialized_editor(item_id, workspace_id)
1177            .context("Failed to query editor state")
1178        {
1179            Ok(Some(serialized_editor)) => {
1180                if ProjectSettings::get_global(cx)
1181                    .session
1182                    .restore_unsaved_buffers
1183                {
1184                    serialized_editor
1185                } else {
1186                    SerializedEditor {
1187                        abs_path: serialized_editor.abs_path,
1188                        contents: None,
1189                        language: None,
1190                        mtime: None,
1191                    }
1192                }
1193            }
1194            Ok(None) => {
1195                return Task::ready(Err(anyhow!(
1196                    "Unable to deserialize editor: No entry in database for item_id: {item_id} and workspace_id {workspace_id:?}"
1197                )));
1198            }
1199            Err(error) => {
1200                return Task::ready(Err(error));
1201            }
1202        };
1203        log::debug!(
1204            "Deserialized editor {item_id:?} in workspace {workspace_id:?}, {serialized_editor:?}"
1205        );
1206
1207        match serialized_editor {
1208            SerializedEditor {
1209                abs_path: None,
1210                contents: Some(contents),
1211                language,
1212                ..
1213            } => window.spawn(cx, {
1214                let project = project.clone();
1215                async move |cx| {
1216                    let language_registry =
1217                        project.read_with(cx, |project, _| project.languages().clone());
1218
1219                    let language = if let Some(language_name) = language {
1220                        // We don't fail here, because we'd rather not set the language if the name changed
1221                        // than fail to restore the buffer.
1222                        language_registry
1223                            .language_for_name(&language_name)
1224                            .await
1225                            .ok()
1226                    } else {
1227                        None
1228                    };
1229
1230                    // First create the empty buffer
1231                    let buffer = project
1232                        .update(cx, |project, cx| project.create_buffer(language, true, cx))
1233                        .await
1234                        .context("Failed to create buffer while deserializing editor")?;
1235
1236                    // Then set the text so that the dirty bit is set correctly
1237                    buffer.update(cx, |buffer, cx| {
1238                        buffer.set_language_registry(language_registry);
1239                        buffer.set_text(contents, cx);
1240                        if let Some(entry) = buffer.peek_undo_stack() {
1241                            buffer.forget_transaction(entry.transaction_id());
1242                        }
1243                    });
1244
1245                    cx.update(|window, cx| {
1246                        cx.new(|cx| {
1247                            let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1248
1249                            editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1250                            editor
1251                        })
1252                    })
1253                }
1254            }),
1255            SerializedEditor {
1256                abs_path: Some(abs_path),
1257                contents,
1258                mtime,
1259                ..
1260            } => {
1261                let opened_buffer = project.update(cx, |project, cx| {
1262                    let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1263                    let project_path = ProjectPath {
1264                        worktree_id: worktree.read(cx).id(),
1265                        path: path,
1266                    };
1267                    Some(project.open_path(project_path, cx))
1268                });
1269
1270                match opened_buffer {
1271                    Some(opened_buffer) => window.spawn(cx, async move |cx| {
1272                        let (_, buffer) = opened_buffer
1273                            .await
1274                            .context("Failed to open path in project")?;
1275
1276                        if let Some(contents) = contents {
1277                            buffer.update(cx, |buffer, cx| {
1278                                restore_serialized_buffer_contents(buffer, contents, mtime, cx);
1279                            });
1280                        }
1281
1282                        cx.update(|window, cx| {
1283                            cx.new(|cx| {
1284                                let mut editor =
1285                                    Editor::for_buffer(buffer, Some(project), window, cx);
1286
1287                                editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1288                                editor
1289                            })
1290                        })
1291                    }),
1292                    None => {
1293                        // File is not in any worktree (e.g., opened as a standalone file).
1294                        // Open the buffer directly via the project rather than through
1295                        // workspace.open_abs_path(), which has the side effect of adding
1296                        // the item to a pane. The caller (deserialize_to) will add the
1297                        // returned item to the correct pane.
1298                        window.spawn(cx, async move |cx| {
1299                            let buffer = project
1300                                .update(cx, |project, cx| project.open_local_buffer(&abs_path, cx))
1301                                .await
1302                                .with_context(|| {
1303                                    format!("Failed to open buffer for {abs_path:?}")
1304                                })?;
1305
1306                            if let Some(contents) = contents {
1307                                buffer.update(cx, |buffer, cx| {
1308                                    restore_serialized_buffer_contents(buffer, contents, mtime, cx);
1309                                });
1310                            }
1311
1312                            cx.update(|window, cx| {
1313                                cx.new(|cx| {
1314                                    let mut editor =
1315                                        Editor::for_buffer(buffer, Some(project), window, cx);
1316                                    editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1317                                    editor
1318                                })
1319                            })
1320                        })
1321                    }
1322                }
1323            }
1324            SerializedEditor {
1325                abs_path: None,
1326                contents: None,
1327                ..
1328            } => window.spawn(cx, async move |cx| {
1329                let buffer = project
1330                    .update(cx, |project, cx| project.create_buffer(None, true, cx))
1331                    .await
1332                    .context("Failed to create buffer")?;
1333
1334                cx.update(|window, cx| {
1335                    cx.new(|cx| {
1336                        let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1337
1338                        editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1339                        editor
1340                    })
1341                })
1342            }),
1343        }
1344    }
1345
1346    fn serialize(
1347        &mut self,
1348        workspace: &mut Workspace,
1349        item_id: ItemId,
1350        closing: bool,
1351        window: &mut Window,
1352        cx: &mut Context<Self>,
1353    ) -> Option<Task<Result<()>>> {
1354        let buffer_serialization = self.buffer_serialization?;
1355        let project = self.project.clone()?;
1356
1357        let serialize_dirty_buffers = match buffer_serialization {
1358            // Always serialize dirty buffers, including for worktree-less windows.
1359            // This enables hot-exit functionality for empty windows and single files.
1360            BufferSerialization::All => true,
1361            BufferSerialization::NonDirtyBuffers => false,
1362        };
1363
1364        if closing && !serialize_dirty_buffers {
1365            return None;
1366        }
1367
1368        let workspace_id = workspace.database_id()?;
1369
1370        let buffer = self.buffer().read(cx).as_singleton()?;
1371
1372        let abs_path = buffer.read(cx).file().and_then(|file| {
1373            let worktree_id = file.worktree_id(cx);
1374            project
1375                .read(cx)
1376                .worktree_for_id(worktree_id, cx)
1377                .map(|worktree| worktree.read(cx).absolutize(file.path()))
1378                .or_else(|| {
1379                    let full_path = file.full_path(cx);
1380                    let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1381                    project.read(cx).absolute_path(&project_path, cx)
1382                })
1383        });
1384
1385        let is_dirty = buffer.read(cx).is_dirty();
1386        let mtime = buffer.read(cx).saved_mtime();
1387
1388        let snapshot = buffer.read(cx).snapshot();
1389
1390        let db = EditorDb::global(cx);
1391        Some(cx.spawn_in(window, async move |_this, cx| {
1392            cx.background_spawn(async move {
1393                let (contents, language) = if serialize_dirty_buffers && is_dirty {
1394                    let contents = snapshot.text();
1395                    let language = snapshot.language().map(|lang| lang.name().to_string());
1396                    (Some(contents), language)
1397                } else {
1398                    (None, None)
1399                };
1400
1401                let editor = SerializedEditor {
1402                    abs_path,
1403                    contents,
1404                    language,
1405                    mtime,
1406                };
1407                log::debug!("Serializing editor {item_id:?} in workspace {workspace_id:?}");
1408                db.save_serialized_editor(item_id, workspace_id, editor)
1409                    .await
1410                    .context("failed to save serialized editor")
1411            })
1412            .await
1413            .context("failed to save contents of buffer")?;
1414
1415            Ok(())
1416        }))
1417    }
1418
1419    fn should_serialize(&self, event: &Self::Event) -> bool {
1420        self.should_serialize_buffer()
1421            && matches!(
1422                event,
1423                EditorEvent::Saved
1424                    | EditorEvent::DirtyChanged
1425                    | EditorEvent::BufferEdited
1426                    | EditorEvent::FileHandleChanged
1427            )
1428    }
1429}
1430
1431#[derive(Debug, Default)]
1432struct EditorRestorationData {
1433    entries: HashMap<PathBuf, RestorationData>,
1434}
1435
1436#[derive(Default, Debug)]
1437pub struct RestorationData {
1438    pub scroll_position: (BufferRow, gpui::Point<ScrollOffset>),
1439    pub folds: Vec<Range<Point>>,
1440    pub selections: Vec<Range<Point>>,
1441}
1442
1443impl ProjectItem for Editor {
1444    type Item = Buffer;
1445
1446    fn project_item_kind() -> Option<ProjectItemKind> {
1447        Some(ProjectItemKind("Editor"))
1448    }
1449
1450    fn for_project_item(
1451        project: Entity<Project>,
1452        pane: Option<&Pane>,
1453        buffer: Entity<Buffer>,
1454        window: &mut Window,
1455        cx: &mut Context<Self>,
1456    ) -> Self {
1457        let mut editor = Self::for_buffer(buffer.clone(), Some(project), window, cx);
1458        let multibuffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1459
1460        if let Some(buffer_snapshot) = editor.buffer().read(cx).snapshot(cx).as_singleton()
1461            && WorkspaceSettings::get(None, cx).restore_on_file_reopen
1462            && let Some(restoration_data) = Self::project_item_kind()
1463                .and_then(|kind| pane.as_ref()?.project_item_restoration_data.get(&kind))
1464                .and_then(|data| data.downcast_ref::<EditorRestorationData>())
1465                .and_then(|data| {
1466                    let file = project::File::from_dyn(buffer.read(cx).file())?;
1467                    data.entries.get(&file.abs_path(cx))
1468                })
1469        {
1470            if !restoration_data.folds.is_empty() {
1471                editor.fold_ranges(
1472                    clip_ranges(&restoration_data.folds, buffer_snapshot),
1473                    false,
1474                    window,
1475                    cx,
1476                );
1477            }
1478            if !restoration_data.selections.is_empty() {
1479                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1480                    s.select_ranges(clip_ranges(&restoration_data.selections, buffer_snapshot));
1481                });
1482            }
1483            let (top_row, offset) = restoration_data.scroll_position;
1484            let anchor = multibuffer_snapshot.anchor_before(Point::new(top_row, 0));
1485            editor.set_scroll_anchor(ScrollAnchor { anchor, offset }, window, cx);
1486        }
1487
1488        editor
1489    }
1490
1491    fn for_broken_project_item(
1492        abs_path: &Path,
1493        is_local: bool,
1494        e: &anyhow::Error,
1495        window: &mut Window,
1496        cx: &mut App,
1497    ) -> Option<InvalidItemView> {
1498        Some(InvalidItemView::new(abs_path, is_local, e, window, cx))
1499    }
1500}
1501
1502fn clip_ranges<'a>(
1503    original: impl IntoIterator<Item = &'a Range<Point>> + 'a,
1504    snapshot: &'a BufferSnapshot,
1505) -> Vec<Range<Point>> {
1506    original
1507        .into_iter()
1508        .map(|range| {
1509            snapshot.clip_point(range.start, Bias::Left)
1510                ..snapshot.clip_point(range.end, Bias::Right)
1511        })
1512        .collect()
1513}
1514
1515impl EventEmitter<SearchEvent> for Editor {}
1516
1517impl Editor {
1518    pub fn update_restoration_data(
1519        &self,
1520        cx: &mut Context<Self>,
1521        write: impl for<'a> FnOnce(&'a mut RestorationData) + 'static,
1522    ) {
1523        if self.mode.is_minimap() || !WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1524            return;
1525        }
1526
1527        let editor = cx.entity();
1528        cx.defer(move |cx| {
1529            editor.update(cx, |editor, cx| {
1530                let kind = Editor::project_item_kind()?;
1531                let pane = editor.workspace()?.read(cx).pane_for(&cx.entity())?;
1532                let buffer = editor.buffer().read(cx).as_singleton()?;
1533                let file_abs_path = project::File::from_dyn(buffer.read(cx).file())?.abs_path(cx);
1534                pane.update(cx, |pane, _| {
1535                    let data = pane
1536                        .project_item_restoration_data
1537                        .entry(kind)
1538                        .or_insert_with(|| Box::new(EditorRestorationData::default()) as Box<_>);
1539                    let data = match data.downcast_mut::<EditorRestorationData>() {
1540                        Some(data) => data,
1541                        None => {
1542                            *data = Box::new(EditorRestorationData::default());
1543                            data.downcast_mut::<EditorRestorationData>()
1544                                .expect("just written the type downcasted to")
1545                        }
1546                    };
1547
1548                    let data = data.entries.entry(file_abs_path).or_default();
1549                    write(data);
1550                    Some(())
1551                })
1552            });
1553        });
1554    }
1555}
1556
1557impl SearchableItem for Editor {
1558    type Match = Range<Anchor>;
1559
1560    fn get_matches(&self, _window: &mut Window, _: &mut App) -> (Vec<Range<Anchor>>, SearchToken) {
1561        (
1562            self.background_highlights
1563                .get(&HighlightKey::BufferSearchHighlights)
1564                .map_or(Vec::new(), |(_color, ranges)| {
1565                    ranges.iter().cloned().collect()
1566                }),
1567            SearchToken::default(),
1568        )
1569    }
1570
1571    fn clear_matches(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1572        if self
1573            .clear_background_highlights(HighlightKey::BufferSearchHighlights, cx)
1574            .is_some()
1575        {
1576            cx.emit(SearchEvent::MatchesInvalidated);
1577        }
1578    }
1579
1580    fn update_matches(
1581        &mut self,
1582        matches: &[Range<Anchor>],
1583        active_match_index: Option<usize>,
1584        _token: SearchToken,
1585        _: &mut Window,
1586        cx: &mut Context<Self>,
1587    ) {
1588        let existing_range = self
1589            .background_highlights
1590            .get(&HighlightKey::BufferSearchHighlights)
1591            .map(|(_, range)| range.as_ref());
1592        let updated = existing_range != Some(matches);
1593        self.highlight_background(
1594            HighlightKey::BufferSearchHighlights,
1595            matches,
1596            move |index, theme| {
1597                if active_match_index == Some(*index) {
1598                    theme.colors().search_active_match_background
1599                } else {
1600                    theme.colors().search_match_background
1601                }
1602            },
1603            cx,
1604        );
1605        if updated {
1606            cx.emit(SearchEvent::MatchesInvalidated);
1607        }
1608    }
1609
1610    fn has_filtered_search_ranges(&mut self) -> bool {
1611        self.has_background_highlights(HighlightKey::SearchWithinRange)
1612    }
1613
1614    fn toggle_filtered_search_ranges(
1615        &mut self,
1616        enabled: Option<FilteredSearchRange>,
1617        _: &mut Window,
1618        cx: &mut Context<Self>,
1619    ) {
1620        if self.has_filtered_search_ranges() {
1621            self.previous_search_ranges = self
1622                .clear_background_highlights(HighlightKey::SearchWithinRange, cx)
1623                .map(|(_, ranges)| ranges)
1624        }
1625
1626        if let Some(range) = enabled {
1627            let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1628
1629            if ranges.iter().any(|s| s.start != s.end) {
1630                self.set_search_within_ranges(&ranges, cx);
1631            } else if let Some(previous_search_ranges) = self.previous_search_ranges.take()
1632                && range != FilteredSearchRange::Selection
1633            {
1634                self.set_search_within_ranges(&previous_search_ranges, cx);
1635            }
1636        }
1637    }
1638
1639    fn supported_options(&self) -> SearchOptions {
1640        if self.in_project_search {
1641            SearchOptions {
1642                case: true,
1643                word: true,
1644                regex: true,
1645                replacement: false,
1646                selection: false,
1647                select_all: true,
1648                find_in_results: true,
1649            }
1650        } else {
1651            SearchOptions {
1652                case: true,
1653                word: true,
1654                regex: true,
1655                replacement: true,
1656                selection: true,
1657                select_all: true,
1658                find_in_results: false,
1659            }
1660        }
1661    }
1662
1663    fn query_suggestion(
1664        &mut self,
1665        ignore_settings: bool,
1666        window: &mut Window,
1667        cx: &mut Context<Self>,
1668    ) -> String {
1669        let setting = if ignore_settings {
1670            SeedQuerySetting::Always
1671        } else {
1672            EditorSettings::get_global(cx).seed_search_query_from_cursor
1673        };
1674        let snapshot = self.snapshot(window, cx);
1675        let selection = self.selections.newest_adjusted(&snapshot.display_snapshot);
1676        let buffer_snapshot = snapshot.buffer_snapshot();
1677
1678        match setting {
1679            SeedQuerySetting::Never => String::new(),
1680            SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1681                buffer_snapshot
1682                    .text_for_range(selection.start..selection.end)
1683                    .collect()
1684            }
1685            SeedQuerySetting::Selection => String::new(),
1686            SeedQuerySetting::Always => {
1687                let (range, kind) = buffer_snapshot
1688                    .surrounding_word(selection.start, Some(CharScopeContext::Completion));
1689                if kind == Some(CharKind::Word) {
1690                    let text: String = buffer_snapshot.text_for_range(range).collect();
1691                    if !text.trim().is_empty() {
1692                        return text;
1693                    }
1694                }
1695                String::new()
1696            }
1697        }
1698    }
1699
1700    fn activate_match(
1701        &mut self,
1702        index: usize,
1703        matches: &[Range<Anchor>],
1704        _token: SearchToken,
1705        window: &mut Window,
1706        cx: &mut Context<Self>,
1707    ) {
1708        self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1709        let range = self.range_for_match(&matches[index]);
1710        let autoscroll = if EditorSettings::get_global(cx).search.center_on_match {
1711            Autoscroll::center()
1712        } else {
1713            Autoscroll::fit()
1714        };
1715        self.change_selections(
1716            SelectionEffects::scroll(autoscroll).from_search(true),
1717            window,
1718            cx,
1719            |s| {
1720                s.select_ranges([range]);
1721            },
1722        )
1723    }
1724
1725    fn select_matches(
1726        &mut self,
1727        matches: &[Self::Match],
1728        _token: SearchToken,
1729        window: &mut Window,
1730        cx: &mut Context<Self>,
1731    ) {
1732        self.unfold_ranges(matches, false, false, cx);
1733        self.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1734            s.select_ranges(matches.iter().cloned())
1735        });
1736    }
1737    fn replace(
1738        &mut self,
1739        identifier: &Self::Match,
1740        query: &SearchQuery,
1741        _token: SearchToken,
1742        window: &mut Window,
1743        cx: &mut Context<Self>,
1744    ) {
1745        let text = self.buffer.read(cx);
1746        let text = text.snapshot(cx);
1747        let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1748        let text: Cow<_> = if text.len() == 1 {
1749            text.first().cloned().unwrap().into()
1750        } else {
1751            let joined_chunks = text.join("");
1752            joined_chunks.into()
1753        };
1754
1755        if let Some(replacement) = query.replacement_for(&text) {
1756            self.transact(window, cx, |this, _, cx| {
1757                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1758            });
1759        }
1760    }
1761    fn replace_all(
1762        &mut self,
1763        matches: &mut dyn Iterator<Item = &Self::Match>,
1764        query: &SearchQuery,
1765        _token: SearchToken,
1766        window: &mut Window,
1767        cx: &mut Context<Self>,
1768    ) {
1769        let text = self.buffer.read(cx);
1770        let text = text.snapshot(cx);
1771        let mut edits = vec![];
1772
1773        // A regex might have replacement variables so we cannot apply
1774        // the same replacement to all matches
1775        if query.is_regex() {
1776            edits = matches
1777                .filter_map(|m| {
1778                    let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1779
1780                    let text: Cow<_> = if text.len() == 1 {
1781                        text.first().cloned().unwrap().into()
1782                    } else {
1783                        let joined_chunks = text.join("");
1784                        joined_chunks.into()
1785                    };
1786
1787                    query
1788                        .replacement_for(&text)
1789                        .map(|replacement| (m.clone(), Arc::from(&*replacement)))
1790                })
1791                .collect();
1792        } else if let Some(replacement) = query.replacement().map(Arc::<str>::from) {
1793            edits = matches.map(|m| (m.clone(), replacement.clone())).collect();
1794        }
1795
1796        if !edits.is_empty() {
1797            self.transact(window, cx, |this, _, cx| {
1798                this.edit(edits, cx);
1799            });
1800        }
1801    }
1802    fn match_index_for_direction(
1803        &mut self,
1804        matches: &[Range<Anchor>],
1805        current_index: usize,
1806        direction: Direction,
1807        count: usize,
1808        _token: SearchToken,
1809        _: &mut Window,
1810        cx: &mut Context<Self>,
1811    ) -> usize {
1812        let buffer = self.buffer().read(cx).snapshot(cx);
1813        let current_index_position = if self.selections.disjoint_anchors_arc().len() == 1 {
1814            self.selections.newest_anchor().head()
1815        } else {
1816            matches[current_index].start
1817        };
1818
1819        let mut count = count % matches.len();
1820        if count == 0 {
1821            return current_index;
1822        }
1823        match direction {
1824            Direction::Next => {
1825                if matches[current_index]
1826                    .start
1827                    .cmp(&current_index_position, &buffer)
1828                    .is_gt()
1829                {
1830                    count -= 1
1831                }
1832
1833                (current_index + count) % matches.len()
1834            }
1835            Direction::Prev => {
1836                if matches[current_index]
1837                    .end
1838                    .cmp(&current_index_position, &buffer)
1839                    .is_lt()
1840                {
1841                    count -= 1;
1842                }
1843
1844                if current_index >= count {
1845                    current_index - count
1846                } else {
1847                    matches.len() - (count - current_index)
1848                }
1849            }
1850        }
1851    }
1852
1853    fn find_matches(
1854        &mut self,
1855        query: Arc<project::search::SearchQuery>,
1856        _: &mut Window,
1857        cx: &mut Context<Self>,
1858    ) -> Task<Vec<Range<Anchor>>> {
1859        let buffer = self.buffer().read(cx).snapshot(cx);
1860        let search_within_ranges = self
1861            .background_highlights
1862            .get(&HighlightKey::SearchWithinRange)
1863            .map_or(vec![], |(_color, ranges)| {
1864                ranges.iter().cloned().collect::<Vec<_>>()
1865            });
1866
1867        cx.background_spawn(async move {
1868            let mut ranges = Vec::new();
1869
1870            let search_within_ranges = if search_within_ranges.is_empty() {
1871                vec![buffer.anchor_before(MultiBufferOffset(0))..buffer.anchor_after(buffer.len())]
1872            } else {
1873                search_within_ranges
1874            };
1875
1876            for range in search_within_ranges {
1877                for (search_buffer, search_range, deleted_hunk_anchor) in
1878                    buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1879                {
1880                    ranges.extend(
1881                        query
1882                            .search(
1883                                search_buffer,
1884                                Some(search_range.start.0..search_range.end.0),
1885                            )
1886                            .await
1887                            .into_iter()
1888                            .filter_map(|match_range| {
1889                                if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
1890                                    let start = search_buffer
1891                                        .anchor_after(search_range.start + match_range.start);
1892                                    let end = search_buffer
1893                                        .anchor_before(search_range.start + match_range.end);
1894                                    Some(
1895                                        deleted_hunk_anchor.with_diff_base_anchor(start)
1896                                            ..deleted_hunk_anchor.with_diff_base_anchor(end),
1897                                    )
1898                                } else {
1899                                    let start = search_buffer
1900                                        .anchor_after(search_range.start + match_range.start);
1901                                    let end = search_buffer
1902                                        .anchor_before(search_range.start + match_range.end);
1903                                    buffer.buffer_anchor_range_to_anchor_range(start..end)
1904                                }
1905                            }),
1906                    );
1907                }
1908            }
1909
1910            ranges
1911        })
1912    }
1913
1914    fn active_match_index(
1915        &mut self,
1916        direction: Direction,
1917        matches: &[Range<Anchor>],
1918        _token: SearchToken,
1919        _: &mut Window,
1920        cx: &mut Context<Self>,
1921    ) -> Option<usize> {
1922        active_match_index(
1923            direction,
1924            matches,
1925            &self.selections.newest_anchor().head(),
1926            &self.buffer().read(cx).snapshot(cx),
1927        )
1928    }
1929
1930    fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
1931        self.expect_bounds_change = self.last_bounds;
1932    }
1933
1934    fn set_search_is_case_sensitive(
1935        &mut self,
1936        case_sensitive: Option<bool>,
1937        _cx: &mut Context<Self>,
1938    ) {
1939        self.select_next_is_case_sensitive = case_sensitive;
1940    }
1941}
1942
1943pub fn active_match_index(
1944    direction: Direction,
1945    ranges: &[Range<Anchor>],
1946    cursor: &Anchor,
1947    buffer: &MultiBufferSnapshot,
1948) -> Option<usize> {
1949    if ranges.is_empty() {
1950        None
1951    } else {
1952        let r = ranges.binary_search_by(|probe| {
1953            if probe.end.cmp(cursor, buffer).is_lt() {
1954                Ordering::Less
1955            } else if probe.start.cmp(cursor, buffer).is_gt() {
1956                Ordering::Greater
1957            } else {
1958                Ordering::Equal
1959            }
1960        });
1961        match direction {
1962            Direction::Prev => match r {
1963                Ok(i) => Some(i),
1964                Err(i) => Some(i.saturating_sub(1)),
1965            },
1966            Direction::Next => match r {
1967                Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1968            },
1969        }
1970    }
1971}
1972
1973pub fn entry_label_color(selected: bool) -> Color {
1974    if selected {
1975        Color::Default
1976    } else {
1977        Color::Muted
1978    }
1979}
1980
1981pub fn entry_diagnostic_aware_icon_name_and_color(
1982    diagnostic_severity: Option<DiagnosticSeverity>,
1983) -> Option<(IconName, Color)> {
1984    match diagnostic_severity {
1985        Some(DiagnosticSeverity::ERROR) => Some((IconName::Close, Color::Error)),
1986        Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1987        _ => None,
1988    }
1989}
1990
1991pub fn entry_diagnostic_aware_icon_decoration_and_color(
1992    diagnostic_severity: Option<DiagnosticSeverity>,
1993) -> Option<(IconDecorationKind, Color)> {
1994    match diagnostic_severity {
1995        Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1996        Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1997        _ => None,
1998    }
1999}
2000
2001pub fn entry_git_aware_label_color(git_status: GitSummary, ignored: bool, selected: bool) -> Color {
2002    let tracked = git_status.index + git_status.worktree;
2003    if git_status.conflict > 0 {
2004        Color::Conflict
2005    } else if tracked.deleted > 0 {
2006        Color::Deleted
2007    } else if tracked.modified > 0 {
2008        Color::Modified
2009    } else if tracked.added > 0 || git_status.untracked > 0 {
2010        Color::Created
2011    } else if ignored {
2012        Color::Ignored
2013    } else {
2014        entry_label_color(selected)
2015    }
2016}
2017
2018fn path_for_buffer<'a>(
2019    buffer: &Entity<MultiBuffer>,
2020    height: usize,
2021    include_filename: bool,
2022    cx: &'a App,
2023) -> Option<Cow<'a, str>> {
2024    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
2025    path_for_file(file, height, include_filename, cx)
2026}
2027
2028fn path_for_file<'a>(
2029    file: &'a Arc<dyn language::File>,
2030    mut height: usize,
2031    include_filename: bool,
2032    cx: &'a App,
2033) -> Option<Cow<'a, str>> {
2034    if project::File::from_dyn(Some(file)).is_none() {
2035        return None;
2036    }
2037
2038    let file = file.as_ref();
2039    // Ensure we always render at least the filename.
2040    height += 1;
2041
2042    let mut prefix = file.path().as_ref();
2043    while height > 0 {
2044        if let Some(parent) = prefix.parent() {
2045            prefix = parent;
2046            height -= 1;
2047        } else {
2048            break;
2049        }
2050    }
2051
2052    // The full_path method allocates, so avoid calling it if height is zero.
2053    if height > 0 {
2054        let mut full_path = file.full_path(cx);
2055        if !include_filename {
2056            if !full_path.pop() {
2057                return None;
2058            }
2059        }
2060        Some(full_path.to_string_lossy().into_owned().into())
2061    } else {
2062        let mut path = file.path().strip_prefix(prefix).ok()?;
2063        if !include_filename {
2064            path = path.parent()?;
2065        }
2066        Some(path.display(file.path_style(cx)))
2067    }
2068}
2069
2070/// Restores serialized buffer contents by overwriting the buffer with saved text.
2071/// This is somewhat wasteful since we load the whole buffer from disk then overwrite it,
2072/// but keeps implementation simple as we don't need to persist all metadata from loading
2073/// (git diff base, etc.).
2074fn restore_serialized_buffer_contents(
2075    buffer: &mut Buffer,
2076    contents: String,
2077    mtime: Option<MTime>,
2078    cx: &mut Context<Buffer>,
2079) {
2080    // If we did restore an mtime, store it on the buffer so that
2081    // the next edit will mark the buffer as dirty/conflicted.
2082    if mtime.is_some() {
2083        buffer.did_reload(buffer.version(), buffer.line_ending(), mtime, cx);
2084    }
2085    buffer.set_text(contents, cx);
2086    if let Some(entry) = buffer.peek_undo_stack() {
2087        buffer.forget_transaction(entry.transaction_id());
2088    }
2089}
2090
2091fn serialize_path_key(path_key: &PathKey) -> proto::PathKey {
2092    proto::PathKey {
2093        sort_prefix: path_key.sort_prefix,
2094        path: path_key.path.to_proto(),
2095    }
2096}
2097
2098fn deserialize_path_key(path_key: proto::PathKey) -> Option<PathKey> {
2099    Some(PathKey {
2100        sort_prefix: path_key.sort_prefix,
2101        path: RelPath::from_proto(&path_key.path).ok()?,
2102    })
2103}
2104
2105#[cfg(test)]
2106mod tests {
2107    use crate::editor_tests::init_test;
2108    use fs::Fs;
2109    use workspace::MultiWorkspace;
2110
2111    use super::*;
2112    use fs::MTime;
2113    use gpui::{App, VisualTestContext};
2114    use language::TestFile;
2115    use project::FakeFs;
2116    use serde_json::json;
2117    use std::path::{Path, PathBuf};
2118    use util::{path, rel_path::RelPath};
2119
2120    #[gpui::test]
2121    fn test_path_for_file(cx: &mut App) {
2122        let file: Arc<dyn language::File> = Arc::new(TestFile {
2123            path: RelPath::empty().into(),
2124            root_name: String::new(),
2125            local_root: None,
2126        });
2127        assert_eq!(path_for_file(&file, 0, false, cx), None);
2128    }
2129
2130    async fn deserialize_editor(
2131        item_id: ItemId,
2132        workspace_id: WorkspaceId,
2133        workspace: Entity<Workspace>,
2134        project: Entity<Project>,
2135        cx: &mut VisualTestContext,
2136    ) -> Entity<Editor> {
2137        workspace
2138            .update_in(cx, |workspace, window, cx| {
2139                let pane = workspace.active_pane();
2140                pane.update(cx, |_, cx| {
2141                    Editor::deserialize(
2142                        project.clone(),
2143                        workspace.weak_handle(),
2144                        workspace_id,
2145                        item_id,
2146                        window,
2147                        cx,
2148                    )
2149                })
2150            })
2151            .await
2152            .unwrap()
2153    }
2154
2155    #[gpui::test]
2156    async fn test_deserialize(cx: &mut gpui::TestAppContext) {
2157        init_test(cx, |_| {});
2158
2159        let fs = FakeFs::new(cx.executor());
2160        fs.insert_file(path!("/file.rs"), Default::default()).await;
2161
2162        // Test case 1: Deserialize with path and contents
2163        {
2164            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2165            let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2166                MultiWorkspace::test_new(project.clone(), window, cx)
2167            });
2168            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2169            let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2170            let workspace_id = db.next_id().await.unwrap();
2171            let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2172            let item_id = 1234 as ItemId;
2173            let mtime = fs
2174                .metadata(Path::new(path!("/file.rs")))
2175                .await
2176                .unwrap()
2177                .unwrap()
2178                .mtime;
2179
2180            let serialized_editor = SerializedEditor {
2181                abs_path: Some(PathBuf::from(path!("/file.rs"))),
2182                contents: Some("fn main() {}".to_string()),
2183                language: Some("Rust".to_string()),
2184                mtime: Some(mtime),
2185            };
2186
2187            editor_db
2188                .save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
2189                .await
2190                .unwrap();
2191
2192            let deserialized =
2193                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2194
2195            deserialized.update(cx, |editor, cx| {
2196                assert_eq!(editor.text(cx), "fn main() {}");
2197                assert!(editor.is_dirty(cx));
2198                assert!(!editor.has_conflict(cx));
2199                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2200                assert!(buffer.file().is_some());
2201            });
2202        }
2203
2204        // Test case 2: Deserialize with only path
2205        {
2206            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2207            let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2208                MultiWorkspace::test_new(project.clone(), window, cx)
2209            });
2210            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2211            let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2212            let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2213
2214            let workspace_id = db.next_id().await.unwrap();
2215
2216            let item_id = 5678 as ItemId;
2217            let serialized_editor = SerializedEditor {
2218                abs_path: Some(PathBuf::from(path!("/file.rs"))),
2219                contents: None,
2220                language: None,
2221                mtime: None,
2222            };
2223
2224            editor_db
2225                .save_serialized_editor(item_id, workspace_id, serialized_editor)
2226                .await
2227                .unwrap();
2228
2229            let deserialized =
2230                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2231
2232            deserialized.update(cx, |editor, cx| {
2233                assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
2234                assert!(!editor.is_dirty(cx));
2235                assert!(!editor.has_conflict(cx));
2236
2237                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2238                assert!(buffer.file().is_some());
2239            });
2240        }
2241
2242        // Test case 3: Deserialize with no path (untitled buffer, with content and language)
2243        {
2244            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2245            // Add Rust to the language, so that we can restore the language of the buffer
2246            project.read_with(cx, |project, _| {
2247                project.languages().add(languages::rust_lang())
2248            });
2249
2250            let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2251                MultiWorkspace::test_new(project.clone(), window, cx)
2252            });
2253            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2254            let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2255            let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2256
2257            let workspace_id = db.next_id().await.unwrap();
2258
2259            let item_id = 9012 as ItemId;
2260            let serialized_editor = SerializedEditor {
2261                abs_path: None,
2262                contents: Some("hello".to_string()),
2263                language: Some("Rust".to_string()),
2264                mtime: None,
2265            };
2266
2267            editor_db
2268                .save_serialized_editor(item_id, workspace_id, serialized_editor)
2269                .await
2270                .unwrap();
2271
2272            let deserialized =
2273                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2274
2275            deserialized.update(cx, |editor, cx| {
2276                assert_eq!(editor.text(cx), "hello");
2277                assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
2278
2279                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2280                assert_eq!(
2281                    buffer.language().map(|lang| lang.name()),
2282                    Some("Rust".into())
2283                ); // Language should be set to Rust
2284                assert!(buffer.file().is_none()); // The buffer should not have an associated file
2285            });
2286        }
2287
2288        // Test case 4: Deserialize with path, content, and old mtime
2289        {
2290            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2291            let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2292                MultiWorkspace::test_new(project.clone(), window, cx)
2293            });
2294            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2295            let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2296            let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2297
2298            let workspace_id = db.next_id().await.unwrap();
2299
2300            let item_id = 9345 as ItemId;
2301            let old_mtime = MTime::from_seconds_and_nanos(0, 50);
2302            let serialized_editor = SerializedEditor {
2303                abs_path: Some(PathBuf::from(path!("/file.rs"))),
2304                contents: Some("fn main() {}".to_string()),
2305                language: Some("Rust".to_string()),
2306                mtime: Some(old_mtime),
2307            };
2308
2309            editor_db
2310                .save_serialized_editor(item_id, workspace_id, serialized_editor)
2311                .await
2312                .unwrap();
2313
2314            let deserialized =
2315                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2316
2317            deserialized.update(cx, |editor, cx| {
2318                assert_eq!(editor.text(cx), "fn main() {}");
2319                assert!(editor.has_conflict(cx)); // The editor should have a conflict
2320            });
2321        }
2322
2323        // Test case 5: Deserialize with no path, no content, no language, and no old mtime (new, empty, unsaved buffer)
2324        {
2325            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2326            let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2327                MultiWorkspace::test_new(project.clone(), window, cx)
2328            });
2329            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2330            let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2331            let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2332
2333            let workspace_id = db.next_id().await.unwrap();
2334
2335            let item_id = 10000 as ItemId;
2336            let serialized_editor = SerializedEditor {
2337                abs_path: None,
2338                contents: None,
2339                language: None,
2340                mtime: None,
2341            };
2342
2343            editor_db
2344                .save_serialized_editor(item_id, workspace_id, serialized_editor)
2345                .await
2346                .unwrap();
2347
2348            let deserialized =
2349                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2350
2351            deserialized.update(cx, |editor, cx| {
2352                assert_eq!(editor.text(cx), "");
2353                assert!(!editor.is_dirty(cx));
2354                assert!(!editor.has_conflict(cx));
2355
2356                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2357                assert!(buffer.file().is_none());
2358            });
2359        }
2360
2361        // Test case 6: Deserialize with path and contents in an empty workspace (no worktree)
2362        // This tests the hot-exit scenario where a file is opened in an empty workspace
2363        // and has unsaved changes that should be restored.
2364        {
2365            let fs = FakeFs::new(cx.executor());
2366            fs.insert_file(path!("/standalone.rs"), "original content".into())
2367                .await;
2368
2369            // Create an empty project with no worktrees
2370            let project = Project::test(fs.clone(), [], cx).await;
2371            let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2372                MultiWorkspace::test_new(project.clone(), window, cx)
2373            });
2374            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2375            let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2376            let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2377
2378            let workspace_id = db.next_id().await.unwrap();
2379            let item_id = 11000 as ItemId;
2380
2381            let mtime = fs
2382                .metadata(Path::new(path!("/standalone.rs")))
2383                .await
2384                .unwrap()
2385                .unwrap()
2386                .mtime;
2387
2388            // Simulate serialized state: file with unsaved changes
2389            let serialized_editor = SerializedEditor {
2390                abs_path: Some(PathBuf::from(path!("/standalone.rs"))),
2391                contents: Some("modified content".to_string()),
2392                language: Some("Rust".to_string()),
2393                mtime: Some(mtime),
2394            };
2395
2396            editor_db
2397                .save_serialized_editor(item_id, workspace_id, serialized_editor)
2398                .await
2399                .unwrap();
2400
2401            let deserialized =
2402                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2403
2404            deserialized.update(cx, |editor, cx| {
2405                // The editor should have the serialized contents, not the disk contents
2406                assert_eq!(editor.text(cx), "modified content");
2407                assert!(editor.is_dirty(cx));
2408                assert!(!editor.has_conflict(cx));
2409
2410                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2411                assert!(buffer.file().is_some());
2412            });
2413        }
2414    }
2415
2416    // Verify that renaming an open file emits EditorEvent::FileHandleChanged so that
2417    // the workspace re-serializes the editor with the updated path.
2418    #[gpui::test]
2419    async fn test_file_handle_changed_on_rename(cx: &mut gpui::TestAppContext) {
2420        use serde_json::json;
2421        use std::cell::RefCell;
2422        use std::rc::Rc;
2423        use util::rel_path::rel_path;
2424
2425        init_test(cx, |_| {});
2426
2427        let fs = FakeFs::new(cx.executor());
2428        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}" }))
2429            .await;
2430
2431        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
2432
2433        let buffer = project
2434            .update(cx, |project, cx| {
2435                project.open_local_buffer(path!("/root/file.rs"), cx)
2436            })
2437            .await
2438            .unwrap();
2439
2440        let received_file_handle_changed = Rc::new(RefCell::new(false));
2441        let (editor, cx) = cx.add_window_view({
2442            let project = project.clone();
2443            let received_file_handle_changed = received_file_handle_changed.clone();
2444            move |window, cx| {
2445                let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
2446                editor.set_should_serialize(true, cx);
2447                let entity = cx.entity();
2448                cx.subscribe_in(&entity, window, move |_, _, event: &EditorEvent, _, _| {
2449                    if matches!(event, EditorEvent::FileHandleChanged) {
2450                        *received_file_handle_changed.borrow_mut() = true;
2451                    }
2452                })
2453                .detach();
2454                editor
2455            }
2456        });
2457
2458        cx.run_until_parked();
2459
2460        let (entry_id, worktree_id) = project.update(cx, |project, cx| {
2461            let worktree = project.worktrees(cx).next().unwrap();
2462            let worktree = worktree.read(cx);
2463            let entry = worktree.entry_for_path(rel_path("file.rs")).unwrap();
2464            (entry.id, worktree.id())
2465        });
2466
2467        project
2468            .update(cx, |project, cx| {
2469                project.rename_entry(entry_id, (worktree_id, rel_path("renamed.rs")).into(), cx)
2470            })
2471            .await
2472            .unwrap();
2473
2474        cx.run_until_parked();
2475
2476        assert!(
2477            *received_file_handle_changed.borrow(),
2478            "EditorEvent::FileHandleChanged must be emitted when the open file is renamed"
2479        );
2480
2481        editor.update(cx, |editor, cx| {
2482            let buffer = editor.buffer().read(cx).as_singleton().unwrap();
2483            let path = buffer.read(cx).file().unwrap().path();
2484            assert!(
2485                path.as_std_path().ends_with("renamed.rs"),
2486                "buffer path must reflect the renamed file, got {path:?}"
2487            );
2488        });
2489    }
2490
2491    // Regression test for https://github.com/zed-industries/zed/issues/35947
2492    // Verifies that deserializing a non-worktree editor does not add the item
2493    // to any pane as a side effect.
2494    #[gpui::test]
2495    async fn test_deserialize_non_worktree_file_does_not_add_to_pane(
2496        cx: &mut gpui::TestAppContext,
2497    ) {
2498        init_test(cx, |_| {});
2499
2500        let fs = FakeFs::new(cx.executor());
2501        fs.insert_tree(path!("/outside"), json!({ "settings.json": "{}" }))
2502            .await;
2503
2504        // Project with a different root — settings.json is NOT in any worktree
2505        let project = Project::test(fs.clone(), [], cx).await;
2506        let (multi_workspace, cx) =
2507            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2508        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2509        let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2510        let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2511
2512        let workspace_id = db.next_id().await.unwrap();
2513        let item_id = 99999 as ItemId;
2514
2515        let serialized_editor = SerializedEditor {
2516            abs_path: Some(PathBuf::from(path!("/outside/settings.json"))),
2517            contents: None,
2518            language: None,
2519            mtime: None,
2520        };
2521
2522        editor_db
2523            .save_serialized_editor(item_id, workspace_id, serialized_editor)
2524            .await
2525            .unwrap();
2526
2527        // Count items in all panes before deserialization
2528        let pane_items_before = workspace.read_with(cx, |workspace, cx| {
2529            workspace
2530                .panes()
2531                .iter()
2532                .map(|pane| pane.read(cx).items_len())
2533                .sum::<usize>()
2534        });
2535
2536        let deserialized =
2537            deserialize_editor(item_id, workspace_id, workspace.clone(), project, cx).await;
2538
2539        cx.run_until_parked();
2540
2541        // The editor should exist and have the file
2542        deserialized.update(cx, |editor, cx| {
2543            let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2544            assert!(buffer.file().is_some());
2545        });
2546
2547        // No items should have been added to any pane as a side effect
2548        let pane_items_after = workspace.read_with(cx, |workspace, cx| {
2549            workspace
2550                .panes()
2551                .iter()
2552                .map(|pane| pane.read(cx).items_len())
2553                .sum::<usize>()
2554        });
2555
2556        assert_eq!(
2557            pane_items_before, pane_items_after,
2558            "Editor::deserialize should not add items to panes as a side effect"
2559        );
2560    }
2561}