items.rs

   1use crate::{
   2    editor_settings::SeedQuerySetting, persistence::DB, scroll::ScrollAnchor, Anchor, Autoscroll,
   3    Editor, EditorEvent, EditorSettings, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot,
   4    NavigationData, ToPoint as _,
   5};
   6use anyhow::{anyhow, Context as _, Result};
   7use collections::HashSet;
   8use futures::future::try_join_all;
   9use gpui::{
  10    div, point, AnyElement, AppContext, AsyncWindowContext, Context, Entity, EntityId,
  11    EventEmitter, IntoElement, Model, ParentElement, Pixels, Render, SharedString, Styled,
  12    Subscription, Task, View, ViewContext, VisualContext, WeakView, WindowContext,
  13};
  14use language::{
  15    proto::serialize_anchor as serialize_text_anchor, Bias, Buffer, CharKind, OffsetRangeExt,
  16    Point, SelectionGoal,
  17};
  18use project::repository::GitFileStatus;
  19use project::{search::SearchQuery, FormatTrigger, Item as _, Project, ProjectPath};
  20use rpc::proto::{self, update_view, PeerId};
  21use settings::Settings;
  22use workspace::item::ItemSettings;
  23
  24use std::fmt::Write;
  25use std::{
  26    borrow::Cow,
  27    cmp::{self, Ordering},
  28    iter,
  29    ops::Range,
  30    path::{Path, PathBuf},
  31    sync::Arc,
  32};
  33use text::{BufferId, Selection};
  34use theme::Theme;
  35use ui::{h_flex, prelude::*, Label};
  36use util::{paths::PathExt, paths::FILE_ROW_COLUMN_DELIMITER, ResultExt, TryFutureExt};
  37use workspace::{
  38    item::{BreadcrumbText, FollowEvent, FollowableItemHandle},
  39    StatusItemView,
  40};
  41use workspace::{
  42    item::{FollowableItem, Item, ItemEvent, ItemHandle, ProjectItem},
  43    searchable::{Direction, SearchEvent, SearchableItem, SearchableItemHandle},
  44    ItemId, ItemNavHistory, Pane, ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
  45};
  46
  47pub const MAX_TAB_TITLE_LEN: usize = 24;
  48
  49impl FollowableItem for Editor {
  50    fn remote_id(&self) -> Option<ViewId> {
  51        self.remote_id
  52    }
  53
  54    fn from_state_proto(
  55        pane: View<workspace::Pane>,
  56        workspace: View<Workspace>,
  57        remote_id: ViewId,
  58        state: &mut Option<proto::view::Variant>,
  59        cx: &mut WindowContext,
  60    ) -> Option<Task<Result<View<Self>>>> {
  61        let project = workspace.read(cx).project().to_owned();
  62        let Some(proto::view::Variant::Editor(_)) = state else {
  63            return None;
  64        };
  65        let Some(proto::view::Variant::Editor(state)) = state.take() else {
  66            unreachable!()
  67        };
  68
  69        let client = project.read(cx).client();
  70        let replica_id = project.read(cx).replica_id();
  71        let buffer_ids = state
  72            .excerpts
  73            .iter()
  74            .map(|excerpt| excerpt.buffer_id)
  75            .collect::<HashSet<_>>();
  76        let buffers = project.update(cx, |project, cx| {
  77            buffer_ids
  78                .iter()
  79                .map(|id| BufferId::new(*id).map(|id| project.open_buffer_by_id(id, cx)))
  80                .collect::<Result<Vec<_>>>()
  81        });
  82
  83        let pane = pane.downgrade();
  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            let editor = pane.update(&mut cx, |pane, cx| {
  89                let mut editors = pane.items_of_type::<Self>();
  90                editors.find(|editor| {
  91                    let ids_match = editor.remote_id(&client, cx) == Some(remote_id);
  92                    let singleton_buffer_matches = state.singleton
  93                        && buffers.first()
  94                            == editor.read(cx).buffer.read(cx).as_singleton().as_ref();
  95                    ids_match || singleton_buffer_matches
  96                })
  97            })?;
  98
  99            let editor = if let Some(editor) = editor {
 100                editor
 101            } else {
 102                pane.update(&mut cx, |_, cx| {
 103                    let multibuffer = cx.new_model(|cx| {
 104                        let mut multibuffer;
 105                        if state.singleton && buffers.len() == 1 {
 106                            multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
 107                        } else {
 108                            multibuffer =
 109                                MultiBuffer::new(replica_id, project.read(cx).capability());
 110                            let mut excerpts = state.excerpts.into_iter().peekable();
 111                            while let Some(excerpt) = excerpts.peek() {
 112                                let Ok(buffer_id) = BufferId::new(excerpt.buffer_id) else {
 113                                    continue;
 114                                };
 115                                let buffer_excerpts = iter::from_fn(|| {
 116                                    let excerpt = excerpts.peek()?;
 117                                    (excerpt.buffer_id == u64::from(buffer_id))
 118                                        .then(|| excerpts.next().unwrap())
 119                                });
 120                                let buffer =
 121                                    buffers.iter().find(|b| b.read(cx).remote_id() == buffer_id);
 122                                if let Some(buffer) = buffer {
 123                                    multibuffer.push_excerpts(
 124                                        buffer.clone(),
 125                                        buffer_excerpts.filter_map(deserialize_excerpt_range),
 126                                        cx,
 127                                    );
 128                                }
 129                            }
 130                        };
 131
 132                        if let Some(title) = &state.title {
 133                            multibuffer = multibuffer.with_title(title.clone())
 134                        }
 135
 136                        multibuffer
 137                    });
 138
 139                    cx.new_view(|cx| {
 140                        let mut editor =
 141                            Editor::for_multibuffer(multibuffer, Some(project.clone()), cx);
 142                        editor.remote_id = Some(remote_id);
 143                        editor
 144                    })
 145                })?
 146            };
 147
 148            update_editor_from_message(
 149                editor.downgrade(),
 150                project,
 151                proto::update_view::Editor {
 152                    selections: state.selections,
 153                    pending_selection: state.pending_selection,
 154                    scroll_top_anchor: state.scroll_top_anchor,
 155                    scroll_x: state.scroll_x,
 156                    scroll_y: state.scroll_y,
 157                    ..Default::default()
 158                },
 159                &mut cx,
 160            )
 161            .await?;
 162
 163            Ok(editor)
 164        }))
 165    }
 166
 167    fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>) {
 168        self.leader_peer_id = leader_peer_id;
 169        if self.leader_peer_id.is_some() {
 170            self.buffer.update(cx, |buffer, cx| {
 171                buffer.remove_active_selections(cx);
 172            });
 173        } else if self.focus_handle.is_focused(cx) {
 174            self.buffer.update(cx, |buffer, cx| {
 175                buffer.set_active_selections(
 176                    &self.selections.disjoint_anchors(),
 177                    self.selections.line_mode,
 178                    self.cursor_shape,
 179                    cx,
 180                );
 181            });
 182        }
 183        cx.notify();
 184    }
 185
 186    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
 187        let buffer = self.buffer.read(cx);
 188        if buffer
 189            .as_singleton()
 190            .and_then(|buffer| buffer.read(cx).file())
 191            .map_or(false, |file| file.is_private())
 192        {
 193            return None;
 194        }
 195
 196        let scroll_anchor = self.scroll_manager.anchor();
 197        let excerpts = buffer
 198            .read(cx)
 199            .excerpts()
 200            .map(|(id, buffer, range)| proto::Excerpt {
 201                id: id.to_proto(),
 202                buffer_id: buffer.remote_id().into(),
 203                context_start: Some(serialize_text_anchor(&range.context.start)),
 204                context_end: Some(serialize_text_anchor(&range.context.end)),
 205                primary_start: range
 206                    .primary
 207                    .as_ref()
 208                    .map(|range| serialize_text_anchor(&range.start)),
 209                primary_end: range
 210                    .primary
 211                    .as_ref()
 212                    .map(|range| serialize_text_anchor(&range.end)),
 213            })
 214            .collect();
 215
 216        Some(proto::view::Variant::Editor(proto::view::Editor {
 217            singleton: buffer.is_singleton(),
 218            title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
 219            excerpts,
 220            scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
 221            scroll_x: scroll_anchor.offset.x,
 222            scroll_y: scroll_anchor.offset.y,
 223            selections: self
 224                .selections
 225                .disjoint_anchors()
 226                .iter()
 227                .map(serialize_selection)
 228                .collect(),
 229            pending_selection: self
 230                .selections
 231                .pending_anchor()
 232                .as_ref()
 233                .map(serialize_selection),
 234        }))
 235    }
 236
 237    fn to_follow_event(event: &EditorEvent) -> Option<workspace::item::FollowEvent> {
 238        match event {
 239            EditorEvent::Edited => Some(FollowEvent::Unfollow),
 240            EditorEvent::SelectionsChanged { local }
 241            | EditorEvent::ScrollPositionChanged { local, .. } => {
 242                if *local {
 243                    Some(FollowEvent::Unfollow)
 244                } else {
 245                    None
 246                }
 247            }
 248            _ => None,
 249        }
 250    }
 251
 252    fn add_event_to_update_proto(
 253        &self,
 254        event: &EditorEvent,
 255        update: &mut Option<proto::update_view::Variant>,
 256        cx: &WindowContext,
 257    ) -> bool {
 258        let update =
 259            update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
 260
 261        match update {
 262            proto::update_view::Variant::Editor(update) => match event {
 263                EditorEvent::ExcerptsAdded {
 264                    buffer,
 265                    predecessor,
 266                    excerpts,
 267                } => {
 268                    let buffer_id = buffer.read(cx).remote_id();
 269                    let mut excerpts = excerpts.iter();
 270                    if let Some((id, range)) = excerpts.next() {
 271                        update.inserted_excerpts.push(proto::ExcerptInsertion {
 272                            previous_excerpt_id: Some(predecessor.to_proto()),
 273                            excerpt: serialize_excerpt(buffer_id, id, range),
 274                        });
 275                        update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
 276                            proto::ExcerptInsertion {
 277                                previous_excerpt_id: None,
 278                                excerpt: serialize_excerpt(buffer_id, id, range),
 279                            }
 280                        }))
 281                    }
 282                    true
 283                }
 284                EditorEvent::ExcerptsRemoved { ids } => {
 285                    update
 286                        .deleted_excerpts
 287                        .extend(ids.iter().map(ExcerptId::to_proto));
 288                    true
 289                }
 290                EditorEvent::ScrollPositionChanged { autoscroll, .. } if !autoscroll => {
 291                    let scroll_anchor = self.scroll_manager.anchor();
 292                    update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
 293                    update.scroll_x = scroll_anchor.offset.x;
 294                    update.scroll_y = scroll_anchor.offset.y;
 295                    true
 296                }
 297                EditorEvent::SelectionsChanged { .. } => {
 298                    update.selections = self
 299                        .selections
 300                        .disjoint_anchors()
 301                        .iter()
 302                        .map(serialize_selection)
 303                        .collect();
 304                    update.pending_selection = self
 305                        .selections
 306                        .pending_anchor()
 307                        .as_ref()
 308                        .map(serialize_selection);
 309                    true
 310                }
 311                _ => false,
 312            },
 313        }
 314    }
 315
 316    fn apply_update_proto(
 317        &mut self,
 318        project: &Model<Project>,
 319        message: update_view::Variant,
 320        cx: &mut ViewContext<Self>,
 321    ) -> Task<Result<()>> {
 322        let update_view::Variant::Editor(message) = message;
 323        let project = project.clone();
 324        cx.spawn(|this, mut cx| async move {
 325            update_editor_from_message(this, project, message, &mut cx).await
 326        })
 327    }
 328
 329    fn is_project_item(&self, _cx: &WindowContext) -> bool {
 330        true
 331    }
 332}
 333
 334async fn update_editor_from_message(
 335    this: WeakView<Editor>,
 336    project: Model<Project>,
 337    message: proto::update_view::Editor,
 338    cx: &mut AsyncWindowContext,
 339) -> Result<()> {
 340    // Open all of the buffers of which excerpts were added to the editor.
 341    let inserted_excerpt_buffer_ids = message
 342        .inserted_excerpts
 343        .iter()
 344        .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
 345        .collect::<HashSet<_>>();
 346    let inserted_excerpt_buffers = project.update(cx, |project, cx| {
 347        inserted_excerpt_buffer_ids
 348            .into_iter()
 349            .map(|id| BufferId::new(id).map(|id| project.open_buffer_by_id(id, cx)))
 350            .collect::<Result<Vec<_>>>()
 351    })??;
 352    let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
 353
 354    // Update the editor's excerpts.
 355    this.update(cx, |editor, cx| {
 356        editor.buffer.update(cx, |multibuffer, cx| {
 357            let mut removed_excerpt_ids = message
 358                .deleted_excerpts
 359                .into_iter()
 360                .map(ExcerptId::from_proto)
 361                .collect::<Vec<_>>();
 362            removed_excerpt_ids.sort_by({
 363                let multibuffer = multibuffer.read(cx);
 364                move |a, b| a.cmp(&b, &multibuffer)
 365            });
 366
 367            let mut insertions = message.inserted_excerpts.into_iter().peekable();
 368            while let Some(insertion) = insertions.next() {
 369                let Some(excerpt) = insertion.excerpt else {
 370                    continue;
 371                };
 372                let Some(previous_excerpt_id) = insertion.previous_excerpt_id else {
 373                    continue;
 374                };
 375                let buffer_id = BufferId::new(excerpt.buffer_id)?;
 376                let Some(buffer) = project.read(cx).buffer_for_id(buffer_id) else {
 377                    continue;
 378                };
 379
 380                let adjacent_excerpts = iter::from_fn(|| {
 381                    let insertion = insertions.peek()?;
 382                    if insertion.previous_excerpt_id.is_none()
 383                        && insertion.excerpt.as_ref()?.buffer_id == u64::from(buffer_id)
 384                    {
 385                        insertions.next()?.excerpt
 386                    } else {
 387                        None
 388                    }
 389                });
 390
 391                multibuffer.insert_excerpts_with_ids_after(
 392                    ExcerptId::from_proto(previous_excerpt_id),
 393                    buffer,
 394                    [excerpt]
 395                        .into_iter()
 396                        .chain(adjacent_excerpts)
 397                        .filter_map(|excerpt| {
 398                            Some((
 399                                ExcerptId::from_proto(excerpt.id),
 400                                deserialize_excerpt_range(excerpt)?,
 401                            ))
 402                        }),
 403                    cx,
 404                );
 405            }
 406
 407            multibuffer.remove_excerpts(removed_excerpt_ids, cx);
 408            Result::<(), anyhow::Error>::Ok(())
 409        })
 410    })??;
 411
 412    // Deserialize the editor state.
 413    let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {
 414        let buffer = editor.buffer.read(cx).read(cx);
 415        let selections = message
 416            .selections
 417            .into_iter()
 418            .filter_map(|selection| deserialize_selection(&buffer, selection))
 419            .collect::<Vec<_>>();
 420        let pending_selection = message
 421            .pending_selection
 422            .and_then(|selection| deserialize_selection(&buffer, selection));
 423        let scroll_top_anchor = message
 424            .scroll_top_anchor
 425            .and_then(|anchor| deserialize_anchor(&buffer, anchor));
 426        anyhow::Ok((selections, pending_selection, scroll_top_anchor))
 427    })??;
 428
 429    // Wait until the buffer has received all of the operations referenced by
 430    // the editor's new state.
 431    this.update(cx, |editor, cx| {
 432        editor.buffer.update(cx, |buffer, cx| {
 433            buffer.wait_for_anchors(
 434                selections
 435                    .iter()
 436                    .chain(pending_selection.as_ref())
 437                    .flat_map(|selection| [selection.start, selection.end])
 438                    .chain(scroll_top_anchor),
 439                cx,
 440            )
 441        })
 442    })?
 443    .await?;
 444
 445    // Update the editor's state.
 446    this.update(cx, |editor, cx| {
 447        if !selections.is_empty() || pending_selection.is_some() {
 448            editor.set_selections_from_remote(selections, pending_selection, cx);
 449            editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
 450        } else if let Some(scroll_top_anchor) = scroll_top_anchor {
 451            editor.set_scroll_anchor_remote(
 452                ScrollAnchor {
 453                    anchor: scroll_top_anchor,
 454                    offset: point(message.scroll_x, message.scroll_y),
 455                },
 456                cx,
 457            );
 458        }
 459    })?;
 460    Ok(())
 461}
 462
 463fn serialize_excerpt(
 464    buffer_id: BufferId,
 465    id: &ExcerptId,
 466    range: &ExcerptRange<language::Anchor>,
 467) -> Option<proto::Excerpt> {
 468    Some(proto::Excerpt {
 469        id: id.to_proto(),
 470        buffer_id: buffer_id.into(),
 471        context_start: Some(serialize_text_anchor(&range.context.start)),
 472        context_end: Some(serialize_text_anchor(&range.context.end)),
 473        primary_start: range
 474            .primary
 475            .as_ref()
 476            .map(|r| serialize_text_anchor(&r.start)),
 477        primary_end: range
 478            .primary
 479            .as_ref()
 480            .map(|r| serialize_text_anchor(&r.end)),
 481    })
 482}
 483
 484fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
 485    proto::Selection {
 486        id: selection.id as u64,
 487        start: Some(serialize_anchor(&selection.start)),
 488        end: Some(serialize_anchor(&selection.end)),
 489        reversed: selection.reversed,
 490    }
 491}
 492
 493fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
 494    proto::EditorAnchor {
 495        excerpt_id: anchor.excerpt_id.to_proto(),
 496        anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
 497    }
 498}
 499
 500fn deserialize_excerpt_range(excerpt: proto::Excerpt) -> Option<ExcerptRange<language::Anchor>> {
 501    let context = {
 502        let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
 503        let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
 504        start..end
 505    };
 506    let primary = excerpt
 507        .primary_start
 508        .zip(excerpt.primary_end)
 509        .and_then(|(start, end)| {
 510            let start = language::proto::deserialize_anchor(start)?;
 511            let end = language::proto::deserialize_anchor(end)?;
 512            Some(start..end)
 513        });
 514    Some(ExcerptRange { context, primary })
 515}
 516
 517fn deserialize_selection(
 518    buffer: &MultiBufferSnapshot,
 519    selection: proto::Selection,
 520) -> Option<Selection<Anchor>> {
 521    Some(Selection {
 522        id: selection.id as usize,
 523        start: deserialize_anchor(buffer, selection.start?)?,
 524        end: deserialize_anchor(buffer, selection.end?)?,
 525        reversed: selection.reversed,
 526        goal: SelectionGoal::None,
 527    })
 528}
 529
 530fn deserialize_anchor(buffer: &MultiBufferSnapshot, anchor: proto::EditorAnchor) -> Option<Anchor> {
 531    let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
 532    Some(Anchor {
 533        excerpt_id,
 534        text_anchor: language::proto::deserialize_anchor(anchor.anchor?)?,
 535        buffer_id: buffer.buffer_id_for_excerpt(excerpt_id),
 536    })
 537}
 538
 539impl Item for Editor {
 540    type Event = EditorEvent;
 541
 542    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
 543        if let Ok(data) = data.downcast::<NavigationData>() {
 544            let newest_selection = self.selections.newest::<Point>(cx);
 545            let buffer = self.buffer.read(cx).read(cx);
 546            let offset = if buffer.can_resolve(&data.cursor_anchor) {
 547                data.cursor_anchor.to_point(&buffer)
 548            } else {
 549                buffer.clip_point(data.cursor_position, Bias::Left)
 550            };
 551
 552            let mut scroll_anchor = data.scroll_anchor;
 553            if !buffer.can_resolve(&scroll_anchor.anchor) {
 554                scroll_anchor.anchor = buffer.anchor_before(
 555                    buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
 556                );
 557            }
 558
 559            drop(buffer);
 560
 561            if newest_selection.head() == offset {
 562                false
 563            } else {
 564                let nav_history = self.nav_history.take();
 565                self.set_scroll_anchor(scroll_anchor, cx);
 566                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 567                    s.select_ranges([offset..offset])
 568                });
 569                self.nav_history = nav_history;
 570                true
 571            }
 572        } else {
 573            false
 574        }
 575    }
 576
 577    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
 578        let file_path = self
 579            .buffer()
 580            .read(cx)
 581            .as_singleton()?
 582            .read(cx)
 583            .file()
 584            .and_then(|f| f.as_local())?
 585            .abs_path(cx);
 586
 587        let file_path = file_path.compact().to_string_lossy().to_string();
 588
 589        Some(file_path.into())
 590    }
 591
 592    fn telemetry_event_text(&self) -> Option<&'static str> {
 593        None
 594    }
 595
 596    fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<SharedString> {
 597        let path = path_for_buffer(&self.buffer, detail, true, cx)?;
 598        Some(path.to_string_lossy().to_string().into())
 599    }
 600
 601    fn tab_content(&self, detail: Option<usize>, selected: bool, cx: &WindowContext) -> AnyElement {
 602        let git_status = if ItemSettings::get_global(cx).git_status {
 603            self.buffer()
 604                .read(cx)
 605                .as_singleton()
 606                .and_then(|buffer| buffer.read(cx).project_path(cx))
 607                .and_then(|path| self.project.as_ref()?.read(cx).entry_for_path(&path, cx))
 608                .and_then(|entry| entry.git_status())
 609        } else {
 610            None
 611        };
 612        let label_color = match git_status {
 613            Some(GitFileStatus::Added) => Color::Created,
 614            Some(GitFileStatus::Modified) => Color::Modified,
 615            Some(GitFileStatus::Conflict) => Color::Conflict,
 616            None => {
 617                if selected {
 618                    Color::Default
 619                } else {
 620                    Color::Muted
 621                }
 622            }
 623        };
 624
 625        let description = 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(Label::new(self.title(cx).to_string()).color(label_color))
 640            .when_some(description, |this, description| {
 641                this.child(
 642                    Label::new(description)
 643                        .size(LabelSize::XSmall)
 644                        .color(Color::Muted),
 645                )
 646            })
 647            .into_any_element()
 648    }
 649
 650    fn for_each_project_item(
 651        &self,
 652        cx: &AppContext,
 653        f: &mut dyn FnMut(EntityId, &dyn project::Item),
 654    ) {
 655        self.buffer
 656            .read(cx)
 657            .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
 658    }
 659
 660    fn is_singleton(&self, cx: &AppContext) -> bool {
 661        self.buffer.read(cx).is_singleton()
 662    }
 663
 664    fn clone_on_split(
 665        &self,
 666        _workspace_id: WorkspaceId,
 667        cx: &mut ViewContext<Self>,
 668    ) -> Option<View<Editor>>
 669    where
 670        Self: Sized,
 671    {
 672        Some(cx.new_view(|cx| self.clone(cx)))
 673    }
 674
 675    fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
 676        self.nav_history = Some(history);
 677    }
 678
 679    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 680        let selection = self.selections.newest_anchor();
 681        self.push_to_nav_history(selection.head(), None, cx);
 682    }
 683
 684    fn workspace_deactivated(&mut self, cx: &mut ViewContext<Self>) {
 685        self.hide_hovered_link(cx);
 686    }
 687
 688    fn is_dirty(&self, cx: &AppContext) -> bool {
 689        self.buffer().read(cx).read(cx).is_dirty()
 690    }
 691
 692    fn has_conflict(&self, cx: &AppContext) -> bool {
 693        self.buffer().read(cx).read(cx).has_conflict()
 694    }
 695
 696    fn can_save(&self, cx: &AppContext) -> bool {
 697        let buffer = &self.buffer().read(cx);
 698        if let Some(buffer) = buffer.as_singleton() {
 699            buffer.read(cx).project_path(cx).is_some()
 700        } else {
 701            true
 702        }
 703    }
 704
 705    fn save(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
 706        self.report_editor_event("save", None, cx);
 707        let buffers = self.buffer().clone().read(cx).all_buffers();
 708        cx.spawn(|this, mut cx| async move {
 709            this.update(&mut cx, |this, cx| {
 710                this.perform_format(project.clone(), FormatTrigger::Save, cx)
 711            })?
 712            .await?;
 713
 714            if buffers.len() == 1 {
 715                project
 716                    .update(&mut cx, |project, cx| project.save_buffers(buffers, cx))?
 717                    .await?;
 718            } else {
 719                // For multi-buffers, only save those ones that contain changes. For clean buffers
 720                // we simulate saving by calling `Buffer::did_save`, so that language servers or
 721                // other downstream listeners of save events get notified.
 722                let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
 723                    buffer
 724                        .update(&mut cx, |buffer, _| {
 725                            buffer.is_dirty() || buffer.has_conflict()
 726                        })
 727                        .unwrap_or(false)
 728                });
 729
 730                project
 731                    .update(&mut cx, |project, cx| {
 732                        project.save_buffers(dirty_buffers, cx)
 733                    })?
 734                    .await?;
 735                for buffer in clean_buffers {
 736                    buffer
 737                        .update(&mut cx, |buffer, cx| {
 738                            let version = buffer.saved_version().clone();
 739                            let fingerprint = buffer.saved_version_fingerprint();
 740                            let mtime = buffer.saved_mtime();
 741                            buffer.did_save(version, fingerprint, mtime, cx);
 742                        })
 743                        .ok();
 744                }
 745            }
 746
 747            Ok(())
 748        })
 749    }
 750
 751    fn save_as(
 752        &mut self,
 753        project: Model<Project>,
 754        abs_path: PathBuf,
 755        cx: &mut ViewContext<Self>,
 756    ) -> Task<Result<()>> {
 757        let buffer = self
 758            .buffer()
 759            .read(cx)
 760            .as_singleton()
 761            .expect("cannot call save_as on an excerpt list");
 762
 763        let file_extension = abs_path
 764            .extension()
 765            .map(|a| a.to_string_lossy().to_string());
 766        self.report_editor_event("save", file_extension, cx);
 767
 768        project.update(cx, |project, cx| {
 769            project.save_buffer_as(buffer, abs_path, cx)
 770        })
 771    }
 772
 773    fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
 774        let buffer = self.buffer().clone();
 775        let buffers = self.buffer.read(cx).all_buffers();
 776        let reload_buffers =
 777            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
 778        cx.spawn(|this, mut cx| async move {
 779            let transaction = reload_buffers.log_err().await;
 780            this.update(&mut cx, |editor, cx| {
 781                editor.request_autoscroll(Autoscroll::fit(), cx)
 782            })?;
 783            buffer
 784                .update(&mut cx, |buffer, cx| {
 785                    if let Some(transaction) = transaction {
 786                        if !buffer.is_singleton() {
 787                            buffer.push_transaction(&transaction.0, cx);
 788                        }
 789                    }
 790                })
 791                .ok();
 792            Ok(())
 793        })
 794    }
 795
 796    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 797        Some(Box::new(handle.clone()))
 798    }
 799
 800    fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<gpui::Point<Pixels>> {
 801        self.pixel_position_of_newest_cursor
 802    }
 803
 804    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 805        if self.show_breadcrumbs {
 806            ToolbarItemLocation::PrimaryLeft
 807        } else {
 808            ToolbarItemLocation::Hidden
 809        }
 810    }
 811
 812    fn breadcrumbs(&self, variant: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 813        let cursor = self.selections.newest_anchor().head();
 814        let multibuffer = &self.buffer().read(cx);
 815        let (buffer_id, symbols) =
 816            multibuffer.symbols_containing(cursor, Some(&variant.syntax()), cx)?;
 817        let buffer = multibuffer.buffer(buffer_id)?;
 818
 819        let buffer = buffer.read(cx);
 820        let filename = buffer
 821            .snapshot()
 822            .resolve_file_path(
 823                cx,
 824                self.project
 825                    .as_ref()
 826                    .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 827                    .unwrap_or_default(),
 828            )
 829            .map(|path| path.to_string_lossy().to_string())
 830            .unwrap_or_else(|| "untitled".to_string());
 831
 832        let mut breadcrumbs = vec![BreadcrumbText {
 833            text: filename,
 834            highlights: None,
 835        }];
 836        breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
 837            text: symbol.text,
 838            highlights: Some(symbol.highlight_ranges),
 839        }));
 840        Some(breadcrumbs)
 841    }
 842
 843    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 844        let workspace_id = workspace.database_id();
 845        let item_id = cx.view().item_id().as_u64() as ItemId;
 846        self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
 847
 848        fn serialize(
 849            buffer: Model<Buffer>,
 850            workspace_id: WorkspaceId,
 851            item_id: ItemId,
 852            cx: &mut AppContext,
 853        ) {
 854            if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
 855                let path = file.abs_path(cx);
 856
 857                cx.background_executor()
 858                    .spawn(async move {
 859                        DB.save_path(item_id, workspace_id, path.clone())
 860                            .await
 861                            .log_err()
 862                    })
 863                    .detach();
 864            }
 865        }
 866
 867        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 868            serialize(buffer.clone(), workspace_id, item_id, cx);
 869
 870            cx.subscribe(&buffer, |this, buffer, event, cx| {
 871                if let Some((_, workspace_id)) = this.workspace.as_ref() {
 872                    if let language::Event::FileHandleChanged = event {
 873                        serialize(
 874                            buffer,
 875                            *workspace_id,
 876                            cx.view().item_id().as_u64() as ItemId,
 877                            cx,
 878                        );
 879                    }
 880                }
 881            })
 882            .detach();
 883        }
 884    }
 885
 886    fn serialized_item_kind() -> Option<&'static str> {
 887        Some("Editor")
 888    }
 889
 890    fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
 891        match event {
 892            EditorEvent::Closed => f(ItemEvent::CloseItem),
 893
 894            EditorEvent::Saved | EditorEvent::TitleChanged => {
 895                f(ItemEvent::UpdateTab);
 896                f(ItemEvent::UpdateBreadcrumbs);
 897            }
 898
 899            EditorEvent::Reparsed => {
 900                f(ItemEvent::UpdateBreadcrumbs);
 901            }
 902
 903            EditorEvent::SelectionsChanged { local } if *local => {
 904                f(ItemEvent::UpdateBreadcrumbs);
 905            }
 906
 907            EditorEvent::DirtyChanged => {
 908                f(ItemEvent::UpdateTab);
 909            }
 910
 911            EditorEvent::BufferEdited => {
 912                f(ItemEvent::Edit);
 913                f(ItemEvent::UpdateBreadcrumbs);
 914            }
 915
 916            EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
 917                f(ItemEvent::Edit);
 918            }
 919
 920            _ => {}
 921        }
 922    }
 923
 924    fn deserialize(
 925        project: Model<Project>,
 926        _workspace: WeakView<Workspace>,
 927        workspace_id: workspace::WorkspaceId,
 928        item_id: ItemId,
 929        cx: &mut ViewContext<Pane>,
 930    ) -> Task<Result<View<Self>>> {
 931        let project_item: Result<_> = project.update(cx, |project, cx| {
 932            // Look up the path with this key associated, create a self with that path
 933            let path = DB
 934                .get_path(item_id, workspace_id)?
 935                .context("No path stored for this editor")?;
 936
 937            let (worktree, path) = project
 938                .find_local_worktree(&path, cx)
 939                .with_context(|| format!("No worktree for path: {path:?}"))?;
 940            let project_path = ProjectPath {
 941                worktree_id: worktree.read(cx).id(),
 942                path: path.into(),
 943            };
 944
 945            Ok(project.open_path(project_path, cx))
 946        });
 947
 948        project_item
 949            .map(|project_item| {
 950                cx.spawn(|pane, mut cx| async move {
 951                    let (_, project_item) = project_item.await?;
 952                    let buffer = project_item
 953                        .downcast::<Buffer>()
 954                        .map_err(|_| anyhow!("Project item at stored path was not a buffer"))?;
 955                    pane.update(&mut cx, |_, cx| {
 956                        cx.new_view(|cx| {
 957                            let mut editor = Editor::for_buffer(buffer, Some(project), cx);
 958
 959                            editor.read_scroll_position_from_db(item_id, workspace_id, cx);
 960                            editor
 961                        })
 962                    })
 963                })
 964            })
 965            .unwrap_or_else(|error| Task::ready(Err(error)))
 966    }
 967}
 968
 969impl ProjectItem for Editor {
 970    type Item = Buffer;
 971
 972    fn for_project_item(
 973        project: Model<Project>,
 974        buffer: Model<Buffer>,
 975        cx: &mut ViewContext<Self>,
 976    ) -> Self {
 977        Self::for_buffer(buffer, Some(project), cx)
 978    }
 979}
 980
 981impl EventEmitter<SearchEvent> for Editor {}
 982
 983pub(crate) enum BufferSearchHighlights {}
 984impl SearchableItem for Editor {
 985    type Match = Range<Anchor>;
 986
 987    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
 988        self.clear_background_highlights::<BufferSearchHighlights>(cx);
 989    }
 990
 991    fn update_matches(&mut self, matches: Vec<Range<Anchor>>, cx: &mut ViewContext<Self>) {
 992        self.highlight_background::<BufferSearchHighlights>(
 993            matches,
 994            |theme| theme.search_match_background,
 995            cx,
 996        );
 997    }
 998
 999    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
