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