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_content_text(&self, detail: usize, cx: &App) -> SharedString {
 623        if let Some(path) = path_for_buffer(&self.buffer, detail, true, cx) {
 624            path.to_string_lossy().to_string().into()
 625        } else {
 626            "untitled".into()
 627        }
 628    }
 629
 630    fn tab_icon(&self, _: &Window, cx: &App) -> Option<Icon> {
 631        ItemSettings::get_global(cx)
 632            .file_icons
 633            .then(|| {
 634                path_for_buffer(&self.buffer, 0, true, cx)
 635                    .and_then(|path| FileIcons::get_icon(path.as_ref(), cx))
 636            })
 637            .flatten()
 638            .map(Icon::from_path)
 639    }
 640
 641    fn tab_content(&self, params: TabContentParams, _: &Window, cx: &App) -> AnyElement {
 642        let label_color = if ItemSettings::get_global(cx).git_status {
 643            self.buffer()
 644                .read(cx)
 645                .as_singleton()
 646                .and_then(|buffer| {
 647                    let buffer = buffer.read(cx);
 648                    let path = buffer.project_path(cx)?;
 649                    let buffer_id = buffer.remote_id();
 650                    let project = self.project.as_ref()?.read(cx);
 651                    let entry = project.entry_for_path(&path, cx)?;
 652                    let (repo, repo_path) = project
 653                        .git_store()
 654                        .read(cx)
 655                        .repository_and_path_for_buffer_id(buffer_id, cx)?;
 656                    let status = repo.read(cx).status_for_path(&repo_path)?.status;
 657
 658                    Some(entry_git_aware_label_color(
 659                        status.summary(),
 660                        entry.is_ignored,
 661                        params.selected,
 662                    ))
 663                })
 664                .unwrap_or_else(|| entry_label_color(params.selected))
 665        } else {
 666            entry_label_color(params.selected)
 667        };
 668
 669        let description = params.detail.and_then(|detail| {
 670            let path = path_for_buffer(&self.buffer, detail, false, cx)?;
 671            let description = path.to_string_lossy();
 672            let description = description.trim();
 673
 674            if description.is_empty() {
 675                return None;
 676            }
 677
 678            Some(util::truncate_and_trailoff(description, MAX_TAB_TITLE_LEN))
 679        });
 680
 681        // Whether the file was saved in the past but is now deleted.
 682        let was_deleted: bool = self
 683            .buffer()
 684            .read(cx)
 685            .as_singleton()
 686            .and_then(|buffer| buffer.read(cx).file())
 687            .map_or(false, |file| file.disk_state() == DiskState::Deleted);
 688
 689        h_flex()
 690            .gap_2()
 691            .child(
 692                Label::new(self.title(cx).to_string())
 693                    .color(label_color)
 694                    .when(params.preview, |this| this.italic())
 695                    .when(was_deleted, |this| this.strikethrough()),
 696            )
 697            .when_some(description, |this, description| {
 698                this.child(
 699                    Label::new(description)
 700                        .size(LabelSize::XSmall)
 701                        .color(Color::Muted),
 702                )
 703            })
 704            .into_any_element()
 705    }
 706
 707    fn for_each_project_item(
 708        &self,
 709        cx: &App,
 710        f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 711    ) {
 712        self.buffer
 713            .read(cx)
 714            .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
 715    }
 716
 717    fn is_singleton(&self, cx: &App) -> bool {
 718        self.buffer.read(cx).is_singleton()
 719    }
 720
 721    fn can_save_as(&self, cx: &App) -> bool {
 722        self.buffer.read(cx).is_singleton()
 723    }
 724
 725    fn clone_on_split(
 726        &self,
 727        _workspace_id: Option<WorkspaceId>,
 728        window: &mut Window,
 729        cx: &mut Context<Self>,
 730    ) -> Option<Entity<Editor>>
 731    where
 732        Self: Sized,
 733    {
 734        Some(cx.new(|cx| self.clone(window, cx)))
 735    }
 736
 737    fn set_nav_history(
 738        &mut self,
 739        history: ItemNavHistory,
 740        _window: &mut Window,
 741        _: &mut Context<Self>,
 742    ) {
 743        self.nav_history = Some(history);
 744    }
 745
 746    fn discarded(&self, _project: Entity<Project>, _: &mut Window, cx: &mut Context<Self>) {
 747        for buffer in self.buffer().clone().read(cx).all_buffers() {
 748            buffer.update(cx, |buffer, cx| buffer.discarded(cx))
 749        }
 750    }
 751
 752    fn deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 753        let selection = self.selections.newest_anchor();
 754        self.push_to_nav_history(selection.head(), None, true, cx);
 755    }
 756
 757    fn workspace_deactivated(&mut self, _: &mut Window, cx: &mut Context<Self>) {
 758        self.hide_hovered_link(cx);
 759    }
 760
 761    fn is_dirty(&self, cx: &App) -> bool {
 762        self.buffer().read(cx).read(cx).is_dirty()
 763    }
 764
 765    fn has_deleted_file(&self, cx: &App) -> bool {
 766        self.buffer().read(cx).read(cx).has_deleted_file()
 767    }
 768
 769    fn has_conflict(&self, cx: &App) -> bool {
 770        self.buffer().read(cx).read(cx).has_conflict()
 771    }
 772
 773    fn can_save(&self, cx: &App) -> bool {
 774        let buffer = &self.buffer().read(cx);
 775        if let Some(buffer) = buffer.as_singleton() {
 776            buffer.read(cx).project_path(cx).is_some()
 777        } else {
 778            true
 779        }
 780    }
 781
 782    fn save(
 783        &mut self,
 784        format: bool,
 785        project: Entity<Project>,
 786        window: &mut Window,
 787        cx: &mut Context<Self>,
 788    ) -> Task<Result<()>> {
 789        self.report_editor_event("Editor Saved", None, cx);
 790        let buffers = self.buffer().clone().read(cx).all_buffers();
 791        let buffers = buffers
 792            .into_iter()
 793            .map(|handle| handle.read(cx).base_buffer().unwrap_or(handle.clone()))
 794            .collect::<HashSet<_>>();
 795        cx.spawn_in(window, async move |this, cx| {
 796            if format {
 797                this.update_in(cx, |editor, window, cx| {
 798                    editor.perform_format(
 799                        project.clone(),
 800                        FormatTrigger::Save,
 801                        FormatTarget::Buffers,
 802                        window,
 803                        cx,
 804                    )
 805                })?
 806                .await?;
 807            }
 808
 809            if buffers.len() == 1 {
 810                // Apply full save routine for singleton buffers, to allow to `touch` the file via the editor.
 811                project
 812                    .update(cx, |project, cx| project.save_buffers(buffers, cx))?
 813                    .await?;
 814            } else {
 815                // For multi-buffers, only format and save the buffers with changes.
 816                // For clean buffers, we simulate saving by calling `Buffer::did_save`,
 817                // so that language servers or other downstream listeners of save events get notified.
 818                let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
 819                    buffer
 820                        .update(cx, |buffer, _| buffer.is_dirty() || buffer.has_conflict())
 821                        .unwrap_or(false)
 822                });
 823
 824                project
 825                    .update(cx, |project, cx| project.save_buffers(dirty_buffers, cx))?
 826                    .await?;
 827                for buffer in clean_buffers {
 828                    buffer
 829                        .update(cx, |buffer, cx| {
 830                            let version = buffer.saved_version().clone();
 831                            let mtime = buffer.saved_mtime();
 832                            buffer.did_save(version, mtime, cx);
 833                        })
 834                        .ok();
 835                }
 836            }
 837
 838            Ok(())
 839        })
 840    }
 841
 842    fn save_as(
 843        &mut self,
 844        project: Entity<Project>,
 845        path: ProjectPath,
 846        _: &mut Window,
 847        cx: &mut Context<Self>,
 848    ) -> Task<Result<()>> {
 849        let buffer = self
 850            .buffer()
 851            .read(cx)
 852            .as_singleton()
 853            .expect("cannot call save_as on an excerpt list");
 854
 855        let file_extension = path
 856            .path
 857            .extension()
 858            .map(|a| a.to_string_lossy().to_string());
 859        self.report_editor_event("Editor Saved", file_extension, cx);
 860
 861        project.update(cx, |project, cx| project.save_buffer_as(buffer, path, cx))
 862    }
 863
 864    fn reload(
 865        &mut self,
 866        project: Entity<Project>,
 867        window: &mut Window,
 868        cx: &mut Context<Self>,
 869    ) -> Task<Result<()>> {
 870        let buffer = self.buffer().clone();
 871        let buffers = self.buffer.read(cx).all_buffers();
 872        let reload_buffers =
 873            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
 874        cx.spawn_in(window, async move |this, cx| {
 875            let transaction = reload_buffers.log_err().await;
 876            this.update(cx, |editor, cx| {
 877                editor.request_autoscroll(Autoscroll::fit(), cx)
 878            })?;
 879            buffer
 880                .update(cx, |buffer, cx| {
 881                    if let Some(transaction) = transaction {
 882                        if !buffer.is_singleton() {
 883                            buffer.push_transaction(&transaction.0, cx);
 884                        }
 885                    }
 886                })
 887                .ok();
 888            Ok(())
 889        })
 890    }
 891
 892    fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 893        Some(Box::new(handle.clone()))
 894    }
 895
 896    fn pixel_position_of_cursor(&self, _: &App) -> Option<gpui::Point<Pixels>> {
 897        self.pixel_position_of_newest_cursor
 898    }
 899
 900    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 901        if self.show_breadcrumbs {
 902            ToolbarItemLocation::PrimaryLeft
 903        } else {
 904            ToolbarItemLocation::Hidden
 905        }
 906    }
 907
 908    fn breadcrumbs(&self, variant: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 909        let cursor = self.selections.newest_anchor().head();
 910        let multibuffer = &self.buffer().read(cx);
 911        let (buffer_id, symbols) =
 912            multibuffer.symbols_containing(cursor, Some(variant.syntax()), cx)?;
 913        let buffer = multibuffer.buffer(buffer_id)?;
 914
 915        let buffer = buffer.read(cx);
 916        let text = self.breadcrumb_header.clone().unwrap_or_else(|| {
 917            buffer
 918                .snapshot()
 919                .resolve_file_path(
 920                    cx,
 921                    self.project
 922                        .as_ref()
 923                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 924                        .unwrap_or_default(),
 925                )
 926                .map(|path| path.to_string_lossy().to_string())
 927                .unwrap_or_else(|| {
 928                    if multibuffer.is_singleton() {
 929                        multibuffer.title(cx).to_string()
 930                    } else {
 931                        "untitled".to_string()
 932                    }
 933                })
 934        });
 935
 936        let settings = ThemeSettings::get_global(cx);
 937
 938        let mut breadcrumbs = vec![BreadcrumbText {
 939            text,
 940            highlights: None,
 941            font: Some(settings.buffer_font.clone()),
 942        }];
 943
 944        breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
 945            text: symbol.text,
 946            highlights: Some(symbol.highlight_ranges),
 947            font: Some(settings.buffer_font.clone()),
 948        }));
 949        Some(breadcrumbs)
 950    }
 951
 952    fn added_to_workspace(
 953        &mut self,
 954        workspace: &mut Workspace,
 955        _window: &mut Window,
 956        cx: &mut Context<Self>,
 957    ) {
 958        self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
 959        if let Some(workspace) = &workspace.weak_handle().upgrade() {
 960            cx.subscribe(&workspace, |editor, _, event: &workspace::Event, _cx| {
 961                if matches!(event, workspace::Event::ModalOpened) {
 962                    editor.mouse_context_menu.take();
 963                    editor.inline_blame_popover.take();
 964                }
 965            })
 966            .detach();
 967        }
 968    }
 969
 970    fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
 971        match event {
 972            EditorEvent::Closed => f(ItemEvent::CloseItem),
 973
 974            EditorEvent::Saved | EditorEvent::TitleChanged => {
 975                f(ItemEvent::UpdateTab);
 976                f(ItemEvent::UpdateBreadcrumbs);
 977            }
 978
 979            EditorEvent::Reparsed(_) => {
 980                f(ItemEvent::UpdateBreadcrumbs);
 981            }
 982
 983            EditorEvent::SelectionsChanged { local } if *local => {
 984                f(ItemEvent::UpdateBreadcrumbs);
 985            }
 986
 987            EditorEvent::DirtyChanged => {
 988                f(ItemEvent::UpdateTab);
 989            }
 990
 991            EditorEvent::BufferEdited => {
 992                f(ItemEvent::Edit);
 993                f(ItemEvent::UpdateBreadcrumbs);
 994            }
 995
 996            EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
 997                f(ItemEvent::Edit);
 998            }
 999
