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