items.rs

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