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