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        self.buffer()
 649            .read(cx)
 650            .as_singleton()
 651            .and_then(|buffer| buffer.read(cx).file())
 652            .and_then(|file| File::from_dyn(Some(file)))
 653            .map(|file| {
 654                file.worktree
 655                    .read(cx)
 656                    .absolutize(&file.path)
 657                    .compact()
 658                    .to_string_lossy()
 659                    .into_owned()
 660                    .into()
 661            })
 662    }
 663
 664    fn telemetry_event_text(&self) -> Option<&'static str> {
 665        None
 666    }
 667
 668    fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
 669        if let Some(path) = path_for_buffer(&self.buffer, detail, true, cx) {
 670            path.to_string().into()
 671        } else {
 672            // Use the same logic as the displayed title for consistency
 673            self.buffer.read(cx).title(cx).to_string().into()
 674        }
 675    }
 676
 677    fn suggested_filename(&self, cx: &App) -> SharedString {
 678        self.buffer.read(cx).title(cx).to_string().into()
 679    }
 680
 681    fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
 682        ItemSettings::get_global(cx)
 683            .file_icons
 684            .then(|| {
 685                path_for_buffer(&self.buffer, 0, true, cx)
 686                    .and_then(|path| FileIcons::get_icon(Path::new(&*path), cx))
 687            })
 688            .flatten()
 689            .map(Icon::from_path)
 690    }
 691
 692    fn tab_content(&self, params: TabContentParams, _: &Window, cx: &App) -> AnyElement {
 693        let label_color = if ItemSettings::get_global(cx).git_status {
 694            self.buffer()
 695                .read(cx)
 696                .as_singleton()
 697                .and_then(|buffer| {
 698                    let buffer = buffer.read(cx);
 699                    let path = buffer.project_path(cx)?;
 700                    let buffer_id = buffer.remote_id();
 701                    let project = self.project()?.read(cx);
 702                    let entry = project.entry_for_path(&path, cx)?;
 703                    let (repo, repo_path) = project
 704                        .git_store()
 705                        .read(cx)
 706                        .repository_and_path_for_buffer_id(buffer_id, cx)?;
 707                    let status = repo.read(cx).status_for_path(&repo_path)?.status;
 708
 709                    Some(entry_git_aware_label_color(
 710                        status.summary(),
 711                        entry.is_ignored,
 712                        params.selected,
 713                    ))
 714                })
 715                .unwrap_or_else(|| entry_label_color(params.selected))
 716        } else {
 717            entry_label_color(params.selected)
 718        };
 719
 720        let description = params.detail.and_then(|detail| {
 721            let path = path_for_buffer(&self.buffer, detail, false, cx)?;
 722            let description = path.trim();
 723
 724            if description.is_empty() {
 725                return None;
 726            }
 727
 728            Some(util::truncate_and_trailoff(description, MAX_TAB_TITLE_LEN))
 729        });
 730
 731        // Whether the file was saved in the past but is now deleted.
 732        let was_deleted: bool = self
 733            .buffer()
 734            .read(cx)
 735            .as_singleton()
 736            .and_then(|buffer| buffer.read(cx).file())
 737            .is_some_and(|file| file.disk_state().is_deleted());
 738
 739        h_flex()
 740            .gap_2()
 741            .child(
 742                Label::new(util::truncate_and_trailoff(
 743                    &self.title(cx),
 744                    MAX_TAB_TITLE_LEN,
 745                ))
 746                .color(label_color)
 747                .when(params.preview, |this| this.italic())
 748                .when(was_deleted, |this| this.strikethrough()),
 749            )
 750            .when_some(description, |this, description| {
 751                this.child(
 752                    Label::new(description)
 753                        .size(LabelSize::XSmall)
 754                        .color(Color::Muted),
 755                )
 756            })
 757            .into_any_element()
 758    }
 759
 760    fn for_each_project_item(
 761        &self,
 762        cx: &App,
 763        f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 764    ) {
 765        self.buffer
 766            .read(cx)
 767            .for_each_buffer(&mut |buffer| f(buffer.entity_id(), buffer.read(cx)));
 768    }
 769
 770    fn buffer_kind(&self, cx: &App) -> ItemBufferKind {
 771        match self.buffer.read(cx).is_singleton() {
 772            true => ItemBufferKind::Singleton,
 773            false => ItemBufferKind::Multibuffer,
 774        }
 775    }
 776
 777    fn can_save_as(&self, cx: &App) -> bool {
 778        self.buffer.read(cx).is_singleton()
 779    }
 780
 781    fn can_split(&self) -> bool {
 782        true
 783    }
 784
 785    fn clone_on_split(
 786        &self,
 787        _workspace_id: Option<WorkspaceId>,
 788        window: &mut Window,
 789        cx: &mut Context<Self>,
 790    ) -> Task<Option<Entity<Editor>>>
 791    where
 792        Self: Sized,
 793    {
 794        Task::ready(Some(cx.new(|cx| self.clone(window, cx))))
 795    }
 796
 797    fn set_nav_history(
 798        &mut self,
 799        history: ItemNavHistory,
 800        _window: &mut Window,
 801        _: &mut Context<Self>,
 802    ) {
 803        self.nav_history = Some(history);
 804    }
 805
 806    fn on_removed(&self, cx: &mut Context<Self>) {
 807        self.report_editor_event(ReportEditorEvent::Closed, None, cx);
 808    }
 809
 810    fn deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 811        let selection = self.selections.newest_anchor();
 812        self.push_to_nav_history(selection.head(), None, true, false, cx);
 813    }
 814
 815    fn workspace_deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 816        self.hide_hovered_link(cx);
 817    }
 818
 819    fn is_dirty(&self, cx: &App) -> bool {
 820        self.buffer().read(cx).read(cx).is_dirty()
 821    }
 822
 823    fn capability(&self, cx: &App) -> Capability {
 824        self.capability(cx)
 825    }
 826
 827    // Note: this mirrors the logic in `Editor::toggle_read_only`, but is reachable
 828    // without relying on focus-based action dispatch.
 829    fn toggle_read_only(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 830        if let Some(buffer) = self.buffer.read(cx).as_singleton() {
 831            buffer.update(cx, |buffer, cx| {
 832                buffer.set_capability(
 833                    match buffer.capability() {
 834                        Capability::ReadWrite => Capability::Read,
 835                        Capability::Read => Capability::ReadWrite,
 836                        Capability::ReadOnly => Capability::ReadOnly,
 837                    },
 838                    cx,
 839                );
 840            });
 841        }
 842        cx.notify();
 843        window.refresh();
 844    }
 845
 846    fn has_deleted_file(&self, cx: &App) -> bool {
 847        self.buffer().read(cx).read(cx).has_deleted_file()
 848    }
 849
 850    fn has_conflict(&self, cx: &App) -> bool {
 851        self.buffer().read(cx).read(cx).has_conflict()
 852    }
 853
 854    fn can_save(&self, cx: &App) -> bool {
 855        let buffer = &self.buffer().read(cx);
 856        if let Some(buffer) = buffer.as_singleton() {
 857            buffer.read(cx).project_path(cx).is_some()
 858        } else {
 859            true
 860        }
 861    }
 862
 863    fn save(
 864        &mut self,
 865        options: SaveOptions,
 866        project: Entity<Project>,
 867        window: &mut Window,
 868        cx: &mut Context<Self>,
 869    ) -> Task<Result<()>> {
 870        // Add meta data tracking # of auto saves
 871        if options.autosave {
 872            self.report_editor_event(ReportEditorEvent::Saved { auto_saved: true }, None, cx);
 873        } else {
 874            self.report_editor_event(ReportEditorEvent::Saved { auto_saved: false }, None, cx);
 875        }
 876
 877        let buffers = self.buffer().clone().read(cx).all_buffers();
 878        let buffers = buffers
 879            .into_iter()
 880            .map(|handle| handle.read(cx).base_buffer().unwrap_or(handle.clone()))
 881            .collect::<HashSet<_>>();
 882
 883        let buffers_to_save = if self.buffer.read(cx).is_singleton() && !options.autosave {
 884            buffers
 885        } else {
 886            buffers
 887                .into_iter()
 888                .filter(|buffer| buffer.read(cx).is_dirty())
 889                .collect()
 890        };
 891
 892        let format_trigger = if options.force_format {
 893            FormatTrigger::Manual
 894        } else {
 895            FormatTrigger::Save
 896        };
 897
 898        cx.spawn_in(window, async move |this, cx| {
 899            if options.format {
 900                this.update_in(cx, |editor, window, cx| {
 901                    editor.perform_format(
 902                        project.clone(),
 903                        format_trigger,
 904                        FormatTarget::Buffers(buffers_to_save.clone()),
 905                        window,
 906                        cx,
 907                    )
 908                })?
 909                .await?;
 910            }
 911
 912            if !buffers_to_save.is_empty() {
 913                project
 914                    .update(cx, |project, cx| {
 915                        project.save_buffers(buffers_to_save.clone(), cx)
 916                    })
 917                    .await?;
 918            }
 919
 920            Ok(())
 921        })
 922    }
 923
 924    fn save_as(
 925        &mut self,
 926        project: Entity<Project>,
 927        path: ProjectPath,
 928        _: &mut Window,
 929        cx: &mut Context<Self>,
 930    ) -> Task<Result<()>> {
 931        let buffer = self
 932            .buffer()
 933            .read(cx)
 934            .as_singleton()
 935            .expect("cannot call save_as on an excerpt list");
 936
 937        let file_extension = path.path.extension().map(|a| a.to_string());
 938        self.report_editor_event(
 939            ReportEditorEvent::Saved { auto_saved: false },
 940            file_extension,
 941            cx,
 942        );
 943
 944        project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
 945    }
 946
 947    fn reload(
 948        &mut self,
 949        project: Entity<Project>,
 950        window: &mut Window,
 951        cx: &mut Context<Self>,
 952    ) -> Task<Result<()>> {
 953        let buffer = self.buffer().clone();
 954        let buffers = self.buffer.read(cx).all_buffers();
 955        let reload_buffers =
 956            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
 957        cx.spawn_in(window, async move |this, cx| {
 958            let transaction = reload_buffers.log_err().await;
 959            this.update(cx, |editor, cx| {
 960                editor.request_autoscroll(Autoscroll::fit(), cx)
 961            })?;
 962            buffer.update(cx, |buffer, cx| {
 963                if let Some(transaction) = transaction
 964                    && !buffer.is_singleton()
 965                {
 966                    buffer.push_transaction(&transaction.0, cx);
 967                }
 968            });
 969            Ok(())
 970        })
 971    }
 972
 973    fn as_searchable(
 974        &self,
 975        handle: &Entity<Self>,
 976        _: &App,
 977    ) -> Option<Box<dyn SearchableItemHandle>> {
 978        Some(Box::new(handle.clone()))
 979    }
 980
 981    fn pixel_position_of_cursor(&self, _: &App) -> Option<gpui::Point<Pixels>> {
 982        self.pixel_position_of_newest_cursor
 983    }
 984
 985    fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
 986        if self.show_breadcrumbs && self.buffer().read(cx).is_singleton() {
 987            ToolbarItemLocation::PrimaryLeft
 988        } else {
 989            ToolbarItemLocation::Hidden
 990        }
 991    }
 992
 993    // In a non-singleton case, the breadcrumbs are actually shown on sticky file headers of the multibuffer.
 994    fn breadcrumbs(&self, cx: &App) -> Option<(Vec<HighlightedText>, Option<Font>)> {
 995        if self.buffer.read(cx).is_singleton() {
 996            let font = theme_settings::ThemeSettings::get_global(cx)
 997                .buffer_font
 998                .clone();
 999            Some((self.breadcrumbs_inner(cx)?, Some(font)))
1000        } else {
1001            None
1002        }
1003    }
1004
1005    fn added_to_workspace(
1006        &mut self,
1007        workspace: &mut Workspace,
1008        window: &mut Window,
1009        cx: &mut Context<Self>,
1010    ) {
1011        self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
1012        if let Some(workspace_entity) = &workspace.weak_handle().upgrade() {
1013            cx.subscribe(
1014                workspace_entity,
1015                |editor, _, event: &workspace::Event, _cx| {
1016                    if let workspace::Event::ModalOpened = event {
1017                        editor.mouse_context_menu.take();
1018                        editor.inline_blame_popover.take();
1019                    }
1020                },
1021            )
1022            .detach();
1023        }
1024
1025        // Load persisted folds if this editor doesn't already have folds.
1026        // This handles manually-opened files (not workspace restoration).
1027        let display_snapshot = self
1028            .display_map
1029            .update(cx, |display_map, cx| display_map.snapshot(cx));
1030        let has_folds = display_snapshot
1031            .folds_in_range(MultiBufferOffset(0)..display_snapshot.buffer_snapshot().len())
1032            .next()
1033            .is_some();
1034
1035        if !has_folds {
1036            if let Some(workspace_id) = workspace.database_id()
1037                && let Some(file_path) = self.buffer().read(cx).as_singleton().and_then(|buffer| {
1038                    project::File::from_dyn(buffer.read(cx).file()).map(|file| file.abs_path(cx))
1039                })
1040            {
1041                self.load_folds_from_db(workspace_id, file_path, window, cx);
1042            }
1043        }
1044    }
1045
1046    fn pane_changed(&mut self, new_pane_id: EntityId, cx: &mut Context<Self>) {
1047        if self
1048            .highlighted_rows
1049            .get(&TypeId::of::<ActiveDebugLine>())
1050            .is_some_and(|lines| !lines.is_empty())
1051            && let Some(breakpoint_store) = self.breakpoint_store.as_ref()
1052        {
1053            breakpoint_store.update(cx, |store, _cx| {
1054                store.set_active_debug_pane_id(new_pane_id);
1055            });
1056        }
1057    }
1058
1059    fn to_item_events(event: &EditorEvent, f: &mut dyn FnMut(ItemEvent)) {
1060        match event {
1061            EditorEvent::Saved | EditorEvent::TitleChanged => {
1062                f(ItemEvent::UpdateTab);
1063                f(ItemEvent::UpdateBreadcrumbs);
1064            }
1065
1066            EditorEvent::Reparsed(_) => {
1067                f(ItemEvent::UpdateBreadcrumbs);
1068            }
1069
1070            EditorEvent::SelectionsChanged { local } if *local => {
1071                f(ItemEvent::UpdateBreadcrumbs);
1072            }
1073
1074            EditorEvent::BreadcrumbsChanged => {
1075                f(ItemEvent::UpdateBreadcrumbs);
1076            }
1077
1078            EditorEvent::DirtyChanged => {
1079                f(ItemEvent::UpdateTab);
1080            }
1081
1082            EditorEvent::BufferEdited => {
1083                f(ItemEvent::Edit);
1084                f(ItemEvent::UpdateBreadcrumbs);
1085            }
1086
1087            EditorEvent::BufferRangesUpdated { .. } | EditorEvent::BuffersRemoved { .. } => {
1088                f(ItemEvent::Edit);
1089            }
1090
1091            _ => {}
1092        }
1093    }
1094
1095    fn tab_extra_context_menu_actions(
1096        &self,
1097        _window: &mut Window,
1098        cx: &mut Context<Self>,
1099    ) -> Vec<(SharedString, Box<dyn gpui::Action>)> {
1100        let mut actions = Vec::new();
1101
1102        let is_markdown = self
1103            .buffer()
1104            .read(cx)
1105            .as_singleton()
1106            .and_then(|buffer| buffer.read(cx).language())
1107            .is_some_and(|language| language.name().as_ref() == "Markdown");
1108
1109        let is_svg = self
1110            .buffer()
1111            .read(cx)
1112            .as_singleton()
1113            .and_then(|buffer| buffer.read(cx).file())
1114            .is_some_and(|file| {
1115                std::path::Path::new(file.file_name(cx))
1116                    .extension()
1117                    .is_some_and(|ext| ext.eq_ignore_ascii_case("svg"))
1118            });
1119
1120        if is_markdown {
1121            actions.push((
1122                "Open Markdown Preview".into(),
1123                Box::new(OpenMarkdownPreview) as Box<dyn gpui::Action>,
1124            ));
1125        }
1126
1127        if is_svg {
1128            actions.push((
1129                "Open SVG Preview".into(),
1130                Box::new(OpenSvgPreview) as Box<dyn gpui::Action>,
1131            ));
1132        }
1133
1134        actions
1135    }
1136
1137    fn preserve_preview(&self, cx: &App) -> bool {
1138        self.buffer.read(cx).preserve_preview(cx)
1139    }
1140}
1141
1142impl SerializableItem for Editor {
1143    fn serialized_item_kind() -> &'static str {
1144        "Editor"
1145    }
1146
1147    fn cleanup(
1148        workspace_id: WorkspaceId,
1149        alive_items: Vec<ItemId>,
1150        _window: &mut Window,
1151        cx: &mut App,
1152    ) -> Task<Result<()>> {
1153        workspace::delete_unloaded_items(
1154            alive_items,
1155            workspace_id,
1156            "editors",
1157            &EditorDb::global(cx),
1158            cx,
1159        )
1160    }
1161
1162    fn deserialize(
1163        project: Entity<Project>,
1164        _workspace: WeakEntity<Workspace>,
1165        workspace_id: workspace::WorkspaceId,
1166        item_id: ItemId,
1167        window: &mut Window,
1168        cx: &mut App,
1169    ) -> Task<Result<Entity<Self>>> {
1170        let serialized_editor = match EditorDb::global(cx)
1171            .get_serialized_editor(item_id, workspace_id)
1172            .context("Failed to query editor state")
1173        {
1174            Ok(Some(serialized_editor)) => {
1175                if ProjectSettings::get_global(cx)
1176                    .session
1177                    .restore_unsaved_buffers
1178                {
1179                    serialized_editor
1180                } else {
1181                    SerializedEditor {
1182                        abs_path: serialized_editor.abs_path,
1183                        contents: None,
1184                        language: None,
1185                        mtime: None,
1186                    }
1187                }
1188            }
1189            Ok(None) => {
1190                return Task::ready(Err(anyhow!(
1191                    "Unable to deserialize editor: No entry in database for item_id: {item_id} and workspace_id {workspace_id:?}"
1192                )));
1193            }
1194            Err(error) => {
1195                return Task::ready(Err(error));
1196            }
1197        };
1198        log::debug!(
1199            "Deserialized editor {item_id:?} in workspace {workspace_id:?}, {serialized_editor:?}"
1200        );
1201
1202        match serialized_editor {
1203            SerializedEditor {
1204                abs_path: None,
1205                contents: Some(contents),
1206                language,
1207                ..
1208            } => window.spawn(cx, {
1209                let project = project.clone();
1210                async move |cx| {
1211                    let language_registry =
1212                        project.read_with(cx, |project, _| project.languages().clone());
1213
1214                    let language = if let Some(language_name) = language {
1215                        // We don't fail here, because we'd rather not set the language if the name changed
1216                        // than fail to restore the buffer.
1217                        language_registry
1218                            .language_for_name(&language_name)
1219                            .await
1220                            .ok()
1221                    } else {
1222                        None
1223                    };
1224
1225                    // First create the empty buffer
1226                    let buffer = project
1227                        .update(cx, |project, cx| project.create_buffer(language, true, cx))
1228                        .await
1229                        .context("Failed to create buffer while deserializing editor")?;
1230
1231                    // Then set the text so that the dirty bit is set correctly
1232                    buffer.update(cx, |buffer, cx| {
1233                        buffer.set_language_registry(language_registry);
1234                        buffer.set_text(contents, cx);
1235                        if let Some(entry) = buffer.peek_undo_stack() {
1236                            buffer.forget_transaction(entry.transaction_id());
1237                        }
1238                    });
1239
1240                    cx.update(|window, cx| {
1241                        cx.new(|cx| {
1242                            let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1243
1244                            editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1245                            editor
1246                        })
1247                    })
1248                }
1249            }),
1250            SerializedEditor {
1251                abs_path: Some(abs_path),
1252                contents,
1253                mtime,
1254                ..
1255            } => {
1256                let opened_buffer = project.update(cx, |project, cx| {
1257                    let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1258                    let project_path = ProjectPath {
1259                        worktree_id: worktree.read(cx).id(),
1260                        path: path,
1261                    };
1262                    Some(project.open_path(project_path, cx))
1263                });
1264
1265                match opened_buffer {
1266                    Some(opened_buffer) => window.spawn(cx, async move |cx| {
1267                        let (_, buffer) = opened_buffer
1268                            .await
1269                            .context("Failed to open path in project")?;
1270
1271                        if let Some(contents) = contents {
1272                            buffer.update(cx, |buffer, cx| {
1273                                restore_serialized_buffer_contents(buffer, contents, mtime, cx);
1274                            });
1275                        }
1276
1277                        cx.update(|window, cx| {
1278                            cx.new(|cx| {
1279                                let mut editor =
1280                                    Editor::for_buffer(buffer, Some(project), window, cx);
1281
1282                                editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1283                                editor
1284                            })
1285                        })
1286                    }),
1287                    None => {
1288                        // File is not in any worktree (e.g., opened as a standalone file).
1289                        // Open the buffer directly via the project rather than through
1290                        // workspace.open_abs_path(), which has the side effect of adding
1291                        // the item to a pane. The caller (deserialize_to) will add the
1292                        // returned item to the correct pane.
1293                        window.spawn(cx, async move |cx| {
1294                            let buffer = project
1295                                .update(cx, |project, cx| project.open_local_buffer(&abs_path, cx))
1296                                .await
1297                                .with_context(|| {
1298                                    format!("Failed to open buffer for {abs_path:?}")
1299                                })?;
1300
1301                            if let Some(contents) = contents {
1302                                buffer.update(cx, |buffer, cx| {
1303                                    restore_serialized_buffer_contents(buffer, contents, mtime, cx);
1304                                });
1305                            }
1306
1307                            cx.update(|window, cx| {
1308                                cx.new(|cx| {
1309                                    let mut editor =
1310                                        Editor::for_buffer(buffer, Some(project), window, cx);
1311                                    editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1312                                    editor
1313                                })
1314                            })
1315                        })
1316                    }
1317                }
1318            }
1319            SerializedEditor {
1320                abs_path: None,
1321                contents: None,
1322                ..
1323            } => window.spawn(cx, async move |cx| {
1324                let buffer = project
1325                    .update(cx, |project, cx| project.create_buffer(None, true, cx))
1326                    .await
1327                    .context("Failed to create buffer")?;
1328
1329                cx.update(|window, cx| {
1330                    cx.new(|cx| {
1331                        let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1332
1333                        editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1334                        editor
1335                    })
1336                })
1337            }),
1338        }
1339    }
1340
1341    fn serialize(
1342        &mut self,
1343        workspace: &mut Workspace,
1344        item_id: ItemId,
1345        closing: bool,
1346        window: &mut Window,
1347        cx: &mut Context<Self>,
1348    ) -> Option<Task<Result<()>>> {
1349        let buffer_serialization = self.buffer_serialization?;
1350        let project = self.project.clone()?;
1351
1352        let serialize_dirty_buffers = match buffer_serialization {
1353            // Always serialize dirty buffers, including for worktree-less windows.
1354            // This enables hot-exit functionality for empty windows and single files.
1355            BufferSerialization::All => true,
1356            BufferSerialization::NonDirtyBuffers => false,
1357        };
1358
1359        if closing && !serialize_dirty_buffers {
1360            return None;
1361        }
1362
1363        let workspace_id = workspace.database_id()?;
1364
1365        let buffer = self.buffer().read(cx).as_singleton()?;
1366
1367        let abs_path = buffer.read(cx).file().and_then(|file| {
1368            let worktree_id = file.worktree_id(cx);
1369            project
1370                .read(cx)
1371                .worktree_for_id(worktree_id, cx)
1372                .map(|worktree| worktree.read(cx).absolutize(file.path()))
1373                .or_else(|| {
1374                    let full_path = file.full_path(cx);
1375                    let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1376                    project.read(cx).absolute_path(&project_path, cx)
1377                })
1378        });
1379
1380        let is_dirty = buffer.read(cx).is_dirty();
1381        let mtime = buffer.read(cx).saved_mtime();
1382
1383        let snapshot = buffer.read(cx).snapshot();
1384
1385        let db = EditorDb::global(cx);
1386        Some(cx.spawn_in(window, async move |_this, cx| {
1387            cx.background_spawn(async move {
1388                let (contents, language) = if serialize_dirty_buffers && is_dirty {
1389                    let contents = snapshot.text();
1390                    let language = snapshot.language().map(|lang| lang.name().to_string());
1391                    (Some(contents), language)
1392                } else {
1393                    (None, None)
1394                };
1395
1396                let editor = SerializedEditor {
1397                    abs_path,
1398                    contents,
1399                    language,
1400                    mtime,
1401                };
1402                log::debug!("Serializing editor {item_id:?} in workspace {workspace_id:?}");
1403                db.save_serialized_editor(item_id, workspace_id, editor)
1404                    .await
1405                    .context("failed to save serialized editor")
1406            })
1407            .await
1408            .context("failed to save contents of buffer")?;
1409
1410            Ok(())
1411        }))
1412    }
1413
1414    fn should_serialize(&self, event: &Self::Event) -> bool {
1415        self.should_serialize_buffer()
1416            && matches!(
1417                event,
1418                EditorEvent::Saved
1419                    | EditorEvent::DirtyChanged
1420                    | EditorEvent::BufferEdited
1421                    | EditorEvent::FileHandleChanged
1422            )
1423    }
1424}
1425
1426#[derive(Debug, Default)]
1427struct EditorRestorationData {
1428    entries: HashMap<PathBuf, RestorationData>,
1429}
1430
1431#[derive(Default, Debug)]
1432pub struct RestorationData {
1433    pub scroll_position: (BufferRow, gpui::Point<ScrollOffset>),
1434    pub folds: Vec<Range<Point>>,
1435    pub selections: Vec<Range<Point>>,
1436}
1437
1438impl ProjectItem for Editor {
1439    type Item = Buffer;
1440
1441    fn project_item_kind() -> Option<ProjectItemKind> {
1442        Some(ProjectItemKind("Editor"))
1443    }
1444
1445    fn for_project_item(
1446        project: Entity<Project>,
1447        pane: Option<&Pane>,
1448        buffer: Entity<Buffer>,
1449        window: &mut Window,
1450        cx: &mut Context<Self>,
1451    ) -> Self {
1452        let mut editor = Self::for_buffer(buffer.clone(), Some(project), window, cx);
1453        let multibuffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1454
1455        if let Some(buffer_snapshot) = editor.buffer().read(cx).snapshot(cx).as_singleton()
1456            && WorkspaceSettings::get(None, cx).restore_on_file_reopen
1457            && let Some(restoration_data) = Self::project_item_kind()
1458                .and_then(|kind| pane.as_ref()?.project_item_restoration_data.get(&kind))
1459                .and_then(|data| data.downcast_ref::<EditorRestorationData>())
1460                .and_then(|data| {
1461                    let file = project::File::from_dyn(buffer.read(cx).file())?;
1462                    data.entries.get(&file.abs_path(cx))
1463                })
1464        {
1465            if !restoration_data.folds.is_empty() {
1466                editor.fold_ranges(
1467                    clip_ranges(&restoration_data.folds, buffer_snapshot),
1468                    false,
1469                    window,
1470                    cx,
1471                );
1472            }
1473            if !restoration_data.selections.is_empty() {
1474                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1475                    s.select_ranges(clip_ranges(&restoration_data.selections, buffer_snapshot));
1476                });
1477            }
1478            let (top_row, offset) = restoration_data.scroll_position;
1479            let anchor = multibuffer_snapshot.anchor_before(Point::new(top_row, 0));
1480            editor.set_scroll_anchor(ScrollAnchor { anchor, offset }, window, cx);
1481        }
1482
1483        editor
1484    }
1485
1486    fn for_broken_project_item(
1487        abs_path: &Path,
1488        is_local: bool,
1489        e: &anyhow::Error,
1490        window: &mut Window,
1491        cx: &mut App,
1492    ) -> Option<InvalidItemView> {
1493        Some(InvalidItemView::new(abs_path, is_local, e, window, cx))
1494    }
1495}
1496
1497fn clip_ranges<'a>(
1498    original: impl IntoIterator<Item = &'a Range<Point>> + 'a,
1499    snapshot: &'a BufferSnapshot,
1500) -> Vec<Range<Point>> {
1501    original
1502        .into_iter()
1503        .map(|range| {
1504            snapshot.clip_point(range.start, Bias::Left)
1505                ..snapshot.clip_point(range.end, Bias::Right)
1506        })
1507        .collect()
1508}
1509
1510impl EventEmitter<SearchEvent> for Editor {}
1511
1512impl Editor {
1513    pub fn update_restoration_data(
1514        &self,
1515        cx: &mut Context<Self>,
1516        write: impl for<'a> FnOnce(&'a mut RestorationData) + 'static,
1517    ) {
1518        if self.mode.is_minimap() || !WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1519            return;
1520        }
1521
1522        let editor = cx.entity();
1523        cx.defer(move |cx| {
1524            editor.update(cx, |editor, cx| {
1525                let kind = Editor::project_item_kind()?;
1526                let pane = editor.workspace()?.read(cx).pane_for(&cx.entity())?;
1527                let buffer = editor.buffer().read(cx).as_singleton()?;
1528                let file_abs_path = project::File::from_dyn(buffer.read(cx).file())?.abs_path(cx);
1529                pane.update(cx, |pane, _| {
1530                    let data = pane
1531                        .project_item_restoration_data
1532                        .entry(kind)
1533                        .or_insert_with(|| Box::new(EditorRestorationData::default()) as Box<_>);
1534                    let data = match data.downcast_mut::<EditorRestorationData>() {
1535                        Some(data) => data,
1536                        None => {
1537                            *data = Box::new(EditorRestorationData::default());
1538                            data.downcast_mut::<EditorRestorationData>()
1539                                .expect("just written the type downcasted to")
1540                        }
1541                    };
1542
1543                    let data = data.entries.entry(file_abs_path).or_default();
1544                    write(data);
1545                    Some(())
1546                })
1547            });
1548        });
1549    }
1550}
1551
1552impl SearchableItem for Editor {
1553    type Match = Range<Anchor>;
1554
1555    fn get_matches(&self, _window: &mut Window, _: &mut App) -> (Vec<Range<Anchor>>, SearchToken) {
1556        (
1557            self.background_highlights
1558                .get(&HighlightKey::BufferSearchHighlights)
1559                .map_or(Vec::new(), |(_color, ranges)| {
1560                    ranges.iter().cloned().collect()
1561                }),
1562            SearchToken::default(),
1563        )
1564    }
1565
1566    fn clear_matches(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1567        if self
1568            .clear_background_highlights(HighlightKey::BufferSearchHighlights, cx)
1569            .is_some()
1570        {
1571            cx.emit(SearchEvent::MatchesInvalidated);
1572        }
1573    }
1574
1575    fn update_matches(
1576        &mut self,
1577        matches: &[Range<Anchor>],
1578        active_match_index: Option<usize>,
1579        _token: SearchToken,
1580        _: &mut Window,
1581        cx: &mut Context<Self>,
1582    ) {
1583        let existing_range = self
1584            .background_highlights
1585            .get(&HighlightKey::BufferSearchHighlights)
1586            .map(|(_, range)| range.as_ref());
1587        let updated = existing_range != Some(matches);
1588        self.highlight_background(
1589            HighlightKey::BufferSearchHighlights,
1590            matches,
1591            move |index, theme| {
1592                if active_match_index == Some(*index) {
1593                    theme.colors().search_active_match_background
1594                } else {
1595                    theme.colors().search_match_background
1596                }
1597            },
1598            cx,
1599        );
1600        if updated {
1601            cx.emit(SearchEvent::MatchesInvalidated);
1602        }
1603    }
1604
1605    fn has_filtered_search_ranges(&mut self) -> bool {
1606        self.has_background_highlights(HighlightKey::SearchWithinRange)
1607    }
1608
1609    fn toggle_filtered_search_ranges(
1610        &mut self,
1611        enabled: Option<FilteredSearchRange>,
1612        _: &mut Window,
1613        cx: &mut Context<Self>,
1614    ) {
1615        if self.has_filtered_search_ranges() {
1616            self.previous_search_ranges = self
1617                .clear_background_highlights(HighlightKey::SearchWithinRange, cx)
1618                .map(|(_, ranges)| ranges)
1619        }
1620
1621        if let Some(range) = enabled {
1622            let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1623
1624            if ranges.iter().any(|s| s.start != s.end) {
1625                self.set_search_within_ranges(&ranges, cx);
1626            } else if let Some(previous_search_ranges) = self.previous_search_ranges.take()
1627                && range != FilteredSearchRange::Selection
1628            {
1629                self.set_search_within_ranges(&previous_search_ranges, cx);
1630            }
1631        }
1632    }
1633
1634    fn supported_options(&self) -> SearchOptions {
1635        if self.in_project_search {
1636            SearchOptions {
1637                case: true,
1638                word: true,
1639                regex: true,
1640                replacement: false,
1641                selection: false,
1642                select_all: true,
1643                find_in_results: true,
1644            }
1645        } else {
1646            SearchOptions {
1647                case: true,
1648                word: true,
1649                regex: true,
1650                replacement: true,
1651                selection: true,
1652                select_all: true,
1653                find_in_results: false,
1654            }
1655        }
1656    }
1657
1658    fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
1659        let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1660        let snapshot = self.snapshot(window, cx);
1661        let selection = self.selections.newest_adjusted(&snapshot.display_snapshot);
1662        let buffer_snapshot = snapshot.buffer_snapshot();
1663
1664        match setting {
1665            SeedQuerySetting::Never => String::new(),
1666            SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1667                buffer_snapshot
1668                    .text_for_range(selection.start..selection.end)
1669                    .collect()
1670            }
1671            SeedQuerySetting::Selection => String::new(),
1672            SeedQuerySetting::Always => {
1673                let (range, kind) = buffer_snapshot
1674                    .surrounding_word(selection.start, Some(CharScopeContext::Completion));
1675                if kind == Some(CharKind::Word) {
1676                    let text: String = buffer_snapshot.text_for_range(range).collect();
1677                    if !text.trim().is_empty() {
1678                        return text;
1679                    }
1680                }
1681                String::new()
1682            }
1683        }
1684    }
1685
1686    fn activate_match(
1687        &mut self,
1688        index: usize,
1689        matches: &[Range<Anchor>],
1690        _token: SearchToken,
1691        window: &mut Window,
1692        cx: &mut Context<Self>,
1693    ) {
1694        self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1695        let range = self.range_for_match(&matches[index]);
1696        let autoscroll = if EditorSettings::get_global(cx).search.center_on_match {
1697            Autoscroll::center()
1698        } else {
1699            Autoscroll::fit()
1700        };
1701        self.change_selections(
1702            SelectionEffects::scroll(autoscroll).from_search(true),
1703            window,
1704            cx,
1705            |s| {
1706                s.select_ranges([range]);
1707            },
1708        )
1709    }
1710
1711    fn select_matches(
1712        &mut self,
1713        matches: &[Self::Match],
1714        _token: SearchToken,
1715        window: &mut Window,
1716        cx: &mut Context<Self>,
1717    ) {
1718        self.unfold_ranges(matches, false, false, cx);
1719        self.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
1720            s.select_ranges(matches.iter().cloned())
1721        });
1722    }
1723    fn replace(
1724        &mut self,
1725        identifier: &Self::Match,
1726        query: &SearchQuery,
1727        _token: SearchToken,
1728        window: &mut Window,
1729        cx: &mut Context<Self>,
1730    ) {
1731        let text = self.buffer.read(cx);
1732        let text = text.snapshot(cx);
1733        let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1734        let text: Cow<_> = if text.len() == 1 {
1735            text.first().cloned().unwrap().into()
1736        } else {
1737            let joined_chunks = text.join("");
1738            joined_chunks.into()
1739        };
1740
1741        if let Some(replacement) = query.replacement_for(&text) {
1742            self.transact(window, cx, |this, _, cx| {
1743                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1744            });
1745        }
1746    }
1747    fn replace_all(
1748        &mut self,
1749        matches: &mut dyn Iterator<Item = &Self::Match>,
1750        query: &SearchQuery,
1751        _token: SearchToken,
1752        window: &mut Window,
1753        cx: &mut Context<Self>,
1754    ) {
1755        let text = self.buffer.read(cx);
1756        let text = text.snapshot(cx);
1757        let mut edits = vec![];
1758
1759        // A regex might have replacement variables so we cannot apply
1760        // the same replacement to all matches
1761        if query.is_regex() {
1762            edits = matches
1763                .filter_map(|m| {
1764                    let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1765
1766                    let text: Cow<_> = if text.len() == 1 {
1767                        text.first().cloned().unwrap().into()
1768                    } else {
1769                        let joined_chunks = text.join("");
1770                        joined_chunks.into()
1771                    };
1772
1773                    query
1774                        .replacement_for(&text)
1775                        .map(|replacement| (m.clone(), Arc::from(&*replacement)))
1776                })
1777                .collect();
1778        } else if let Some(replacement) = query.replacement().map(Arc::<str>::from) {
1779            edits = matches.map(|m| (m.clone(), replacement.clone())).collect();
1780        }
1781
1782        if !edits.is_empty() {
1783            self.transact(window, cx, |this, _, cx| {
1784                this.edit(edits, cx);
1785            });
1786        }
1787    }
1788    fn match_index_for_direction(
1789        &mut self,
1790        matches: &[Range<Anchor>],
1791        current_index: usize,
1792        direction: Direction,
1793        count: usize,
1794        _token: SearchToken,
1795        _: &mut Window,
1796        cx: &mut Context<Self>,
1797    ) -> usize {
1798        let buffer = self.buffer().read(cx).snapshot(cx);
1799        let current_index_position = if self.selections.disjoint_anchors_arc().len() == 1 {
1800            self.selections.newest_anchor().head()
1801        } else {
1802            matches[current_index].start
1803        };
1804
1805        let mut count = count % matches.len();
1806        if count == 0 {
1807            return current_index;
1808        }
1809        match direction {
1810            Direction::Next => {
1811                if matches[current_index]
1812                    .start
1813                    .cmp(&current_index_position, &buffer)
1814                    .is_gt()
1815                {
1816                    count -= 1
1817                }
1818
1819                (current_index + count) % matches.len()
1820            }
1821            Direction::Prev => {
1822                if matches[current_index]
1823                    .end
1824                    .cmp(&current_index_position, &buffer)
1825                    .is_lt()
1826                {
1827                    count -= 1;
1828                }
1829
1830                if current_index >= count {
1831                    current_index - count
1832                } else {
1833                    matches.len() - (count - current_index)
1834                }
1835            }
1836        }
1837    }
1838
1839    fn find_matches(
1840        &mut self,
1841        query: Arc<project::search::SearchQuery>,
1842        _: &mut Window,
1843        cx: &mut Context<Self>,
1844    ) -> Task<Vec<Range<Anchor>>> {
1845        let buffer = self.buffer().read(cx).snapshot(cx);
1846        let search_within_ranges = self
1847            .background_highlights
1848            .get(&HighlightKey::SearchWithinRange)
1849            .map_or(vec![], |(_color, ranges)| {
1850                ranges.iter().cloned().collect::<Vec<_>>()
1851            });
1852
1853        cx.background_spawn(async move {
1854            let mut ranges = Vec::new();
1855
1856            let search_within_ranges = if search_within_ranges.is_empty() {
1857                vec![buffer.anchor_before(MultiBufferOffset(0))..buffer.anchor_after(buffer.len())]
1858            } else {
1859                search_within_ranges
1860            };
1861
1862            for range in search_within_ranges {
1863                for (search_buffer, search_range, deleted_hunk_anchor) in
1864                    buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1865                {
1866                    ranges.extend(
1867                        query
1868                            .search(
1869                                search_buffer,
1870                                Some(search_range.start.0..search_range.end.0),
1871                            )
1872                            .await
1873                            .into_iter()
1874                            .filter_map(|match_range| {
1875                                if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
1876                                    let start = search_buffer
1877                                        .anchor_after(search_range.start + match_range.start);
1878                                    let end = search_buffer
1879                                        .anchor_before(search_range.start + match_range.end);
1880                                    Some(
1881                                        deleted_hunk_anchor.with_diff_base_anchor(start)
1882                                            ..deleted_hunk_anchor.with_diff_base_anchor(end),
1883                                    )
1884                                } else {
1885                                    let start = search_buffer
1886                                        .anchor_after(search_range.start + match_range.start);
1887                                    let end = search_buffer
1888                                        .anchor_before(search_range.start + match_range.end);
1889                                    buffer.buffer_anchor_range_to_anchor_range(start..end)
1890                                }
1891                            }),
1892                    );
1893                }
1894            }
1895
1896            ranges
1897        })
1898    }
1899
1900    fn active_match_index(
1901        &mut self,
1902        direction: Direction,
1903        matches: &[Range<Anchor>],
1904        _token: SearchToken,
1905        _: &mut Window,
1906        cx: &mut Context<Self>,
1907    ) -> Option<usize> {
1908        active_match_index(
1909            direction,
1910            matches,
1911            &self.selections.newest_anchor().head(),
1912            &self.buffer().read(cx).snapshot(cx),
1913        )
1914    }
1915
1916    fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
1917        self.expect_bounds_change = self.last_bounds;
1918    }
1919
1920    fn set_search_is_case_sensitive(
1921        &mut self,
1922        case_sensitive: Option<bool>,
1923        _cx: &mut Context<Self>,
1924    ) {
1925        self.select_next_is_case_sensitive = case_sensitive;
1926    }
1927}
1928
1929pub fn active_match_index(
1930    direction: Direction,
1931    ranges: &[Range<Anchor>],
1932    cursor: &Anchor,
1933    buffer: &MultiBufferSnapshot,
1934) -> Option<usize> {
1935    if ranges.is_empty() {
1936        None
1937    } else {
1938        let r = ranges.binary_search_by(|probe| {
1939            if probe.end.cmp(cursor, buffer).is_lt() {
1940                Ordering::Less
1941            } else if probe.start.cmp(cursor, buffer).is_gt() {
1942                Ordering::Greater
1943            } else {
1944                Ordering::Equal
1945            }
1946        });
1947        match direction {
1948            Direction::Prev => match r {
1949                Ok(i) => Some(i),
1950                Err(i) => Some(i.saturating_sub(1)),
1951            },
1952            Direction::Next => match r {
1953                Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1954            },
1955        }
1956    }
1957}
1958
1959pub fn entry_label_color(selected: bool) -> Color {
1960    if selected {
1961        Color::Default
1962    } else {
1963        Color::Muted
1964    }
1965}
1966
1967pub fn entry_diagnostic_aware_icon_name_and_color(
1968    diagnostic_severity: Option<DiagnosticSeverity>,
1969) -> Option<(IconName, Color)> {
1970    match diagnostic_severity {
1971        Some(DiagnosticSeverity::ERROR) => Some((IconName::Close, Color::Error)),
1972        Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1973        _ => None,
1974    }
1975}
1976
1977pub fn entry_diagnostic_aware_icon_decoration_and_color(
1978    diagnostic_severity: Option<DiagnosticSeverity>,
1979) -> Option<(IconDecorationKind, Color)> {
1980    match diagnostic_severity {
1981        Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1982        Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1983        _ => None,
1984    }
1985}
1986
1987pub fn entry_git_aware_label_color(git_status: GitSummary, ignored: bool, selected: bool) -> Color {
1988    let tracked = git_status.index + git_status.worktree;
1989    if git_status.conflict > 0 {
1990        Color::Conflict
1991    } else if tracked.deleted > 0 {
1992        Color::Deleted
1993    } else if tracked.modified > 0 {
1994        Color::Modified
1995    } else if tracked.added > 0 || git_status.untracked > 0 {
1996        Color::Created
1997    } else if ignored {
1998        Color::Ignored
1999    } else {
2000        entry_label_color(selected)
2001    }
2002}
2003
2004fn path_for_buffer<'a>(
2005    buffer: &Entity<MultiBuffer>,
2006    height: usize,
2007    include_filename: bool,
2008    cx: &'a App,
2009) -> Option<Cow<'a, str>> {
2010    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
2011    path_for_file(file, height, include_filename, cx)
2012}
2013
2014fn path_for_file<'a>(
2015    file: &'a Arc<dyn language::File>,
2016    mut height: usize,
2017    include_filename: bool,
2018    cx: &'a App,
2019) -> Option<Cow<'a, str>> {
2020    if project::File::from_dyn(Some(file)).is_none() {
2021        return None;
2022    }
2023
2024    let file = file.as_ref();
2025    // Ensure we always render at least the filename.
2026    height += 1;
2027
2028    let mut prefix = file.path().as_ref();
2029    while height > 0 {
2030        if let Some(parent) = prefix.parent() {
2031            prefix = parent;
2032            height -= 1;
2033        } else {
2034            break;
2035        }
2036    }
2037
2038    // The full_path method allocates, so avoid calling it if height is zero.
2039    if height > 0 {
2040        let mut full_path = file.full_path(cx);
2041        if !include_filename {
2042            if !full_path.pop() {
2043                return None;
2044            }
2045        }
2046        Some(full_path.to_string_lossy().into_owned().into())
2047    } else {
2048        let mut path = file.path().strip_prefix(prefix).ok()?;
2049        if !include_filename {
2050            path = path.parent()?;
2051        }
2052        Some(path.display(file.path_style(cx)))
2053    }
2054}
2055
2056/// Restores serialized buffer contents by overwriting the buffer with saved text.
2057/// This is somewhat wasteful since we load the whole buffer from disk then overwrite it,
2058/// but keeps implementation simple as we don't need to persist all metadata from loading
2059/// (git diff base, etc.).
2060fn restore_serialized_buffer_contents(
2061    buffer: &mut Buffer,
2062    contents: String,
2063    mtime: Option<MTime>,
2064    cx: &mut Context<Buffer>,
2065) {
2066    // If we did restore an mtime, store it on the buffer so that
2067    // the next edit will mark the buffer as dirty/conflicted.
2068    if mtime.is_some() {
2069        buffer.did_reload(buffer.version(), buffer.line_ending(), mtime, cx);
2070    }
2071    buffer.set_text(contents, cx);
2072    if let Some(entry) = buffer.peek_undo_stack() {
2073        buffer.forget_transaction(entry.transaction_id());
2074    }
2075}
2076
2077fn serialize_path_key(path_key: &PathKey) -> proto::PathKey {
2078    proto::PathKey {
2079        sort_prefix: path_key.sort_prefix,
2080        path: path_key.path.to_proto(),
2081    }
2082}
2083
2084fn deserialize_path_key(path_key: proto::PathKey) -> Option<PathKey> {
2085    Some(PathKey {
2086        sort_prefix: path_key.sort_prefix,
2087        path: RelPath::from_proto(&path_key.path).ok()?,
2088    })
2089}
2090
2091#[cfg(test)]
2092mod tests {
2093    use crate::editor_tests::init_test;
2094    use fs::Fs;
2095    use workspace::MultiWorkspace;
2096
2097    use super::*;
2098    use fs::MTime;
2099    use gpui::{App, VisualTestContext};
2100    use language::TestFile;
2101    use project::FakeFs;
2102    use serde_json::json;
2103    use std::path::{Path, PathBuf};
2104    use util::{path, rel_path::RelPath};
2105
2106    #[gpui::test]
2107    fn test_path_for_file(cx: &mut App) {
2108        let file: Arc<dyn language::File> = Arc::new(TestFile {
2109            path: RelPath::empty().into(),
2110            root_name: String::new(),
2111            local_root: None,
2112        });
2113        assert_eq!(path_for_file(&file, 0, false, cx), None);
2114    }
2115
2116    async fn deserialize_editor(
2117        item_id: ItemId,
2118        workspace_id: WorkspaceId,
2119        workspace: Entity<Workspace>,
2120        project: Entity<Project>,
2121        cx: &mut VisualTestContext,
2122    ) -> Entity<Editor> {
2123        workspace
2124            .update_in(cx, |workspace, window, cx| {
2125                let pane = workspace.active_pane();
2126                pane.update(cx, |_, cx| {
2127                    Editor::deserialize(
2128                        project.clone(),
2129                        workspace.weak_handle(),
2130                        workspace_id,
2131                        item_id,
2132                        window,
2133                        cx,
2134                    )
2135                })
2136            })
2137            .await
2138            .unwrap()
2139    }
2140
2141    #[gpui::test]
2142    async fn test_deserialize(cx: &mut gpui::TestAppContext) {
2143        init_test(cx, |_| {});
2144
2145        let fs = FakeFs::new(cx.executor());
2146        fs.insert_file(path!("/file.rs"), Default::default()).await;
2147
2148        // Test case 1: Deserialize with path and contents
2149        {
2150            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2151            let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2152                MultiWorkspace::test_new(project.clone(), window, cx)
2153            });
2154            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2155            let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2156            let workspace_id = db.next_id().await.unwrap();
2157            let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2158            let item_id = 1234 as ItemId;
2159            let mtime = fs
2160                .metadata(Path::new(path!("/file.rs")))
2161                .await
2162                .unwrap()
2163                .unwrap()
2164                .mtime;
2165
2166            let serialized_editor = SerializedEditor {
2167                abs_path: Some(PathBuf::from(path!("/file.rs"))),
2168                contents: Some("fn main() {}".to_string()),
2169                language: Some("Rust".to_string()),
2170                mtime: Some(mtime),
2171            };
2172
2173            editor_db
2174                .save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
2175                .await
2176                .unwrap();
2177
2178            let deserialized =
2179                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2180
2181            deserialized.update(cx, |editor, cx| {
2182                assert_eq!(editor.text(cx), "fn main() {}");
2183                assert!(editor.is_dirty(cx));
2184                assert!(!editor.has_conflict(cx));
2185                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2186                assert!(buffer.file().is_some());
2187            });
2188        }
2189
2190        // Test case 2: Deserialize with only path
2191        {
2192            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2193            let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2194                MultiWorkspace::test_new(project.clone(), window, cx)
2195            });
2196            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2197            let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2198            let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2199
2200            let workspace_id = db.next_id().await.unwrap();
2201
2202            let item_id = 5678 as ItemId;
2203            let serialized_editor = SerializedEditor {
2204                abs_path: Some(PathBuf::from(path!("/file.rs"))),
2205                contents: None,
2206                language: None,
2207                mtime: None,
2208            };
2209
2210            editor_db
2211                .save_serialized_editor(item_id, workspace_id, serialized_editor)
2212                .await
2213                .unwrap();
2214
2215            let deserialized =
2216                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2217
2218            deserialized.update(cx, |editor, cx| {
2219                assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
2220                assert!(!editor.is_dirty(cx));
2221                assert!(!editor.has_conflict(cx));
2222
2223                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2224                assert!(buffer.file().is_some());
2225            });
2226        }
2227
2228        // Test case 3: Deserialize with no path (untitled buffer, with content and language)
2229        {
2230            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2231            // Add Rust to the language, so that we can restore the language of the buffer
2232            project.read_with(cx, |project, _| {
2233                project.languages().add(languages::rust_lang())
2234            });
2235
2236            let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2237                MultiWorkspace::test_new(project.clone(), window, cx)
2238            });
2239            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2240            let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2241            let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2242
2243            let workspace_id = db.next_id().await.unwrap();
2244
2245            let item_id = 9012 as ItemId;
2246            let serialized_editor = SerializedEditor {
2247                abs_path: None,
2248                contents: Some("hello".to_string()),
2249                language: Some("Rust".to_string()),
2250                mtime: None,
2251            };
2252
2253            editor_db
2254                .save_serialized_editor(item_id, workspace_id, serialized_editor)
2255                .await
2256                .unwrap();
2257
2258            let deserialized =
2259                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2260
2261            deserialized.update(cx, |editor, cx| {
2262                assert_eq!(editor.text(cx), "hello");
2263                assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
2264
2265                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2266                assert_eq!(
2267                    buffer.language().map(|lang| lang.name()),
2268                    Some("Rust".into())
2269                ); // Language should be set to Rust
2270                assert!(buffer.file().is_none()); // The buffer should not have an associated file
2271            });
2272        }
2273
2274        // Test case 4: Deserialize with path, content, and old mtime
2275        {
2276            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2277            let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2278                MultiWorkspace::test_new(project.clone(), window, cx)
2279            });
2280            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2281            let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2282            let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2283
2284            let workspace_id = db.next_id().await.unwrap();
2285
2286            let item_id = 9345 as ItemId;
2287            let old_mtime = MTime::from_seconds_and_nanos(0, 50);
2288            let serialized_editor = SerializedEditor {
2289                abs_path: Some(PathBuf::from(path!("/file.rs"))),
2290                contents: Some("fn main() {}".to_string()),
2291                language: Some("Rust".to_string()),
2292                mtime: Some(old_mtime),
2293            };
2294
2295            editor_db
2296                .save_serialized_editor(item_id, workspace_id, serialized_editor)
2297                .await
2298                .unwrap();
2299
2300            let deserialized =
2301                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2302
2303            deserialized.update(cx, |editor, cx| {
2304                assert_eq!(editor.text(cx), "fn main() {}");
2305                assert!(editor.has_conflict(cx)); // The editor should have a conflict
2306            });
2307        }
2308
2309        // Test case 5: Deserialize with no path, no content, no language, and no old mtime (new, empty, unsaved buffer)
2310        {
2311            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2312            let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2313                MultiWorkspace::test_new(project.clone(), window, cx)
2314            });
2315            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2316            let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2317            let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2318
2319            let workspace_id = db.next_id().await.unwrap();
2320
2321            let item_id = 10000 as ItemId;
2322            let serialized_editor = SerializedEditor {
2323                abs_path: None,
2324                contents: None,
2325                language: None,
2326                mtime: None,
2327            };
2328
2329            editor_db
2330                .save_serialized_editor(item_id, workspace_id, serialized_editor)
2331                .await
2332                .unwrap();
2333
2334            let deserialized =
2335                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2336
2337            deserialized.update(cx, |editor, cx| {
2338                assert_eq!(editor.text(cx), "");
2339                assert!(!editor.is_dirty(cx));
2340                assert!(!editor.has_conflict(cx));
2341
2342                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2343                assert!(buffer.file().is_none());
2344            });
2345        }
2346
2347        // Test case 6: Deserialize with path and contents in an empty workspace (no worktree)
2348        // This tests the hot-exit scenario where a file is opened in an empty workspace
2349        // and has unsaved changes that should be restored.
2350        {
2351            let fs = FakeFs::new(cx.executor());
2352            fs.insert_file(path!("/standalone.rs"), "original content".into())
2353                .await;
2354
2355            // Create an empty project with no worktrees
2356            let project = Project::test(fs.clone(), [], cx).await;
2357            let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
2358                MultiWorkspace::test_new(project.clone(), window, cx)
2359            });
2360            let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2361            let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2362            let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2363
2364            let workspace_id = db.next_id().await.unwrap();
2365            let item_id = 11000 as ItemId;
2366
2367            let mtime = fs
2368                .metadata(Path::new(path!("/standalone.rs")))
2369                .await
2370                .unwrap()
2371                .unwrap()
2372                .mtime;
2373
2374            // Simulate serialized state: file with unsaved changes
2375            let serialized_editor = SerializedEditor {
2376                abs_path: Some(PathBuf::from(path!("/standalone.rs"))),
2377                contents: Some("modified content".to_string()),
2378                language: Some("Rust".to_string()),
2379                mtime: Some(mtime),
2380            };
2381
2382            editor_db
2383                .save_serialized_editor(item_id, workspace_id, serialized_editor)
2384                .await
2385                .unwrap();
2386
2387            let deserialized =
2388                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2389
2390            deserialized.update(cx, |editor, cx| {
2391                // The editor should have the serialized contents, not the disk contents
2392                assert_eq!(editor.text(cx), "modified content");
2393                assert!(editor.is_dirty(cx));
2394                assert!(!editor.has_conflict(cx));
2395
2396                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2397                assert!(buffer.file().is_some());
2398            });
2399        }
2400    }
2401
2402    // Verify that renaming an open file emits EditorEvent::FileHandleChanged so that
2403    // the workspace re-serializes the editor with the updated path.
2404    #[gpui::test]
2405    async fn test_file_handle_changed_on_rename(cx: &mut gpui::TestAppContext) {
2406        use serde_json::json;
2407        use std::cell::RefCell;
2408        use std::rc::Rc;
2409        use util::rel_path::rel_path;
2410
2411        init_test(cx, |_| {});
2412
2413        let fs = FakeFs::new(cx.executor());
2414        fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}" }))
2415            .await;
2416
2417        let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
2418
2419        let buffer = project
2420            .update(cx, |project, cx| {
2421                project.open_local_buffer(path!("/root/file.rs"), cx)
2422            })
2423            .await
2424            .unwrap();
2425
2426        let received_file_handle_changed = Rc::new(RefCell::new(false));
2427        let (editor, cx) = cx.add_window_view({
2428            let project = project.clone();
2429            let received_file_handle_changed = received_file_handle_changed.clone();
2430            move |window, cx| {
2431                let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
2432                editor.set_should_serialize(true, cx);
2433                let entity = cx.entity();
2434                cx.subscribe_in(&entity, window, move |_, _, event: &EditorEvent, _, _| {
2435                    if matches!(event, EditorEvent::FileHandleChanged) {
2436                        *received_file_handle_changed.borrow_mut() = true;
2437                    }
2438                })
2439                .detach();
2440                editor
2441            }
2442        });
2443
2444        cx.run_until_parked();
2445
2446        let (entry_id, worktree_id) = project.update(cx, |project, cx| {
2447            let worktree = project.worktrees(cx).next().unwrap();
2448            let worktree = worktree.read(cx);
2449            let entry = worktree.entry_for_path(rel_path("file.rs")).unwrap();
2450            (entry.id, worktree.id())
2451        });
2452
2453        project
2454            .update(cx, |project, cx| {
2455                project.rename_entry(entry_id, (worktree_id, rel_path("renamed.rs")).into(), cx)
2456            })
2457            .await
2458            .unwrap();
2459
2460        cx.run_until_parked();
2461
2462        assert!(
2463            *received_file_handle_changed.borrow(),
2464            "EditorEvent::FileHandleChanged must be emitted when the open file is renamed"
2465        );
2466
2467        editor.update(cx, |editor, cx| {
2468            let buffer = editor.buffer().read(cx).as_singleton().unwrap();
2469            let path = buffer.read(cx).file().unwrap().path();
2470            assert!(
2471                path.as_std_path().ends_with("renamed.rs"),
2472                "buffer path must reflect the renamed file, got {path:?}"
2473            );
2474        });
2475    }
2476
2477    // Regression test for https://github.com/zed-industries/zed/issues/35947
2478    // Verifies that deserializing a non-worktree editor does not add the item
2479    // to any pane as a side effect.
2480    #[gpui::test]
2481    async fn test_deserialize_non_worktree_file_does_not_add_to_pane(
2482        cx: &mut gpui::TestAppContext,
2483    ) {
2484        init_test(cx, |_| {});
2485
2486        let fs = FakeFs::new(cx.executor());
2487        fs.insert_tree(path!("/outside"), json!({ "settings.json": "{}" }))
2488            .await;
2489
2490        // Project with a different root — settings.json is NOT in any worktree
2491        let project = Project::test(fs.clone(), [], cx).await;
2492        let (multi_workspace, cx) =
2493            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
2494        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
2495        let db = cx.update(|_, cx| workspace::WorkspaceDb::global(cx));
2496        let editor_db = cx.update(|_, cx| EditorDb::global(cx));
2497
2498        let workspace_id = db.next_id().await.unwrap();
2499        let item_id = 99999 as ItemId;
2500
2501        let serialized_editor = SerializedEditor {
2502            abs_path: Some(PathBuf::from(path!("/outside/settings.json"))),
2503            contents: None,
2504            language: None,
2505            mtime: None,
2506        };
2507
2508        editor_db
2509            .save_serialized_editor(item_id, workspace_id, serialized_editor)
2510            .await
2511            .unwrap();
2512
2513        // Count items in all panes before deserialization
2514        let pane_items_before = workspace.read_with(cx, |workspace, cx| {
2515            workspace
2516                .panes()
2517                .iter()
2518                .map(|pane| pane.read(cx).items_len())
2519                .sum::<usize>()
2520        });
2521
2522        let deserialized =
2523            deserialize_editor(item_id, workspace_id, workspace.clone(), project, cx).await;
2524
2525        cx.run_until_parked();
2526
2527        // The editor should exist and have the file
2528        deserialized.update(cx, |editor, cx| {
2529            let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2530            assert!(buffer.file().is_some());
2531        });
2532
2533        // No items should have been added to any pane as a side effect
2534        let pane_items_after = workspace.read_with(cx, |workspace, cx| {
2535            workspace
2536                .panes()
2537                .iter()
2538                .map(|pane| pane.read(cx).items_len())
2539                .sum::<usize>()
2540        });
2541
2542        assert_eq!(
2543            pane_items_before, pane_items_after,
2544            "Editor::deserialize should not add items to panes as a side effect"
2545        );
2546    }
2547}