1000        let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
1001        let snapshot = &self.snapshot(cx).buffer_snapshot;
1002        let selection = self.selections.newest::<usize>(cx);
1003
1004        match setting {
1005            SeedQuerySetting::Never => String::new(),
1006            SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
1007                snapshot
1008                    .text_for_range(selection.start..selection.end)
1009                    .collect()
1010            }
1011            SeedQuerySetting::Selection => String::new(),
1012            SeedQuerySetting::Always => {
1013                let (range, kind) = snapshot.surrounding_word(selection.start);
1014                if kind == Some(CharKind::Word) {
1015                    let text: String = snapshot.text_for_range(range).collect();
1016                    if !text.trim().is_empty() {
1017                        return text;
1018                    }
1019                }
1020                String::new()
1021            }
1022        }
1023    }
1024
1025    fn activate_match(
1026        &mut self,
1027        index: usize,
1028        matches: Vec<Range<Anchor>>,
1029        cx: &mut ViewContext<Self>,
1030    ) {
1031        self.unfold_ranges([matches[index].clone()], false, true, cx);
1032        let range = self.range_for_match(&matches[index]);
1033        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
1034            s.select_ranges([range]);
1035        })
1036    }
1037
1038    fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
1039        self.unfold_ranges(matches.clone(), false, false, cx);
1040        let mut ranges = Vec::new();
1041        for m in &matches {
1042            ranges.push(self.range_for_match(&m))
1043        }
1044        self.change_selections(None, cx, |s| s.select_ranges(ranges));
1045    }
1046    fn replace(
1047        &mut self,
1048        identifier: &Self::Match,
1049        query: &SearchQuery,
1050        cx: &mut ViewContext<Self>,
1051    ) {
1052        let text = self.buffer.read(cx);
1053        let text = text.snapshot(cx);
1054        let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1055        let text: Cow<_> = if text.len() == 1 {
1056            text.first().cloned().unwrap().into()
1057        } else {
1058            let joined_chunks = text.join("");
1059            joined_chunks.into()
1060        };
1061
1062        if let Some(replacement) = query.replacement_for(&text) {
1063            self.transact(cx, |this, cx| {
1064                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1065            });
1066        }
1067    }
1068    fn match_index_for_direction(
1069        &mut self,
1070        matches: &Vec<Range<Anchor>>,
1071        current_index: usize,
1072        direction: Direction,
1073        count: usize,
1074        cx: &mut ViewContext<Self>,
1075    ) -> usize {
1076        let buffer = self.buffer().read(cx).snapshot(cx);
1077        let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1078            self.selections.newest_anchor().head()
1079        } else {
1080            matches[current_index].start
1081        };
1082
1083        let mut count = count % matches.len();
1084        if count == 0 {
1085            return current_index;
1086        }
1087        match direction {
1088            Direction::Next => {
1089                if matches[current_index]
1090                    .start
1091                    .cmp(&current_index_position, &buffer)
1092                    .is_gt()
1093                {
1094                    count = count - 1
1095                }
1096
1097                (current_index + count) % matches.len()
1098            }
1099            Direction::Prev => {
1100                if matches[current_index]
1101                    .end
1102                    .cmp(&current_index_position, &buffer)
1103                    .is_lt()
1104                {
1105                    count = count - 1;
1106                }
1107
1108                if current_index >= count {
1109                    current_index - count
1110                } else {
1111                    matches.len() - (count - current_index)
1112                }
1113            }
1114        }
1115    }
1116
1117    fn find_matches(
1118        &mut self,
1119        query: Arc<project::search::SearchQuery>,
1120        cx: &mut ViewContext<Self>,
1121    ) -> Task<Vec<Range<Anchor>>> {
1122        let buffer = self.buffer().read(cx).snapshot(cx);
1123        cx.background_executor().spawn(async move {
1124            let mut ranges = Vec::new();
1125            if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
1126                ranges.extend(
1127                    query
1128                        .search(excerpt_buffer, None)
1129                        .await
1130                        .into_iter()
1131                        .map(|range| {
1132                            buffer.anchor_after(range.start)..buffer.anchor_before(range.end)
1133                        }),
1134                );
1135            } else {
1136                for excerpt in buffer.excerpt_boundaries_in_range(0..buffer.len()) {
1137                    let excerpt_range = excerpt.range.context.to_offset(&excerpt.buffer);
1138                    ranges.extend(
1139                        query
1140                            .search(&excerpt.buffer, Some(excerpt_range.clone()))
1141                            .await
1142                            .into_iter()
1143                            .map(|range| {
1144                                let start = excerpt
1145                                    .buffer
1146                                    .anchor_after(excerpt_range.start + range.start);
1147                                let end = excerpt
1148                                    .buffer
1149                                    .anchor_before(excerpt_range.start + range.end);
1150                                buffer.anchor_in_excerpt(excerpt.id, start)
1151                                    ..buffer.anchor_in_excerpt(excerpt.id, end)
1152                            }),
1153                    );
1154                }
1155            }
1156            ranges
1157        })
1158    }
1159
1160    fn active_match_index(
1161        &mut self,
1162        matches: Vec<Range<Anchor>>,
1163        cx: &mut ViewContext<Self>,
1164    ) -> Option<usize> {
1165        active_match_index(
1166            &matches,
1167            &self.selections.newest_anchor().head(),
1168            &self.buffer().read(cx).snapshot(cx),
1169        )
1170    }
1171}
1172
1173pub fn active_match_index(
1174    ranges: &[Range<Anchor>],
1175    cursor: &Anchor,
1176    buffer: &MultiBufferSnapshot,
1177) -> Option<usize> {
1178    if ranges.is_empty() {
1179        None
1180    } else {
1181        match ranges.binary_search_by(|probe| {
1182            if probe.end.cmp(cursor, &*buffer).is_lt() {
1183                Ordering::Less
1184            } else if probe.start.cmp(cursor, &*buffer).is_gt() {
1185                Ordering::Greater
1186            } else {
1187                Ordering::Equal
1188            }
1189        }) {
1190            Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1191        }
1192    }
1193}
1194
1195pub struct CursorPosition {
1196    position: Option<Point>,
1197    selected_count: usize,
1198    _observe_active_editor: Option<Subscription>,
1199}
1200
1201impl Default for CursorPosition {
1202    fn default() -> Self {
1203        Self::new()
1204    }
1205}
1206
1207impl CursorPosition {
1208    pub fn new() -> Self {
1209        Self {
1210            position: None,
1211            selected_count: 0,
1212            _observe_active_editor: None,
1213        }
1214    }
1215
1216    fn update_position(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
1217        let editor = editor.read(cx);
1218        let buffer = editor.buffer().read(cx).snapshot(cx);
1219
1220        self.selected_count = 0;
1221        let mut last_selection: Option<Selection<usize>> = None;
1222        for selection in editor.selections.all::<usize>(cx) {
1223            self.selected_count += selection.end - selection.start;
1224            if last_selection
1225                .as_ref()
1226                .map_or(true, |last_selection| selection.id > last_selection.id)
1227            {
1228                last_selection = Some(selection);
1229            }
1230        }
1231        self.position = last_selection.map(|s| s.head().to_point(&buffer));
1232
1233        cx.notify();
1234    }
1235}
1236
1237impl Render for CursorPosition {
1238    fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
1239        div().when_some(self.position, |el, position| {
1240            let mut text = format!(
1241                "{}{FILE_ROW_COLUMN_DELIMITER}{}",
1242                position.row + 1,
1243                position.column + 1
1244            );
1245            if self.selected_count > 0 {
1246                write!(text, " ({} selected)", self.selected_count).unwrap();
1247            }
1248
1249            el.child(Label::new(text).size(LabelSize::Small))
1250        })
1251    }
1252}
1253
1254impl StatusItemView for CursorPosition {
1255    fn set_active_pane_item(
1256        &mut self,
1257        active_pane_item: Option<&dyn ItemHandle>,
1258        cx: &mut ViewContext<Self>,
1259    ) {
1260        if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
1261            self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
1262            self.update_position(editor, cx);
1263        } else {
1264            self.position = None;
1265            self._observe_active_editor = None;
1266        }
1267
1268        cx.notify();
1269    }
1270}
1271
1272fn path_for_buffer<'a>(
1273    buffer: &Model<MultiBuffer>,
1274    height: usize,
1275    include_filename: bool,
1276    cx: &'a AppContext,
1277) -> Option<Cow<'a, Path>> {
1278    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1279    path_for_file(file.as_ref(), height, include_filename, cx)
1280}
1281
1282fn path_for_file<'a>(
1283    file: &'a dyn language::File,
1284    mut height: usize,
1285    include_filename: bool,
1286    cx: &'a AppContext,
1287) -> Option<Cow<'a, Path>> {
1288    // Ensure we always render at least the filename.
1289    height += 1;
1290
1291    let mut prefix = file.path().as_ref();
1292    while height > 0 {
1293        if let Some(parent) = prefix.parent() {
1294            prefix = parent;
1295            height -= 1;
1296        } else {
1297            break;
1298        }
1299    }
1300
1301    // Here we could have just always used `full_path`, but that is very
1302    // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1303    // traversed all the way up to the worktree's root.
1304    if height > 0 {
1305        let full_path = file.full_path(cx);
1306        if include_filename {
1307            Some(full_path.into())
1308        } else {
1309            Some(full_path.parent()?.to_path_buf().into())
1310        }
1311    } else {
1312        let mut path = file.path().strip_prefix(prefix).ok()?;
1313        if !include_filename {
1314            path = path.parent()?;
1315        }
1316        Some(path.into())
1317    }
1318}
1319
1320#[cfg(test)]
1321mod tests {
1322    use super::*;
1323    use gpui::AppContext;
1324    use std::{
1325        path::{Path, PathBuf},
1326        sync::Arc,
1327        time::SystemTime,
1328    };
1329
1330    #[gpui::test]
1331    fn test_path_for_file(cx: &mut AppContext) {
1332        let file = TestFile {
1333            path: Path::new("").into(),
1334            full_path: PathBuf::from(""),
1335        };
1336        assert_eq!(path_for_file(&file, 0, false, cx), None);
1337    }
1338
1339    struct TestFile {
1340        path: Arc<Path>,
1341        full_path: PathBuf,
1342    }
1343
1344    impl language::File for TestFile {
1345        fn path(&self) -> &Arc<Path> {
1346            &self.path
1347        }
1348
1349        fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
1350            self.full_path.clone()
1351        }
1352
1353        fn as_local(&self) -> Option<&dyn language::LocalFile> {
1354            unimplemented!()
1355        }
1356
1357        fn mtime(&self) -> SystemTime {
1358            unimplemented!()
1359        }
1360
1361        fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
1362            unimplemented!()
1363        }
1364
1365        fn worktree_id(&self) -> usize {
1366            0
1367        }
1368
1369        fn is_deleted(&self) -> bool {
1370            unimplemented!()
1371        }
1372
1373        fn as_any(&self) -> &dyn std::any::Any {
1374            unimplemented!()
1375        }
1376
1377        fn to_proto(&self) -> rpc::proto::File {
1378            unimplemented!()
1379        }
1380
1381        fn is_private(&self) -> bool {
1382            false
1383        }
1384    }
1385}