items.rs

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