item.rs

   1use crate::{
   2    pane::{self, Pane},
   3    persistence::model::ItemId,
   4    searchable::SearchableItemHandle,
   5    workspace_settings::{AutosaveSetting, WorkspaceSettings},
   6    DelayedDebouncedEditAction, FollowableItemBuilders, ItemNavHistory, ToolbarItemLocation,
   7    ViewId, Workspace, WorkspaceId,
   8};
   9use anyhow::Result;
  10use client2::{
  11    proto::{self, PeerId},
  12    Client,
  13};
  14use gpui::{
  15    AnyElement, AnyView, AppContext, Entity, EntityId, EventEmitter, FocusHandle, FocusableView,
  16    HighlightStyle, Model, Pixels, Point, SharedString, Task, View, ViewContext, WeakView,
  17    WindowContext,
  18};
  19use project2::{Project, ProjectEntryId, ProjectPath};
  20use schemars::JsonSchema;
  21use serde::{Deserialize, Serialize};
  22use settings2::Settings;
  23use smallvec::SmallVec;
  24use std::{
  25    any::{Any, TypeId},
  26    cell::RefCell,
  27    ops::Range,
  28    path::PathBuf,
  29    rc::Rc,
  30    sync::{
  31        atomic::{AtomicBool, Ordering},
  32        Arc,
  33    },
  34    time::Duration,
  35};
  36use theme2::Theme;
  37
  38#[derive(Deserialize)]
  39pub struct ItemSettings {
  40    pub git_status: bool,
  41    pub close_position: ClosePosition,
  42}
  43
  44#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  45#[serde(rename_all = "lowercase")]
  46pub enum ClosePosition {
  47    Left,
  48    #[default]
  49    Right,
  50}
  51
  52impl ClosePosition {
  53    pub fn right(&self) -> bool {
  54        match self {
  55            ClosePosition::Left => false,
  56            ClosePosition::Right => true,
  57        }
  58    }
  59}
  60
  61#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  62pub struct ItemSettingsContent {
  63    git_status: Option<bool>,
  64    close_position: Option<ClosePosition>,
  65}
  66
  67impl Settings for ItemSettings {
  68    const KEY: Option<&'static str> = Some("tabs");
  69
  70    type FileContent = ItemSettingsContent;
  71
  72    fn load(
  73        default_value: &Self::FileContent,
  74        user_values: &[&Self::FileContent],
  75        _: &mut AppContext,
  76    ) -> Result<Self> {
  77        Self::load_via_json_merge(default_value, user_values)
  78    }
  79}
  80
  81#[derive(Eq, PartialEq, Hash, Debug)]
  82pub enum ItemEvent {
  83    CloseItem,
  84    UpdateTab,
  85    UpdateBreadcrumbs,
  86    Edit,
  87}
  88
  89// TODO: Combine this with existing HighlightedText struct?
  90pub struct BreadcrumbText {
  91    pub text: String,
  92    pub highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
  93}
  94
  95pub trait Item: FocusableView + EventEmitter<ItemEvent> {
  96    fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
  97    fn workspace_deactivated(&mut self, _: &mut ViewContext<Self>) {}
  98    fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
  99        false
 100    }
 101    fn tab_tooltip_text(&self, _: &AppContext) -> Option<SharedString> {
 102        None
 103    }
 104    fn tab_description(&self, _: usize, _: &AppContext) -> Option<SharedString> {
 105        None
 106    }
 107    fn tab_content<V: 'static>(&self, detail: Option<usize>, cx: &AppContext) -> AnyElement<V>;
 108
 109    /// (model id, Item)
 110    fn for_each_project_item(
 111        &self,
 112        _: &AppContext,
 113        _: &mut dyn FnMut(EntityId, &dyn project2::Item),
 114    ) {
 115    }
 116    fn is_singleton(&self, _cx: &AppContext) -> bool {
 117        false
 118    }
 119    fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>) {}
 120    fn clone_on_split(
 121        &self,
 122        _workspace_id: WorkspaceId,
 123        _: &mut ViewContext<Self>,
 124    ) -> Option<View<Self>>
 125    where
 126        Self: Sized,
 127    {
 128        None
 129    }
 130    fn is_dirty(&self, _: &AppContext) -> bool {
 131        false
 132    }
 133    fn has_conflict(&self, _: &AppContext) -> bool {
 134        false
 135    }
 136    fn can_save(&self, _cx: &AppContext) -> bool {
 137        false
 138    }
 139    fn save(&mut self, _project: Model<Project>, _cx: &mut ViewContext<Self>) -> Task<Result<()>> {
 140        unimplemented!("save() must be implemented if can_save() returns true")
 141    }
 142    fn save_as(
 143        &mut self,
 144        _project: Model<Project>,
 145        _abs_path: PathBuf,
 146        _cx: &mut ViewContext<Self>,
 147    ) -> Task<Result<()>> {
 148        unimplemented!("save_as() must be implemented if can_save() returns true")
 149    }
 150    fn reload(
 151        &mut self,
 152        _project: Model<Project>,
 153        _cx: &mut ViewContext<Self>,
 154    ) -> Task<Result<()>> {
 155        unimplemented!("reload() must be implemented if can_save() returns true")
 156    }
 157
 158    fn act_as_type<'a>(
 159        &'a self,
 160        type_id: TypeId,
 161        self_handle: &'a View<Self>,
 162        _: &'a AppContext,
 163    ) -> Option<AnyView> {
 164        if TypeId::of::<Self>() == type_id {
 165            Some(self_handle.clone().into())
 166        } else {
 167            None
 168        }
 169    }
 170
 171    fn as_searchable(&self, _: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 172        None
 173    }
 174
 175    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 176        ToolbarItemLocation::Hidden
 177    }
 178
 179    fn breadcrumbs(&self, _theme: &Theme, _cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 180        None
 181    }
 182
 183    fn added_to_workspace(&mut self, _workspace: &mut Workspace, _cx: &mut ViewContext<Self>) {}
 184
 185    fn serialized_item_kind() -> Option<&'static str> {
 186        None
 187    }
 188
 189    fn deserialize(
 190        _project: Model<Project>,
 191        _workspace: WeakView<Workspace>,
 192        _workspace_id: WorkspaceId,
 193        _item_id: ItemId,
 194        _cx: &mut ViewContext<Pane>,
 195    ) -> Task<Result<View<Self>>> {
 196        unimplemented!(
 197            "deserialize() must be implemented if serialized_item_kind() returns Some(_)"
 198        )
 199    }
 200    fn show_toolbar(&self) -> bool {
 201        true
 202    }
 203    fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<Point<Pixels>> {
 204        None
 205    }
 206}
 207
 208pub trait ItemHandle: 'static + Send {
 209    fn focus_handle(&self, cx: &WindowContext) -> FocusHandle;
 210    fn subscribe_to_item_events(
 211        &self,
 212        cx: &mut WindowContext,
 213        handler: Box<dyn Fn(&ItemEvent, &mut WindowContext) + Send>,
 214    ) -> gpui::Subscription;
 215    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString>;
 216    fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString>;
 217    fn tab_content(&self, detail: Option<usize>, cx: &AppContext) -> AnyElement<Pane>;
 218    fn dragged_tab_content(&self, detail: Option<usize>, cx: &AppContext) -> AnyElement<Workspace>;
 219    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 220    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;
 221    fn project_item_model_ids(&self, cx: &AppContext) -> SmallVec<[EntityId; 3]>;
 222    fn for_each_project_item(
 223        &self,
 224        _: &AppContext,
 225        _: &mut dyn FnMut(EntityId, &dyn project2::Item),
 226    );
 227    fn is_singleton(&self, cx: &AppContext) -> bool;
 228    fn boxed_clone(&self) -> Box<dyn ItemHandle>;
 229    fn clone_on_split(
 230        &self,
 231        workspace_id: WorkspaceId,
 232        cx: &mut WindowContext,
 233    ) -> Option<Box<dyn ItemHandle>>;
 234    fn added_to_pane(
 235        &self,
 236        workspace: &mut Workspace,
 237        pane: View<Pane>,
 238        cx: &mut ViewContext<Workspace>,
 239    );
 240    fn deactivated(&self, cx: &mut WindowContext);
 241    fn workspace_deactivated(&self, cx: &mut WindowContext);
 242    fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool;
 243    fn item_id(&self) -> EntityId;
 244    fn to_any(&self) -> AnyView;
 245    fn is_dirty(&self, cx: &AppContext) -> bool;
 246    fn has_conflict(&self, cx: &AppContext) -> bool;
 247    fn can_save(&self, cx: &AppContext) -> bool;
 248    fn save(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>>;
 249    fn save_as(
 250        &self,
 251        project: Model<Project>,
 252        abs_path: PathBuf,
 253        cx: &mut WindowContext,
 254    ) -> Task<Result<()>>;
 255    fn reload(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>>;
 256    fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyView>;
 257    fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
 258    fn on_release(
 259        &self,
 260        cx: &mut AppContext,
 261        callback: Box<dyn FnOnce(&mut AppContext) + Send>,
 262    ) -> gpui::Subscription;
 263    fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>>;
 264    fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation;
 265    fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>>;
 266    fn serialized_item_kind(&self) -> Option<&'static str>;
 267    fn show_toolbar(&self, cx: &AppContext) -> bool;
 268    fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Point<Pixels>>;
 269}
 270
 271pub trait WeakItemHandle: Send + Sync {
 272    fn id(&self) -> EntityId;
 273    fn upgrade(&self) -> Option<Box<dyn ItemHandle>>;
 274}
 275
 276impl dyn ItemHandle {
 277    pub fn downcast<V: 'static>(&self) -> Option<View<V>> {
 278        self.to_any().downcast().ok()
 279    }
 280
 281    pub fn act_as<V: 'static>(&self, cx: &AppContext) -> Option<View<V>> {
 282        self.act_as_type(TypeId::of::<V>(), cx)
 283            .and_then(|t| t.downcast().ok())
 284    }
 285}
 286
 287impl<T: Item> ItemHandle for View<T> {
 288    fn focus_handle(&self, cx: &WindowContext) -> FocusHandle {
 289        self.focus_handle(cx)
 290    }
 291
 292    fn subscribe_to_item_events(
 293        &self,
 294        cx: &mut WindowContext,
 295        handler: Box<dyn Fn(&ItemEvent, &mut WindowContext) + Send>,
 296    ) -> gpui::Subscription {
 297        cx.subscribe(self, move |_, event, cx| {
 298            handler(event, cx);
 299        })
 300    }
 301
 302    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
 303        self.read(cx).tab_tooltip_text(cx)
 304    }
 305
 306    fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString> {
 307        self.read(cx).tab_description(detail, cx)
 308    }
 309
 310    fn tab_content(&self, detail: Option<usize>, cx: &AppContext) -> AnyElement<Pane> {
 311        self.read(cx).tab_content(detail, cx)
 312    }
 313
 314    fn dragged_tab_content(&self, detail: Option<usize>, cx: &AppContext) -> AnyElement<Workspace> {
 315        self.read(cx).tab_content(detail, cx)
 316    }
 317
 318    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
 319        let this = self.read(cx);
 320        let mut result = None;
 321        if this.is_singleton(cx) {
 322            this.for_each_project_item(cx, &mut |_, item| {
 323                result = item.project_path(cx);
 324            });
 325        }
 326        result
 327    }
 328
 329    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
 330        let mut result = SmallVec::new();
 331        self.read(cx).for_each_project_item(cx, &mut |_, item| {
 332            if let Some(id) = item.entry_id(cx) {
 333                result.push(id);
 334            }
 335        });
 336        result
 337    }
 338
 339    fn project_item_model_ids(&self, cx: &AppContext) -> SmallVec<[EntityId; 3]> {
 340        let mut result = SmallVec::new();
 341        self.read(cx).for_each_project_item(cx, &mut |id, _| {
 342            result.push(id);
 343        });
 344        result
 345    }
 346
 347    fn for_each_project_item(
 348        &self,
 349        cx: &AppContext,
 350        f: &mut dyn FnMut(EntityId, &dyn project2::Item),
 351    ) {
 352        self.read(cx).for_each_project_item(cx, f)
 353    }
 354
 355    fn is_singleton(&self, cx: &AppContext) -> bool {
 356        self.read(cx).is_singleton(cx)
 357    }
 358
 359    fn boxed_clone(&self) -> Box<dyn ItemHandle> {
 360        Box::new(self.clone())
 361    }
 362
 363    fn clone_on_split(
 364        &self,
 365        workspace_id: WorkspaceId,
 366        cx: &mut WindowContext,
 367    ) -> Option<Box<dyn ItemHandle>> {
 368        self.update(cx, |item, cx| item.clone_on_split(workspace_id, cx))
 369            .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
 370    }
 371
 372    fn added_to_pane(
 373        &self,
 374        workspace: &mut Workspace,
 375        pane: View<Pane>,
 376        cx: &mut ViewContext<Workspace>,
 377    ) {
 378        let history = pane.read(cx).nav_history_for_item(self);
 379        self.update(cx, |this, cx| {
 380            this.set_nav_history(history, cx);
 381            this.added_to_workspace(workspace, cx);
 382        });
 383
 384        if let Some(followed_item) = self.to_followable_item_handle(cx) {
 385            if let Some(message) = followed_item.to_state_proto(cx) {
 386                workspace.update_followers(
 387                    followed_item.is_project_item(cx),
 388                    proto::update_followers::Variant::CreateView(proto::View {
 389                        id: followed_item
 390                            .remote_id(&workspace.app_state.client, cx)
 391                            .map(|id| id.to_proto()),
 392                        variant: Some(message),
 393                        leader_id: workspace.leader_for_pane(&pane),
 394                    }),
 395                    cx,
 396                );
 397            }
 398        }
 399
 400        if workspace
 401            .panes_by_item
 402            .insert(self.item_id(), pane.downgrade())
 403            .is_none()
 404        {
 405            let mut pending_autosave = DelayedDebouncedEditAction::new();
 406            let pending_update = Rc::new(RefCell::new(None));
 407            let pending_update_scheduled = Arc::new(AtomicBool::new(false));
 408
 409            let mut event_subscription =
 410                Some(cx.subscribe(self, move |workspace, item, event, cx| {
 411                    let pane = if let Some(pane) = workspace
 412                        .panes_by_item
 413                        .get(&item.item_id())
 414                        .and_then(|pane| pane.upgrade())
 415                    {
 416                        pane
 417                    } else {
 418                        log::error!("unexpected item event after pane was dropped");
 419                        return;
 420                    };
 421
 422                    if let Some(item) = item.to_followable_item_handle(cx) {
 423                        let is_project_item = item.is_project_item(cx);
 424                        let leader_id = workspace.leader_for_pane(&pane);
 425
 426                        let follow_event = item.to_follow_event(event);
 427                        if leader_id.is_some()
 428                            && matches!(follow_event, Some(FollowEvent::Unfollow))
 429                        {
 430                            workspace.unfollow(&pane, cx);
 431                        }
 432
 433                        if item.add_event_to_update_proto(
 434                            event,
 435                            &mut *pending_update.borrow_mut(),
 436                            cx,
 437                        ) && !pending_update_scheduled.load(Ordering::SeqCst)
 438                        {
 439                            pending_update_scheduled.store(true, Ordering::SeqCst);
 440                            cx.on_next_frame({
 441                                let pending_update = pending_update.clone();
 442                                let pending_update_scheduled = pending_update_scheduled.clone();
 443                                move |this, cx| {
 444                                    pending_update_scheduled.store(false, Ordering::SeqCst);
 445                                    this.update_followers(
 446                                        is_project_item,
 447                                        proto::update_followers::Variant::UpdateView(
 448                                            proto::UpdateView {
 449                                                id: item
 450                                                    .remote_id(&this.app_state.client, cx)
 451                                                    .map(|id| id.to_proto()),
 452                                                variant: pending_update.borrow_mut().take(),
 453                                                leader_id,
 454                                            },
 455                                        ),
 456                                        cx,
 457                                    );
 458                                }
 459                            });
 460                        }
 461                    }
 462
 463                    match event {
 464                        ItemEvent::CloseItem => {
 465                            pane.update(cx, |pane, cx| {
 466                                pane.close_item_by_id(item.item_id(), crate::SaveIntent::Close, cx)
 467                            })
 468                            .detach_and_log_err(cx);
 469                            return;
 470                        }
 471
 472                        ItemEvent::UpdateTab => {
 473                            pane.update(cx, |_, cx| {
 474                                cx.emit(pane::Event::ChangeItemTitle);
 475                                cx.notify();
 476                            });
 477                        }
 478
 479                        ItemEvent::Edit => {
 480                            let autosave = WorkspaceSettings::get_global(cx).autosave;
 481                            if let AutosaveSetting::AfterDelay { milliseconds } = autosave {
 482                                let delay = Duration::from_millis(milliseconds);
 483                                let item = item.clone();
 484                                pending_autosave.fire_new(delay, cx, move |workspace, cx| {
 485                                    Pane::autosave_item(&item, workspace.project().clone(), cx)
 486                                });
 487                            }
 488                        }
 489
 490                        _ => {}
 491                    }
 492                }));
 493
 494            // todo!()
 495            // cx.observe_focus(self, move |workspace, item, focused, cx| {
 496            //     if !focused
 497            //         && WorkspaceSettings::get_global(cx).autosave == AutosaveSetting::OnFocusChange
 498            //     {
 499            //         Pane::autosave_item(&item, workspace.project.clone(), cx)
 500            //             .detach_and_log_err(cx);
 501            //     }
 502            // })
 503            // .detach();
 504
 505            let item_id = self.item_id();
 506            cx.observe_release(self, move |workspace, _, _| {
 507                workspace.panes_by_item.remove(&item_id);
 508                event_subscription.take();
 509            })
 510            .detach();
 511        }
 512
 513        cx.defer(|workspace, cx| {
 514            workspace.serialize_workspace(cx);
 515        });
 516    }
 517
 518    fn deactivated(&self, cx: &mut WindowContext) {
 519        self.update(cx, |this, cx| this.deactivated(cx));
 520    }
 521
 522    fn workspace_deactivated(&self, cx: &mut WindowContext) {
 523        self.update(cx, |this, cx| this.workspace_deactivated(cx));
 524    }
 525
 526    fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool {
 527        self.update(cx, |this, cx| this.navigate(data, cx))
 528    }
 529
 530    fn item_id(&self) -> EntityId {
 531        self.entity_id()
 532    }
 533
 534    fn to_any(&self) -> AnyView {
 535        self.clone().into()
 536    }
 537
 538    fn is_dirty(&self, cx: &AppContext) -> bool {
 539        self.read(cx).is_dirty(cx)
 540    }
 541
 542    fn has_conflict(&self, cx: &AppContext) -> bool {
 543        self.read(cx).has_conflict(cx)
 544    }
 545
 546    fn can_save(&self, cx: &AppContext) -> bool {
 547        self.read(cx).can_save(cx)
 548    }
 549
 550    fn save(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
 551        self.update(cx, |item, cx| item.save(project, cx))
 552    }
 553
 554    fn save_as(
 555        &self,
 556        project: Model<Project>,
 557        abs_path: PathBuf,
 558        cx: &mut WindowContext,
 559    ) -> Task<anyhow::Result<()>> {
 560        self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
 561    }
 562
 563    fn reload(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
 564        self.update(cx, |item, cx| item.reload(project, cx))
 565    }
 566
 567    fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a AppContext) -> Option<AnyView> {
 568        self.read(cx).act_as_type(type_id, self, cx)
 569    }
 570
 571    fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
 572        if cx.has_global::<FollowableItemBuilders>() {
 573            let builders = cx.global::<FollowableItemBuilders>();
 574            let item = self.to_any();
 575            Some(builders.get(&item.entity_type())?.1(&item))
 576        } else {
 577            None
 578        }
 579    }
 580
 581    fn on_release(
 582        &self,
 583        cx: &mut AppContext,
 584        callback: Box<dyn FnOnce(&mut AppContext) + Send>,
 585    ) -> gpui::Subscription {
 586        cx.observe_release(self, move |_, cx| callback(cx))
 587    }
 588
 589    fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {
 590        self.read(cx).as_searchable(self)
 591    }
 592
 593    fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {
 594        self.read(cx).breadcrumb_location()
 595    }
 596
 597    fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 598        self.read(cx).breadcrumbs(theme, cx)
 599    }
 600
 601    fn serialized_item_kind(&self) -> Option<&'static str> {
 602        T::serialized_item_kind()
 603    }
 604
 605    fn show_toolbar(&self, cx: &AppContext) -> bool {
 606        self.read(cx).show_toolbar()
 607    }
 608
 609    fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Point<Pixels>> {
 610        self.read(cx).pixel_position_of_cursor(cx)
 611    }
 612}
 613
 614impl From<Box<dyn ItemHandle>> for AnyView {
 615    fn from(val: Box<dyn ItemHandle>) -> Self {
 616        val.to_any()
 617    }
 618}
 619
 620impl From<&Box<dyn ItemHandle>> for AnyView {
 621    fn from(val: &Box<dyn ItemHandle>) -> Self {
 622        val.to_any()
 623    }
 624}
 625
 626impl Clone for Box<dyn ItemHandle> {
 627    fn clone(&self) -> Box<dyn ItemHandle> {
 628        self.boxed_clone()
 629    }
 630}
 631
 632impl<T: Item> WeakItemHandle for WeakView<T> {
 633    fn id(&self) -> EntityId {
 634        self.entity_id()
 635    }
 636
 637    fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
 638        self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
 639    }
 640}
 641
 642pub trait ProjectItem: Item {
 643    type Item: project2::Item;
 644
 645    fn for_project_item(
 646        project: Model<Project>,
 647        item: Model<Self::Item>,
 648        cx: &mut ViewContext<Self>,
 649    ) -> Self
 650    where
 651        Self: Sized;
 652}
 653
 654pub enum FollowEvent {
 655    Unfollow,
 656}
 657
 658pub trait FollowableEvents {
 659    fn to_follow_event(&self) -> Option<FollowEvent>;
 660}
 661
 662pub trait FollowableItem: Item {
 663    type FollowableEvent: FollowableEvents;
 664    fn remote_id(&self) -> Option<ViewId>;
 665    fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
 666    fn from_state_proto(
 667        pane: View<Pane>,
 668        project: View<Workspace>,
 669        id: ViewId,
 670        state: &mut Option<proto::view::Variant>,
 671        cx: &mut AppContext,
 672    ) -> Option<Task<Result<View<Self>>>>;
 673    fn add_event_to_update_proto(
 674        &self,
 675        event: &Self::FollowableEvent,
 676        update: &mut Option<proto::update_view::Variant>,
 677        cx: &AppContext,
 678    ) -> bool;
 679    fn apply_update_proto(
 680        &mut self,
 681        project: &Model<Project>,
 682        message: proto::update_view::Variant,
 683        cx: &mut ViewContext<Self>,
 684    ) -> Task<Result<()>>;
 685    fn is_project_item(&self, cx: &AppContext) -> bool;
 686
 687    fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>);
 688}
 689
 690pub trait FollowableItemHandle: ItemHandle {
 691    fn remote_id(&self, client: &Arc<Client>, cx: &AppContext) -> Option<ViewId>;
 692    fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext);
 693    fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
 694    fn add_event_to_update_proto(
 695        &self,
 696        event: &dyn Any,
 697        update: &mut Option<proto::update_view::Variant>,
 698        cx: &AppContext,
 699    ) -> bool;
 700    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
 701    fn apply_update_proto(
 702        &self,
 703        project: &Model<Project>,
 704        message: proto::update_view::Variant,
 705        cx: &mut WindowContext,
 706    ) -> Task<Result<()>>;
 707    fn is_project_item(&self, cx: &AppContext) -> bool;
 708}
 709
 710impl<T: FollowableItem> FollowableItemHandle for View<T> {
 711    fn remote_id(&self, client: &Arc<Client>, cx: &AppContext) -> Option<ViewId> {
 712        self.read(cx).remote_id().or_else(|| {
 713            client.peer_id().map(|creator| ViewId {
 714                creator,
 715                id: self.item_id().as_u64(),
 716            })
 717        })
 718    }
 719
 720    fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext) {
 721        self.update(cx, |this, cx| this.set_leader_peer_id(leader_peer_id, cx))
 722    }
 723
 724    fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
 725        self.read(cx).to_state_proto(cx)
 726    }
 727
 728    fn add_event_to_update_proto(
 729        &self,
 730        event: &dyn Any,
 731        update: &mut Option<proto::update_view::Variant>,
 732        cx: &AppContext,
 733    ) -> bool {
 734        if let Some(event) = event.downcast_ref() {
 735            self.read(cx).add_event_to_update_proto(event, update, cx)
 736        } else {
 737            false
 738        }
 739    }
 740
 741    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
 742        event
 743            .downcast_ref()
 744            .map(T::FollowableEvent::to_follow_event)
 745            .flatten()
 746    }
 747
 748    fn apply_update_proto(
 749        &self,
 750        project: &Model<Project>,
 751        message: proto::update_view::Variant,
 752        cx: &mut WindowContext,
 753    ) -> Task<Result<()>> {
 754        self.update(cx, |this, cx| this.apply_update_proto(project, message, cx))
 755    }
 756
 757    fn is_project_item(&self, cx: &AppContext) -> bool {
 758        self.read(cx).is_project_item(cx)
 759    }
 760}
 761
 762// #[cfg(any(test, feature = "test-support"))]
 763// pub mod test {
 764//     use super::{Item, ItemEvent};
 765//     use crate::{ItemId, ItemNavHistory, Pane, Workspace, WorkspaceId};
 766//     use gpui::{
 767//         elements::Empty, AnyElement, AppContext, Element, Entity, Model, Task, View,
 768//         ViewContext, View, WeakViewHandle,
 769//     };
 770//     use project2::{Project, ProjectEntryId, ProjectPath, WorktreeId};
 771//     use smallvec::SmallVec;
 772//     use std::{any::Any, borrow::Cow, cell::Cell, path::Path};
 773
 774//     pub struct TestProjectItem {
 775//         pub entry_id: Option<ProjectEntryId>,
 776//         pub project_path: Option<ProjectPath>,
 777//     }
 778
 779//     pub struct TestItem {
 780//         pub workspace_id: WorkspaceId,
 781//         pub state: String,
 782//         pub label: String,
 783//         pub save_count: usize,
 784//         pub save_as_count: usize,
 785//         pub reload_count: usize,
 786//         pub is_dirty: bool,
 787//         pub is_singleton: bool,
 788//         pub has_conflict: bool,
 789//         pub project_items: Vec<Model<TestProjectItem>>,
 790//         pub nav_history: Option<ItemNavHistory>,
 791//         pub tab_descriptions: Option<Vec<&'static str>>,
 792//         pub tab_detail: Cell<Option<usize>>,
 793//     }
 794
 795//     impl Entity for TestProjectItem {
 796//         type Event = ();
 797//     }
 798
 799//     impl project2::Item for TestProjectItem {
 800//         fn entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
 801//             self.entry_id
 802//         }
 803
 804//         fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
 805//             self.project_path.clone()
 806//         }
 807//     }
 808
 809//     pub enum TestItemEvent {
 810//         Edit,
 811//     }
 812
 813//     impl Clone for TestItem {
 814//         fn clone(&self) -> Self {
 815//             Self {
 816//                 state: self.state.clone(),
 817//                 label: self.label.clone(),
 818//                 save_count: self.save_count,
 819//                 save_as_count: self.save_as_count,
 820//                 reload_count: self.reload_count,
 821//                 is_dirty: self.is_dirty,
 822//                 is_singleton: self.is_singleton,
 823//                 has_conflict: self.has_conflict,
 824//                 project_items: self.project_items.clone(),
 825//                 nav_history: None,
 826//                 tab_descriptions: None,
 827//                 tab_detail: Default::default(),
 828//                 workspace_id: self.workspace_id,
 829//             }
 830//         }
 831//     }
 832
 833//     impl TestProjectItem {
 834//         pub fn new(id: u64, path: &str, cx: &mut AppContext) -> Model<Self> {
 835//             let entry_id = Some(ProjectEntryId::from_proto(id));
 836//             let project_path = Some(ProjectPath {
 837//                 worktree_id: WorktreeId::from_usize(0),
 838//                 path: Path::new(path).into(),
 839//             });
 840//             cx.add_model(|_| Self {
 841//                 entry_id,
 842//                 project_path,
 843//             })
 844//         }
 845
 846//         pub fn new_untitled(cx: &mut AppContext) -> Model<Self> {
 847//             cx.add_model(|_| Self {
 848//                 project_path: None,
 849//                 entry_id: None,
 850//             })
 851//         }
 852//     }
 853
 854//     impl TestItem {
 855//         pub fn new() -> Self {
 856//             Self {
 857//                 state: String::new(),
 858//                 label: String::new(),
 859//                 save_count: 0,
 860//                 save_as_count: 0,
 861//                 reload_count: 0,
 862//                 is_dirty: false,
 863//                 has_conflict: false,
 864//                 project_items: Vec::new(),
 865//                 is_singleton: true,
 866//                 nav_history: None,
 867//                 tab_descriptions: None,
 868//                 tab_detail: Default::default(),
 869//                 workspace_id: 0,
 870//             }
 871//         }
 872
 873//         pub fn new_deserialized(id: WorkspaceId) -> Self {
 874//             let mut this = Self::new();
 875//             this.workspace_id = id;
 876//             this
 877//         }
 878
 879//         pub fn with_label(mut self, state: &str) -> Self {
 880//             self.label = state.to_string();
 881//             self
 882//         }
 883
 884//         pub fn with_singleton(mut self, singleton: bool) -> Self {
 885//             self.is_singleton = singleton;
 886//             self
 887//         }
 888
 889//         pub fn with_dirty(mut self, dirty: bool) -> Self {
 890//             self.is_dirty = dirty;
 891//             self
 892//         }
 893
 894//         pub fn with_conflict(mut self, has_conflict: bool) -> Self {
 895//             self.has_conflict = has_conflict;
 896//             self
 897//         }
 898
 899//         pub fn with_project_items(mut self, items: &[Model<TestProjectItem>]) -> Self {
 900//             self.project_items.clear();
 901//             self.project_items.extend(items.iter().cloned());
 902//             self
 903//         }
 904
 905//         pub fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
 906//             self.push_to_nav_history(cx);
 907//             self.state = state;
 908//         }
 909
 910//         fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
 911//             if let Some(history) = &mut self.nav_history {
 912//                 history.push(Some(Box::new(self.state.clone())), cx);
 913//             }
 914//         }
 915//     }
 916
 917//     impl Entity for TestItem {
 918//         type Event = TestItemEvent;
 919//     }
 920
 921//     impl View for TestItem {
 922//         fn ui_name() -> &'static str {
 923//             "TestItem"
 924//         }
 925
 926//         fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
 927//             Empty::new().into_any()
 928//         }
 929//     }
 930
 931//     impl Item for TestItem {
 932//         fn tab_description(&self, detail: usize, _: &AppContext) -> Option<Cow<str>> {
 933//             self.tab_descriptions.as_ref().and_then(|descriptions| {
 934//                 let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
 935//                 Some(description.into())
 936//             })
 937//         }
 938
 939//         fn tab_content<V: 'static>(
 940//             &self,
 941//             detail: Option<usize>,
 942//             _: &theme2::Tab,
 943//             _: &AppContext,
 944//         ) -> AnyElement<V> {
 945//             self.tab_detail.set(detail);
 946//             Empty::new().into_any()
 947//         }
 948
 949//         fn for_each_project_item(
 950//             &self,
 951//             cx: &AppContext,
 952//             f: &mut dyn FnMut(usize, &dyn project2::Item),
 953//         ) {
 954//             self.project_items
 955//                 .iter()
 956//                 .for_each(|item| f(item.id(), item.read(cx)))
 957//         }
 958
 959// fn is_singleton(&self, _: &AppContext) -> bool {
 960//     self.is_singleton
 961// }
 962
 963//         fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
 964//             self.nav_history = Some(history);
 965//         }
 966
 967//         fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
 968//             let state = *state.downcast::<String>().unwrap_or_default();
 969//             if state != self.state {
 970//                 self.state = state;
 971//                 true
 972//             } else {
 973//                 false
 974//             }
 975//         }
 976
 977//         fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 978//             self.push_to_nav_history(cx);
 979//         }
 980
 981//         fn clone_on_split(
 982//             &self,
 983//             _workspace_id: WorkspaceId,
 984//             _: &mut ViewContext<Self>,
 985//         ) -> Option<Self>
 986//         where
 987//             Self: Sized,
 988//         {
 989//             Some(self.clone())
 990//         }
 991
 992//         fn is_dirty(&self, _: &AppContext) -> bool {
 993//             self.is_dirty
 994//         }
 995
 996//         fn has_conflict(&self, _: &AppContext) -> bool {
 997//             self.has_conflict
 998//         }
 999
