items.rs

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