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