items.rs

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