1000//         fn can_save(&self, cx: &AppContext) -> bool {
1001//             !self.project_items.is_empty()
1002//                 && self
1003//                     .project_items
1004//                     .iter()
1005//                     .all(|item| item.read(cx).entry_id.is_some())
1006//         }
1007
1008//         fn save(
1009//             &mut self,
1010//             _: Model<Project>,
1011//             _: &mut ViewContext<Self>,
1012//         ) -> Task<anyhow::Result<()>> {
1013//             self.save_count += 1;
1014//             self.is_dirty = false;
1015//             Task::ready(Ok(()))
1016//         }
1017
1018//         fn save_as(
1019//             &mut self,
1020//             _: Model<Project>,
1021//             _: std::path::PathBuf,
1022//             _: &mut ViewContext<Self>,
1023//         ) -> Task<anyhow::Result<()>> {
1024//             self.save_as_count += 1;
1025//             self.is_dirty = false;
1026//             Task::ready(Ok(()))
1027//         }
1028
1029//         fn reload(
1030//             &mut self,
1031//             _: Model<Project>,
1032//             _: &mut ViewContext<Self>,
1033//         ) -> Task<anyhow::Result<()>> {
1034//             self.reload_count += 1;
1035//             self.is_dirty = false;
1036//             Task::ready(Ok(()))
1037//         }
1038
1039//         fn to_item_events(_: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
1040//             [ItemEvent::UpdateTab, ItemEvent::Edit].into()
1041//         }
1042
1043//         fn serialized_item_kind() -> Option<&'static str> {
1044//             Some("TestItem")
1045//         }
1046
1047//         fn deserialize(
1048//             _project: Model<Project>,
1049//             _workspace: WeakViewHandle<Workspace>,
1050//             workspace_id: WorkspaceId,
1051//             _item_id: ItemId,
1052//             cx: &mut ViewContext<Pane>,
1053//         ) -> Task<anyhow::Result<View<Self>>> {
1054//             let view = cx.add_view(|_cx| Self::new_deserialized(workspace_id));
1055//             Task::Ready(Some(anyhow::Ok(view)))
1056//         }
1057//     }
1058// }