1000            _ => {}
1001        }
1002    }
1003
1004    fn preserve_preview(&self, cx: &App) -> bool {
1005        self.buffer.read(cx).preserve_preview(cx)
1006    }
1007}
1008
1009impl SerializableItem for Editor {
1010    fn serialized_item_kind() -> &'static str {
1011        "Editor"
1012    }
1013
1014    fn cleanup(
1015        workspace_id: WorkspaceId,
1016        alive_items: Vec<ItemId>,
1017        _window: &mut Window,
1018        cx: &mut App,
1019    ) -> Task<Result<()>> {
1020        workspace::delete_unloaded_items(alive_items, workspace_id, "editors", &DB, cx)
1021    }
1022
1023    fn deserialize(
1024        project: Entity<Project>,
1025        workspace: WeakEntity<Workspace>,
1026        workspace_id: workspace::WorkspaceId,
1027        item_id: ItemId,
1028        window: &mut Window,
1029        cx: &mut App,
1030    ) -> Task<Result<Entity<Self>>> {
1031        let serialized_editor = match DB
1032            .get_serialized_editor(item_id, workspace_id)
1033            .context("Failed to query editor state")
1034        {
1035            Ok(Some(serialized_editor)) => {
1036                if ProjectSettings::get_global(cx)
1037                    .session
1038                    .restore_unsaved_buffers
1039                {
1040                    serialized_editor
1041                } else {
1042                    SerializedEditor {
1043                        abs_path: serialized_editor.abs_path,
1044                        contents: None,
1045                        language: None,
1046                        mtime: None,
1047                    }
1048                }
1049            }
1050            Ok(None) => {
1051                return Task::ready(Err(anyhow!("No path or contents found for buffer")));
1052            }
1053            Err(error) => {
1054                return Task::ready(Err(error));
1055            }
1056        };
1057
1058        match serialized_editor {
1059            SerializedEditor {
1060                abs_path: None,
1061                contents: Some(contents),
1062                language,
1063                ..
1064            } => window.spawn(cx, {
1065                let project = project.clone();
1066                async move |cx| {
1067                    let language_registry =
1068                        project.update(cx, |project, _| project.languages().clone())?;
1069
1070                    let language = if let Some(language_name) = language {
1071                        // We don't fail here, because we'd rather not set the language if the name changed
1072                        // than fail to restore the buffer.
1073                        language_registry
1074                            .language_for_name(&language_name)
1075                            .await
1076                            .ok()
1077                    } else {
1078                        None
1079                    };
1080
1081                    // First create the empty buffer
1082                    let buffer = project
1083                        .update(cx, |project, cx| project.create_buffer(cx))?
1084                        .await?;
1085
1086                    // Then set the text so that the dirty bit is set correctly
1087                    buffer.update(cx, |buffer, cx| {
1088                        buffer.set_language_registry(language_registry);
1089                        if let Some(language) = language {
1090                            buffer.set_language(Some(language), cx);
1091                        }
1092                        buffer.set_text(contents, cx);
1093                        if let Some(entry) = buffer.peek_undo_stack() {
1094                            buffer.forget_transaction(entry.transaction_id());
1095                        }
1096                    })?;
1097
1098                    cx.update(|window, cx| {
1099                        cx.new(|cx| {
1100                            let mut editor = Editor::for_buffer(buffer, Some(project), window, cx);
1101
1102                            editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1103                            editor
1104                        })
1105                    })
1106                }
1107            }),
1108            SerializedEditor {
1109                abs_path: Some(abs_path),
1110                contents,
1111                mtime,
1112                ..
1113            } => {
1114                let project_item = project.update(cx, |project, cx| {
1115                    let (worktree, path) = project.find_worktree(&abs_path, cx)?;
1116                    let project_path = ProjectPath {
1117                        worktree_id: worktree.read(cx).id(),
1118                        path: path.into(),
1119                    };
1120                    Some(project.open_path(project_path, cx))
1121                });
1122
1123                match project_item {
1124                    Some(project_item) => {
1125                        window.spawn(cx, async move |cx| {
1126                            let (_, project_item) = project_item.await?;
1127                            let buffer = project_item.downcast::<Buffer>().map_err(|_| {
1128                                anyhow!("Project item at stored path was not a buffer")
1129                            })?;
1130
1131                            // This is a bit wasteful: we're loading the whole buffer from
1132                            // disk and then overwrite the content.
1133                            // But for now, it keeps the implementation of the content serialization
1134                            // simple, because we don't have to persist all of the metadata that we get
1135                            // by loading the file (git diff base, ...).
1136                            if let Some(buffer_text) = contents {
1137                                buffer.update(cx, |buffer, cx| {
1138                                    // If we did restore an mtime, we want to store it on the buffer
1139                                    // so that the next edit will mark the buffer as dirty/conflicted.
1140                                    if mtime.is_some() {
1141                                        buffer.did_reload(
1142                                            buffer.version(),
1143                                            buffer.line_ending(),
1144                                            mtime,
1145                                            cx,
1146                                        );
1147                                    }
1148                                    buffer.set_text(buffer_text, cx);
1149                                    if let Some(entry) = buffer.peek_undo_stack() {
1150                                        buffer.forget_transaction(entry.transaction_id());
1151                                    }
1152                                })?;
1153                            }
1154
1155                            cx.update(|window, cx| {
1156                                cx.new(|cx| {
1157                                    let mut editor =
1158                                        Editor::for_buffer(buffer, Some(project), window, cx);
1159
1160                                    editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1161                                    editor
1162                                })
1163                            })
1164                        })
1165                    }
1166                    None => {
1167                        let open_by_abs_path = workspace.update(cx, |workspace, cx| {
1168                            workspace.open_abs_path(
1169                                abs_path.clone(),
1170                                OpenOptions {
1171                                    visible: Some(OpenVisible::None),
1172                                    ..Default::default()
1173                                },
1174                                window,
1175                                cx,
1176                            )
1177                        });
1178                        window.spawn(cx, async move |cx| {
1179                            let editor = open_by_abs_path?.await?.downcast::<Editor>().with_context(|| format!("Failed to downcast to Editor after opening abs path {abs_path:?}"))?;
1180                            editor.update_in(cx, |editor, window, cx| {
1181                                editor.read_metadata_from_db(item_id, workspace_id, window, cx);
1182                            })?;
1183                            Ok(editor)
1184                        })
1185                    }
1186                }
1187            }
1188            SerializedEditor {
1189                abs_path: None,
1190                contents: None,
1191                ..
1192            } => Task::ready(Err(anyhow!("No path or contents found for buffer"))),
1193        }
1194    }
1195
1196    fn serialize(
1197        &mut self,
1198        workspace: &mut Workspace,
1199        item_id: ItemId,
1200        closing: bool,
1201        window: &mut Window,
1202        cx: &mut Context<Self>,
1203    ) -> Option<Task<Result<()>>> {
1204        let mut serialize_dirty_buffers = self.serialize_dirty_buffers;
1205
1206        let project = self.project.clone()?;
1207        if project.read(cx).visible_worktrees(cx).next().is_none() {
1208            // If we don't have a worktree, we don't serialize, because
1209            // projects without worktrees aren't deserialized.
1210            serialize_dirty_buffers = false;
1211        }
1212
1213        if closing && !serialize_dirty_buffers {
1214            return None;
1215        }
1216
1217        let workspace_id = workspace.database_id()?;
1218
1219        let buffer = self.buffer().read(cx).as_singleton()?;
1220
1221        let abs_path = buffer.read(cx).file().and_then(|file| {
1222            let worktree_id = file.worktree_id(cx);
1223            project
1224                .read(cx)
1225                .worktree_for_id(worktree_id, cx)
1226                .and_then(|worktree| worktree.read(cx).absolutize(&file.path()).ok())
1227                .or_else(|| {
1228                    let full_path = file.full_path(cx);
1229                    let project_path = project.read(cx).find_project_path(&full_path, cx)?;
1230                    project.read(cx).absolute_path(&project_path, cx)
1231                })
1232        });
1233
1234        let is_dirty = buffer.read(cx).is_dirty();
1235        let mtime = buffer.read(cx).saved_mtime();
1236
1237        let snapshot = buffer.read(cx).snapshot();
1238
1239        Some(cx.spawn_in(window, async move |_this, cx| {
1240            cx.background_spawn(async move {
1241                let (contents, language) = if serialize_dirty_buffers && is_dirty {
1242                    let contents = snapshot.text();
1243                    let language = snapshot.language().map(|lang| lang.name().to_string());
1244                    (Some(contents), language)
1245                } else {
1246                    (None, None)
1247                };
1248
1249                let editor = SerializedEditor {
1250                    abs_path,
1251                    contents,
1252                    language,
1253                    mtime,
1254                };
1255                log::debug!("Serializing editor {item_id:?} in workspace {workspace_id:?}");
1256                DB.save_serialized_editor(item_id, workspace_id, editor)
1257                    .await
1258                    .context("failed to save serialized editor")
1259            })
1260            .await
1261            .context("failed to save contents of buffer")?;
1262
1263            Ok(())
1264        }))
1265    }
1266
1267    fn should_serialize(&self, event: &Self::Event) -> bool {
1268        matches!(
1269            event,
1270            EditorEvent::Saved | EditorEvent::DirtyChanged | EditorEvent::BufferEdited
1271        )
1272    }
1273}
1274
1275#[derive(Debug, Default)]
1276struct EditorRestorationData {
1277    entries: HashMap<PathBuf, RestorationData>,
1278}
1279
1280#[derive(Default, Debug)]
1281pub struct RestorationData {
1282    pub scroll_position: (BufferRow, gpui::Point<f32>),
1283    pub folds: Vec<Range<Point>>,
1284    pub selections: Vec<Range<Point>>,
1285}
1286
1287impl ProjectItem for Editor {
1288    type Item = Buffer;
1289
1290    fn project_item_kind() -> Option<ProjectItemKind> {
1291        Some(ProjectItemKind("Editor"))
1292    }
1293
1294    fn for_project_item(
1295        project: Entity<Project>,
1296        pane: &Pane,
1297        buffer: Entity<Buffer>,
1298        window: &mut Window,
1299        cx: &mut Context<Self>,
1300    ) -> Self {
1301        let mut editor = Self::for_buffer(buffer.clone(), Some(project), window, cx);
1302        if let Some((excerpt_id, buffer_id, snapshot)) =
1303            editor.buffer().read(cx).snapshot(cx).as_singleton()
1304        {
1305            if WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1306                if let Some(restoration_data) = Self::project_item_kind()
1307                    .and_then(|kind| pane.project_item_restoration_data.get(&kind))
1308                    .and_then(|data| data.downcast_ref::<EditorRestorationData>())
1309                    .and_then(|data| {
1310                        let file = project::File::from_dyn(buffer.read(cx).file())?;
1311                        data.entries.get(&file.abs_path(cx))
1312                    })
1313                {
1314                    editor.fold_ranges(
1315                        clip_ranges(&restoration_data.folds, &snapshot),
1316                        false,
1317                        window,
1318                        cx,
1319                    );
1320                    if !restoration_data.selections.is_empty() {
1321                        editor.change_selections(None, window, cx, |s| {
1322                            s.select_ranges(clip_ranges(&restoration_data.selections, &snapshot));
1323                        });
1324                    }
1325                    let (top_row, offset) = restoration_data.scroll_position;
1326                    let anchor = Anchor::in_buffer(
1327                        *excerpt_id,
1328                        buffer_id,
1329                        snapshot.anchor_before(Point::new(top_row, 0)),
1330                    );
1331                    editor.set_scroll_anchor(ScrollAnchor { anchor, offset }, window, cx);
1332                }
1333            }
1334        }
1335
1336        editor
1337    }
1338}
1339
1340fn clip_ranges<'a>(
1341    original: impl IntoIterator<Item = &'a Range<Point>> + 'a,
1342    snapshot: &'a BufferSnapshot,
1343) -> Vec<Range<Point>> {
1344    original
1345        .into_iter()
1346        .map(|range| {
1347            snapshot.clip_point(range.start, Bias::Left)
1348                ..snapshot.clip_point(range.end, Bias::Right)
1349        })
1350        .collect()
1351}
1352
1353impl EventEmitter<SearchEvent> for Editor {}
1354
1355impl Editor {
1356    pub fn update_restoration_data(
1357        &self,
1358        cx: &mut Context<Self>,
1359        write: impl for<'a> FnOnce(&'a mut RestorationData) + 'static,
1360    ) {
1361        if !WorkspaceSettings::get(None, cx).restore_on_file_reopen {
1362            return;
1363        }
1364
1365        let editor = cx.entity();
1366        cx.defer(move |cx| {
1367            editor.update(cx, |editor, cx| {
1368                let kind = Editor::project_item_kind()?;
1369                let pane = editor.workspace()?.read(cx).pane_for(&cx.entity())?;
1370                let buffer = editor.buffer().read(cx).as_singleton()?;
1371                let file_abs_path = project::File::from_dyn(buffer.read(cx).file())?.abs_path(cx);
1372                pane.update(cx, |pane, _| {
1373                    let data = pane
1374                        .project_item_restoration_data
1375                        .entry(kind)
1376                        .or_insert_with(|| Box::new(EditorRestorationData::default()) as Box<_>);
1377                    let data = match data.downcast_mut::<EditorRestorationData>() {
1378                        Some(data) => data,
1379                        None => {
1380                            *data = Box::new(EditorRestorationData::default());
1381                            data.downcast_mut::<EditorRestorationData>()
1382                                .expect("just written the type downcasted to")
1383                        }
1384                    };
1385
1386                    let data = data.entries.entry(file_abs_path).or_default();
1387                    write(data);
1388                    Some(())
1389                })
1390            });
1391        });
1392    }
1393}
1394
1395pub(crate) enum BufferSearchHighlights {}
1396impl SearchableItem for Editor {
1397    type Match = Range<Anchor>;
1398
1399    fn get_matches(&self, _window: &mut Window, _: &mut App) -> Vec<Range<Anchor>> {
1400        self.background_highlights
1401            .get(&TypeId::of::<BufferSearchHighlights>())
1402            .map_or(Vec::new(), |(_color, ranges)| {
1403                ranges.iter().cloned().collect()
1404            })
1405    }
1406
1407    fn clear_matches(&mut self, _: &mut Window, cx: &mut Context<Self>) {
1408        if self
1409            .clear_background_highlights::<BufferSearchHighlights>(cx)
1410            .is_some()
1411        {
1412            cx.emit(SearchEvent::MatchesInvalidated);
1413        }
1414    }
1415
1416    fn update_matches(
1417        &mut self,
1418        matches: &[Range<Anchor>],
1419        _: &mut Window,
1420        cx: &mut Context<Self>,
1421    ) {
1422        let existing_range = self
1423            .background_highlights
1424            .get(&TypeId::of::<BufferSearchHighlights>())
1425            .map(|(_, range)| range.as_ref());
1426        let updated = existing_range != Some(matches);
1427        self.highlight_background::<BufferSearchHighlights>(
1428            matches,
1429            |theme| theme.search_match_background,
1430            cx,
1431        );
1432        if updated {
1433            cx.emit(SearchEvent::MatchesInvalidated);
1434        }
1435    }
1436
1437    fn has_filtered_search_ranges(&mut self) -> bool {
1438        self.has_background_highlights::<SearchWithinRange>()
1439    }
1440
1441    fn toggle_filtered_search_ranges(
1442        &mut self,
1443        enabled: bool,
1444        _: &mut Window,
1445        cx: &mut Context<Self>,
1446    ) {
1447        if self.has_filtered_search_ranges() {
1448            self.previous_search_ranges = self
1449                .clear_background_highlights::<SearchWithinRange>(cx)
1450                .map(|(_, ranges)| ranges)
1451        }
1452
1453        if !enabled {
1454            return;
1455        }
1456
1457        let ranges = self.selections.disjoint_anchor_ranges().collect::<Vec<_>>();
1458        if ranges.iter().any(|s| s.start != s.end) {
1459            self.set_search_within_ranges(&ranges, cx);
1460        } else if let Some(previous_search_ranges) = self.previous_search_ranges.take() {
1461            self.set_search_within_ranges(&previous_search_ranges, cx)
1462        }
1463    }
1464
1465    fn supported_options(&self) -> SearchOptions {
1466        if self.in_project_search {
1467            SearchOptions {
1468                case: true,
1469                word: true,
1470                regex: true,
1471                replacement: false,
1472                selection: false,
1473                find_in_results: true,
1474            }
1475        } else {
1476            SearchOptions {
1477                case: true,
1478                word: true,
1479                regex: true,
1480                replacement: true,
1481                selection: true,
1482                find_in_results: false,
1483            }
1484        }
1485    }
1486
1487    fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
1488        let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1489        let snapshot = &self.snapshot(window, cx).buffer_snapshot;
1490        let selection = self.selections.newest::<usize>(cx);
1491
1492        match setting {
1493            SeedQuerySetting::Never => String::new(),
1494            SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1495                let text: String = snapshot
1496                    .text_for_range(selection.start..selection.end)
1497                    .collect();
1498                if text.contains('\n') {
1499                    String::new()
1500                } else {
1501                    text
1502                }
1503            }
1504            SeedQuerySetting::Selection => String::new(),
1505            SeedQuerySetting::Always => {
1506                let (range, kind) = snapshot.surrounding_word(selection.start, true);
1507                if kind == Some(CharKind::Word) {
1508                    let text: String = snapshot.text_for_range(range).collect();
1509                    if !text.trim().is_empty() {
1510                        return text;
1511                    }
1512                }
1513                String::new()
1514            }
1515        }
1516    }
1517
1518    fn activate_match(
1519        &mut self,
1520        index: usize,
1521        matches: &[Range<Anchor>],
1522        window: &mut Window,
1523        cx: &mut Context<Self>,
1524    ) {
1525        self.unfold_ranges(&[matches[index].clone()], false, true, cx);
1526        let range = self.range_for_match(&matches[index]);
1527        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
1528            s.select_ranges([range]);
1529        })
1530    }
1531
1532    fn select_matches(
1533        &mut self,
1534        matches: &[Self::Match],
1535        window: &mut Window,
1536        cx: &mut Context<Self>,
1537    ) {
1538        self.unfold_ranges(matches, false, false, cx);
1539        self.change_selections(None, window, cx, |s| {
1540            s.select_ranges(matches.iter().cloned())
1541        });
1542    }
1543    fn replace(
1544        &mut self,
1545        identifier: &Self::Match,
1546        query: &SearchQuery,
1547        window: &mut Window,
1548        cx: &mut Context<Self>,
1549    ) {
1550        let text = self.buffer.read(cx);
1551        let text = text.snapshot(cx);
1552        let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1553        let text: Cow<_> = if text.len() == 1 {
1554            text.first().cloned().unwrap().into()
1555        } else {
1556            let joined_chunks = text.join("");
1557            joined_chunks.into()
1558        };
1559
1560        if let Some(replacement) = query.replacement_for(&text) {
1561            self.transact(window, cx, |this, _, cx| {
1562                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1563            });
1564        }
1565    }
1566    fn replace_all(
1567        &mut self,
1568        matches: &mut dyn Iterator<Item = &Self::Match>,
1569        query: &SearchQuery,
1570        window: &mut Window,
1571        cx: &mut Context<Self>,
1572    ) {
1573        let text = self.buffer.read(cx);
1574        let text = text.snapshot(cx);
1575        let mut edits = vec![];
1576        let mut last_point: Option<Point> = None;
1577
1578        for m in matches {
1579            let point = m.start.to_point(&text);
1580            let text = text.text_for_range(m.clone()).collect::<Vec<_>>();
1581
1582            // Check if the row for the current match is different from the last
1583            // match. If that's not the case and we're still replacing matches
1584            // in the same row/line, skip this match if the `one_match_per_line`
1585            // option is enabled.
1586            if last_point.is_none() {
1587                last_point = Some(point);
1588            } else if last_point.is_some() && point.row != last_point.unwrap().row {
1589                last_point = Some(point);
1590            } else if query.one_match_per_line().is_some_and(|enabled| enabled) {
1591                continue;
1592            }
1593
1594            let text: Cow<_> = if text.len() == 1 {
1595                text.first().cloned().unwrap().into()
1596            } else {
1597                let joined_chunks = text.join("");
1598                joined_chunks.into()
1599            };
1600
1601            if let Some(replacement) = query.replacement_for(&text) {
1602                edits.push((m.clone(), Arc::from(&*replacement)));
1603            }
1604        }
1605
1606        if !edits.is_empty() {
1607            self.transact(window, cx, |this, _, cx| {
1608                this.edit(edits, cx);
1609            });
1610        }
1611    }
1612    fn match_index_for_direction(
1613        &mut self,
1614        matches: &[Range<Anchor>],
1615        current_index: usize,
1616        direction: Direction,
1617        count: usize,
1618        _: &mut Window,
1619        cx: &mut Context<Self>,
1620    ) -> usize {
1621        let buffer = self.buffer().read(cx).snapshot(cx);
1622        let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1623            self.selections.newest_anchor().head()
1624        } else {
1625            matches[current_index].start
1626        };
1627
1628        let mut count = count % matches.len();
1629        if count == 0 {
1630            return current_index;
1631        }
1632        match direction {
1633            Direction::Next => {
1634                if matches[current_index]
1635                    .start
1636                    .cmp(&current_index_position, &buffer)
1637                    .is_gt()
1638                {
1639                    count -= 1
1640                }
1641
1642                (current_index + count) % matches.len()
1643            }
1644            Direction::Prev => {
1645                if matches[current_index]
1646                    .end
1647                    .cmp(&current_index_position, &buffer)
1648                    .is_lt()
1649                {
1650                    count -= 1;
1651                }
1652
1653                if current_index >= count {
1654                    current_index - count
1655                } else {
1656                    matches.len() - (count - current_index)
1657                }
1658            }
1659        }
1660    }
1661
1662    fn find_matches(
1663        &mut self,
1664        query: Arc<project::search::SearchQuery>,
1665        _: &mut Window,
1666        cx: &mut Context<Self>,
1667    ) -> Task<Vec<Range<Anchor>>> {
1668        let buffer = self.buffer().read(cx).snapshot(cx);
1669        let search_within_ranges = self
1670            .background_highlights
1671            .get(&TypeId::of::<SearchWithinRange>())
1672            .map_or(vec![], |(_color, ranges)| {
1673                ranges.iter().cloned().collect::<Vec<_>>()
1674            });
1675
1676        cx.background_spawn(async move {
1677            let mut ranges = Vec::new();
1678
1679            let search_within_ranges = if search_within_ranges.is_empty() {
1680                vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())]
1681            } else {
1682                search_within_ranges
1683            };
1684
1685            for range in search_within_ranges {
1686                for (search_buffer, search_range, excerpt_id, deleted_hunk_anchor) in
1687                    buffer.range_to_buffer_ranges_with_deleted_hunks(range)
1688                {
1689                    ranges.extend(
1690                        query
1691                            .search(search_buffer, Some(search_range.clone()))
1692                            .await
1693                            .into_iter()
1694                            .map(|match_range| {
1695                                if let Some(deleted_hunk_anchor) = deleted_hunk_anchor {
1696                                    let start = search_buffer
1697                                        .anchor_after(search_range.start + match_range.start);
1698                                    let end = search_buffer
1699                                        .anchor_before(search_range.start + match_range.end);
1700                                    Anchor {
1701                                        diff_base_anchor: Some(start),
1702                                        ..deleted_hunk_anchor
1703                                    }..Anchor {
1704                                        diff_base_anchor: Some(end),
1705                                        ..deleted_hunk_anchor
1706                                    }
1707                                } else {
1708                                    let start = search_buffer
1709                                        .anchor_after(search_range.start + match_range.start);
1710                                    let end = search_buffer
1711                                        .anchor_before(search_range.start + match_range.end);
1712                                    Anchor::range_in_buffer(
1713                                        excerpt_id,
1714                                        search_buffer.remote_id(),
1715                                        start..end,
1716                                    )
1717                                }
1718                            }),
1719                    );
1720                }
1721            }
1722
1723            ranges
1724        })
1725    }
1726
1727    fn active_match_index(
1728        &mut self,
1729        direction: Direction,
1730        matches: &[Range<Anchor>],
1731        _: &mut Window,
1732        cx: &mut Context<Self>,
1733    ) -> Option<usize> {
1734        active_match_index(
1735            direction,
1736            matches,
1737            &self.selections.newest_anchor().head(),
1738            &self.buffer().read(cx).snapshot(cx),
1739        )
1740    }
1741
1742    fn search_bar_visibility_changed(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {
1743        self.expect_bounds_change = self.last_bounds;
1744    }
1745}
1746
1747pub fn active_match_index(
1748    direction: Direction,
1749    ranges: &[Range<Anchor>],
1750    cursor: &Anchor,
1751    buffer: &MultiBufferSnapshot,
1752) -> Option<usize> {
1753    if ranges.is_empty() {
1754        None
1755    } else {
1756        let r = ranges.binary_search_by(|probe| {
1757            if probe.end.cmp(cursor, buffer).is_lt() {
1758                Ordering::Less
1759            } else if probe.start.cmp(cursor, buffer).is_gt() {
1760                Ordering::Greater
1761            } else {
1762                Ordering::Equal
1763            }
1764        });
1765        match direction {
1766            Direction::Prev => match r {
1767                Ok(i) => Some(i),
1768                Err(i) => Some(i.saturating_sub(1)),
1769            },
1770            Direction::Next => match r {
1771                Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1772            },
1773        }
1774    }
1775}
1776
1777pub fn entry_label_color(selected: bool) -> Color {
1778    if selected {
1779        Color::Default
1780    } else {
1781        Color::Muted
1782    }
1783}
1784
1785pub fn entry_diagnostic_aware_icon_name_and_color(
1786    diagnostic_severity: Option<DiagnosticSeverity>,
1787) -> Option<(IconName, Color)> {
1788    match diagnostic_severity {
1789        Some(DiagnosticSeverity::ERROR) => Some((IconName::X, Color::Error)),
1790        Some(DiagnosticSeverity::WARNING) => Some((IconName::Triangle, Color::Warning)),
1791        _ => None,
1792    }
1793}
1794
1795pub fn entry_diagnostic_aware_icon_decoration_and_color(
1796    diagnostic_severity: Option<DiagnosticSeverity>,
1797) -> Option<(IconDecorationKind, Color)> {
1798    match diagnostic_severity {
1799        Some(DiagnosticSeverity::ERROR) => Some((IconDecorationKind::X, Color::Error)),
1800        Some(DiagnosticSeverity::WARNING) => Some((IconDecorationKind::Triangle, Color::Warning)),
1801        _ => None,
1802    }
1803}
1804
1805pub fn entry_git_aware_label_color(git_status: GitSummary, ignored: bool, selected: bool) -> Color {
1806    let tracked = git_status.index + git_status.worktree;
1807    if ignored {
1808        Color::Ignored
1809    } else if git_status.conflict > 0 {
1810        Color::Conflict
1811    } else if tracked.modified > 0 {
1812        Color::Modified
1813    } else if tracked.added > 0 || git_status.untracked > 0 {
1814        Color::Created
1815    } else {
1816        entry_label_color(selected)
1817    }
1818}
1819
1820fn path_for_buffer<'a>(
1821    buffer: &Entity<MultiBuffer>,
1822    height: usize,
1823    include_filename: bool,
1824    cx: &'a App,
1825) -> Option<Cow<'a, Path>> {
1826    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1827    path_for_file(file.as_ref(), height, include_filename, cx)
1828}
1829
1830fn path_for_file<'a>(
1831    file: &'a dyn language::File,
1832    mut height: usize,
1833    include_filename: bool,
1834    cx: &'a App,
1835) -> Option<Cow<'a, Path>> {
1836    // Ensure we always render at least the filename.
1837    height += 1;
1838
1839    let mut prefix = file.path().as_ref();
1840    while height > 0 {
1841        if let Some(parent) = prefix.parent() {
1842            prefix = parent;
1843            height -= 1;
1844        } else {
1845            break;
1846        }
1847    }
1848
1849    // Here we could have just always used `full_path`, but that is very
1850    // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1851    // traversed all the way up to the worktree's root.
1852    if height > 0 {
1853        let full_path = file.full_path(cx);
1854        if include_filename {
1855            Some(full_path.into())
1856        } else {
1857            Some(full_path.parent()?.to_path_buf().into())
1858        }
1859    } else {
1860        let mut path = file.path().strip_prefix(prefix).ok()?;
1861        if !include_filename {
1862            path = path.parent()?;
1863        }
1864        Some(path.into())
1865    }
1866}
1867
1868#[cfg(test)]
1869mod tests {
1870    use crate::editor_tests::init_test;
1871    use fs::Fs;
1872
1873    use super::*;
1874    use fs::MTime;
1875    use gpui::{App, VisualTestContext};
1876    use language::{LanguageMatcher, TestFile};
1877    use project::FakeFs;
1878    use std::path::{Path, PathBuf};
1879    use util::path;
1880
1881    #[gpui::test]
1882    fn test_path_for_file(cx: &mut App) {
1883        let file = TestFile {
1884            path: Path::new("").into(),
1885            root_name: String::new(),
1886            local_root: None,
1887        };
1888        assert_eq!(path_for_file(&file, 0, false, cx), None);
1889    }
1890
1891    async fn deserialize_editor(
1892        item_id: ItemId,
1893        workspace_id: WorkspaceId,
1894        workspace: Entity<Workspace>,
1895        project: Entity<Project>,
1896        cx: &mut VisualTestContext,
1897    ) -> Entity<Editor> {
1898        workspace
1899            .update_in(cx, |workspace, window, cx| {
1900                let pane = workspace.active_pane();
1901                pane.update(cx, |_, cx| {
1902                    Editor::deserialize(
1903                        project.clone(),
1904                        workspace.weak_handle(),
1905                        workspace_id,
1906                        item_id,
1907                        window,
1908                        cx,
1909                    )
1910                })
1911            })
1912            .await
1913            .unwrap()
1914    }
1915
1916    fn rust_language() -> Arc<language::Language> {
1917        Arc::new(language::Language::new(
1918            language::LanguageConfig {
1919                name: "Rust".into(),
1920                matcher: LanguageMatcher {
1921                    path_suffixes: vec!["rs".to_string()],
1922                    ..Default::default()
1923                },
1924                ..Default::default()
1925            },
1926            Some(tree_sitter_rust::LANGUAGE.into()),
1927        ))
1928    }
1929
1930    #[gpui::test]
1931    async fn test_deserialize(cx: &mut gpui::TestAppContext) {
1932        init_test(cx, |_| {});
1933
1934        let fs = FakeFs::new(cx.executor());
1935        fs.insert_file(path!("/file.rs"), Default::default()).await;
1936
1937        // Test case 1: Deserialize with path and contents
1938        {
1939            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1940            let (workspace, cx) =
1941                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1942            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1943            let item_id = 1234 as ItemId;
1944            let mtime = fs
1945                .metadata(Path::new(path!("/file.rs")))
1946                .await
1947                .unwrap()
1948                .unwrap()
1949                .mtime;
1950
1951            let serialized_editor = SerializedEditor {
1952                abs_path: Some(PathBuf::from(path!("/file.rs"))),
1953                contents: Some("fn main() {}".to_string()),
1954                language: Some("Rust".to_string()),
1955                mtime: Some(mtime),
1956            };
1957
1958            DB.save_serialized_editor(item_id, workspace_id, serialized_editor.clone())
1959                .await
1960                .unwrap();
1961
1962            let deserialized =
1963                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1964
1965            deserialized.update(cx, |editor, cx| {
1966                assert_eq!(editor.text(cx), "fn main() {}");
1967                assert!(editor.is_dirty(cx));
1968                assert!(!editor.has_conflict(cx));
1969                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
1970                assert!(buffer.file().is_some());
1971            });
1972        }
1973
1974        // Test case 2: Deserialize with only path
1975        {
1976            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
1977            let (workspace, cx) =
1978                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1979
1980            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
1981
1982            let item_id = 5678 as ItemId;
1983            let serialized_editor = SerializedEditor {
1984                abs_path: Some(PathBuf::from(path!("/file.rs"))),
1985                contents: None,
1986                language: None,
1987                mtime: None,
1988            };
1989
1990            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
1991                .await
1992                .unwrap();
1993
1994            let deserialized =
1995                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
1996
1997            deserialized.update(cx, |editor, cx| {
1998                assert_eq!(editor.text(cx), ""); // The file should be empty as per our initial setup
1999                assert!(!editor.is_dirty(cx));
2000                assert!(!editor.has_conflict(cx));
2001
2002                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2003                assert!(buffer.file().is_some());
2004            });
2005        }
2006
2007        // Test case 3: Deserialize with no path (untitled buffer, with content and language)
2008        {
2009            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2010            // Add Rust to the language, so that we can restore the language of the buffer
2011            project.update(cx, |project, _| project.languages().add(rust_language()));
2012
2013            let (workspace, cx) =
2014                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2015
2016            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2017
2018            let item_id = 9012 as ItemId;
2019            let serialized_editor = SerializedEditor {
2020                abs_path: None,
2021                contents: Some("hello".to_string()),
2022                language: Some("Rust".to_string()),
2023                mtime: None,
2024            };
2025
2026            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2027                .await
2028                .unwrap();
2029
2030            let deserialized =
2031                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2032
2033            deserialized.update(cx, |editor, cx| {
2034                assert_eq!(editor.text(cx), "hello");
2035                assert!(editor.is_dirty(cx)); // The editor should be dirty for an untitled buffer
2036
2037                let buffer = editor.buffer().read(cx).as_singleton().unwrap().read(cx);
2038                assert_eq!(
2039                    buffer.language().map(|lang| lang.name()),
2040                    Some("Rust".into())
2041                ); // Language should be set to Rust
2042                assert!(buffer.file().is_none()); // The buffer should not have an associated file
2043            });
2044        }
2045
2046        // Test case 4: Deserialize with path, content, and old mtime
2047        {
2048            let project = Project::test(fs.clone(), [path!("/file.rs").as_ref()], cx).await;
2049            let (workspace, cx) =
2050                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2051
2052            let workspace_id = workspace::WORKSPACE_DB.next_id().await.unwrap();
2053
2054            let item_id = 9345 as ItemId;
2055            let old_mtime = MTime::from_seconds_and_nanos(0, 50);
2056            let serialized_editor = SerializedEditor {
2057                abs_path: Some(PathBuf::from(path!("/file.rs"))),
2058                contents: Some("fn main() {}".to_string()),
2059                language: Some("Rust".to_string()),
2060                mtime: Some(old_mtime),
2061            };
2062
2063            DB.save_serialized_editor(item_id, workspace_id, serialized_editor)
2064                .await
2065                .unwrap();
2066
2067            let deserialized =
2068                deserialize_editor(item_id, workspace_id, workspace, project, cx).await;
2069
2070            deserialized.update(cx, |editor, cx| {
2071                assert_eq!(editor.text(cx), "fn main() {}");
2072                assert!(editor.has_conflict(cx)); // The editor should have a conflict
2073            });
2074        }
2075    }
2076}