items.rs

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