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