items.rs

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