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.add_event_to_update_proto(
 452                            event,
 453                            &mut *pending_update.borrow_mut(),
 454                            cx,
 455                        ) && !pending_update_scheduled.load(Ordering::SeqCst)
 456                        {
 457                            pending_update_scheduled.store(true, Ordering::SeqCst);
 458                            cx.defer({
 459                                let pending_update = pending_update.clone();
 460                                let pending_update_scheduled = pending_update_scheduled.clone();
 461                                move |this, cx| {
 462                                    pending_update_scheduled.store(false, Ordering::SeqCst);
 463                                    this.update_followers(
 464                                        is_project_item,
 465                                        proto::update_followers::Variant::UpdateView(
 466                                            proto::UpdateView {
 467                                                id: item
 468                                                    .remote_id(&this.app_state.client, cx)
 469                                                    .map(|id| id.to_proto()),
 470                                                variant: pending_update.borrow_mut().take(),
 471                                                leader_id,
 472                                            },
 473                                        ),
 474                                        cx,
 475                                    );
 476                                }
 477                            });
 478                        }
 479                    }
 480
 481                    T::to_item_events(event, |event| match event {
 482                        ItemEvent::CloseItem => {
 483                            pane.update(cx, |pane, cx| {
 484                                pane.close_item_by_id(item.item_id(), crate::SaveIntent::Close, cx)
 485                            })
 486                            .detach_and_log_err(cx);
 487                            return;
 488                        }
 489
 490                        ItemEvent::UpdateTab => {
 491                            pane.update(cx, |_, cx| {
 492                                cx.emit(pane::Event::ChangeItemTitle);
 493                                cx.notify();
 494                            });
 495                        }
 496
 497                        ItemEvent::Edit => {
 498                            let autosave = WorkspaceSettings::get_global(cx).autosave;
 499                            if let AutosaveSetting::AfterDelay { milliseconds } = autosave {
 500                                let delay = Duration::from_millis(milliseconds);
 501                                let item = item.clone();
 502                                pending_autosave.fire_new(delay, cx, move |workspace, cx| {
 503                                    Pane::autosave_item(&item, workspace.project().clone(), cx)
 504                                });
 505                            }
 506                        }
 507
 508                        _ => {}
 509                    });
 510                }));
 511
 512            cx.on_blur(&self.focus_handle(cx), move |workspace, cx| {
 513                if WorkspaceSettings::get_global(cx).autosave == AutosaveSetting::OnFocusChange {
 514                    if let Some(item) = weak_item.upgrade() {
 515                        Pane::autosave_item(&item, workspace.project.clone(), cx)
 516                            .detach_and_log_err(cx);
 517                    }
 518                }
 519            })
 520            .detach();
 521
 522            let item_id = self.item_id();
 523            cx.observe_release(self, move |workspace, _, _| {
 524                workspace.panes_by_item.remove(&item_id);
 525                event_subscription.take();
 526            })
 527            .detach();
 528        }
 529
 530        cx.defer(|workspace, cx| {
 531            workspace.serialize_workspace(cx);
 532        });
 533    }
 534
 535    fn deactivated(&self, cx: &mut WindowContext) {
 536        self.update(cx, |this, cx| this.deactivated(cx));
 537    }
 538
 539    fn workspace_deactivated(&self, cx: &mut WindowContext) {
 540        self.update(cx, |this, cx| this.workspace_deactivated(cx));
 541    }
 542
 543    fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool {
 544        self.update(cx, |this, cx| this.navigate(data, cx))
 545    }
 546
 547    fn item_id(&self) -> EntityId {
 548        self.entity_id()
 549    }
 550
 551    fn to_any(&self) -> AnyView {
 552        self.clone().into()
 553    }
 554
 555    fn is_dirty(&self, cx: &AppContext) -> bool {
 556        self.read(cx).is_dirty(cx)
 557    }
 558
 559    fn has_conflict(&self, cx: &AppContext) -> bool {
 560        self.read(cx).has_conflict(cx)
 561    }
 562
 563    fn can_save(&self, cx: &AppContext) -> bool {
 564        self.read(cx).can_save(cx)
 565    }
 566
 567    fn save(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
 568        self.update(cx, |item, cx| item.save(project, cx))
 569    }
 570
 571    fn save_as(
 572        &self,
 573        project: Model<Project>,
 574        abs_path: PathBuf,
 575        cx: &mut WindowContext,
 576    ) -> Task<anyhow::Result<()>> {
 577        self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
 578    }
 579
 580    fn reload(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
 581        self.update(cx, |item, cx| item.reload(project, cx))
 582    }
 583
 584    fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a AppContext) -> Option<AnyView> {
 585        self.read(cx).act_as_type(type_id, self, cx)
 586    }
 587
 588    fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
 589        let builders = cx.try_global::<FollowableItemBuilders>()?;
 590        let item = self.to_any();
 591        Some(builders.get(&item.entity_type())?.1(&item))
 592    }
 593
 594    fn on_release(
 595        &self,
 596        cx: &mut AppContext,
 597        callback: Box<dyn FnOnce(&mut AppContext) + Send>,
 598    ) -> gpui::Subscription {
 599        cx.observe_release(self, move |_, cx| callback(cx))
 600    }
 601
 602    fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {
 603        self.read(cx).as_searchable(self)
 604    }
 605
 606    fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {
 607        self.read(cx).breadcrumb_location()
 608    }
 609
 610    fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 611        self.read(cx).breadcrumbs(theme, cx)
 612    }
 613
 614    fn serialized_item_kind(&self) -> Option<&'static str> {
 615        T::serialized_item_kind()
 616    }
 617
 618    fn show_toolbar(&self, cx: &AppContext) -> bool {
 619        self.read(cx).show_toolbar()
 620    }
 621
 622    fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Point<Pixels>> {
 623        self.read(cx).pixel_position_of_cursor(cx)
 624    }
 625}
 626
 627impl From<Box<dyn ItemHandle>> for AnyView {
 628    fn from(val: Box<dyn ItemHandle>) -> Self {
 629        val.to_any()
 630    }
 631}
 632
 633impl From<&Box<dyn ItemHandle>> for AnyView {
 634    fn from(val: &Box<dyn ItemHandle>) -> Self {
 635        val.to_any()
 636    }
 637}
 638
 639impl Clone for Box<dyn ItemHandle> {
 640    fn clone(&self) -> Box<dyn ItemHandle> {
 641        self.boxed_clone()
 642    }
 643}
 644
 645impl<T: Item> WeakItemHandle for WeakView<T> {
 646    fn id(&self) -> EntityId {
 647        self.entity_id()
 648    }
 649
 650    fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
 651        self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
 652    }
 653}
 654
 655pub trait ProjectItem: Item {
 656    type Item: project::Item;
 657
 658    fn for_project_item(
 659        project: Model<Project>,
 660        item: Model<Self::Item>,
 661        cx: &mut ViewContext<Self>,
 662    ) -> Self
 663    where
 664        Self: Sized;
 665}
 666
 667pub enum FollowEvent {
 668    Unfollow,
 669}
 670
 671pub trait FollowableItem: Item {
 672    fn remote_id(&self) -> Option<ViewId>;
 673    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant>;
 674    fn from_state_proto(
 675        pane: View<Pane>,
 676        project: View<Workspace>,
 677        id: ViewId,
 678        state: &mut Option<proto::view::Variant>,
 679        cx: &mut WindowContext,
 680    ) -> Option<Task<Result<View<Self>>>>;
 681    fn to_follow_event(event: &Self::Event) -> Option<FollowEvent>;
 682    fn add_event_to_update_proto(
 683        &self,
 684        event: &Self::Event,
 685        update: &mut Option<proto::update_view::Variant>,
 686        cx: &WindowContext,
 687    ) -> bool;
 688    fn apply_update_proto(
 689        &mut self,
 690        project: &Model<Project>,
 691        message: proto::update_view::Variant,
 692        cx: &mut ViewContext<Self>,
 693    ) -> Task<Result<()>>;
 694    fn is_project_item(&self, cx: &WindowContext) -> bool;
 695    fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>);
 696}
 697
 698pub trait FollowableItemHandle: ItemHandle {
 699    fn remote_id(&self, client: &Arc<Client>, cx: &WindowContext) -> Option<ViewId>;
 700    fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext);
 701    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant>;
 702    fn add_event_to_update_proto(
 703        &self,
 704        event: &dyn Any,
 705        update: &mut Option<proto::update_view::Variant>,
 706        cx: &WindowContext,
 707    ) -> bool;
 708    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
 709    fn apply_update_proto(
 710        &self,
 711        project: &Model<Project>,
 712        message: proto::update_view::Variant,
 713        cx: &mut WindowContext,
 714    ) -> Task<Result<()>>;
 715    fn is_project_item(&self, cx: &WindowContext) -> bool;
 716}
 717
 718impl<T: FollowableItem> FollowableItemHandle for View<T> {
 719    fn remote_id(&self, client: &Arc<Client>, cx: &WindowContext) -> Option<ViewId> {
 720        self.read(cx).remote_id().or_else(|| {
 721            client.peer_id().map(|creator| ViewId {
 722                creator,
 723                id: self.item_id().as_u64(),
 724            })
 725        })
 726    }
 727
 728    fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext) {
 729        self.update(cx, |this, cx| this.set_leader_peer_id(leader_peer_id, cx))
 730    }
 731
 732    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
 733        self.read(cx).to_state_proto(cx)
 734    }
 735
 736    fn add_event_to_update_proto(
 737        &self,
 738        event: &dyn Any,
 739        update: &mut Option<proto::update_view::Variant>,
 740        cx: &WindowContext,
 741    ) -> bool {
 742        if let Some(event) = event.downcast_ref() {
 743            self.read(cx).add_event_to_update_proto(event, update, cx)
 744        } else {
 745            false
 746        }
 747    }
 748
 749    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
 750        T::to_follow_event(event.downcast_ref()?)
 751    }
 752
 753    fn apply_update_proto(
 754        &self,
 755        project: &Model<Project>,
 756        message: proto::update_view::Variant,
 757        cx: &mut WindowContext,
 758    ) -> Task<Result<()>> {
 759        self.update(cx, |this, cx| this.apply_update_proto(project, message, cx))
 760    }
 761
 762    fn is_project_item(&self, cx: &WindowContext) -> bool {
 763        self.read(cx).is_project_item(cx)
 764    }
 765}
 766
 767#[cfg(any(test, feature = "test-support"))]
 768pub mod test {
 769    use super::{Item, ItemEvent};
 770    use crate::{ItemId, ItemNavHistory, Pane, Workspace, WorkspaceId};
 771    use gpui::{
 772        AnyElement, AppContext, Context as _, EntityId, EventEmitter, FocusableView,
 773        InteractiveElement, IntoElement, Model, Render, SharedString, Task, View, ViewContext,
 774        VisualContext, WeakView,
 775    };
 776    use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
 777    use std::{any::Any, cell::Cell, path::Path};
 778
 779    pub struct TestProjectItem {
 780        pub entry_id: Option<ProjectEntryId>,
 781        pub project_path: Option<ProjectPath>,
 782    }
 783
 784    pub struct TestItem {
 785        pub workspace_id: WorkspaceId,
 786        pub state: String,
 787        pub label: String,
 788        pub save_count: usize,
 789        pub save_as_count: usize,
 790        pub reload_count: usize,
 791        pub is_dirty: bool,
 792        pub is_singleton: bool,
 793        pub has_conflict: bool,
 794        pub project_items: Vec<Model<TestProjectItem>>,
 795        pub nav_history: Option<ItemNavHistory>,
 796        pub tab_descriptions: Option<Vec<&'static str>>,
 797        pub tab_detail: Cell<Option<usize>>,
 798        focus_handle: gpui::FocusHandle,
 799    }
 800
 801    impl project::Item for TestProjectItem {
 802        fn entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
 803            self.entry_id
 804        }
 805
 806        fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
 807            self.project_path.clone()
 808        }
 809    }
 810
 811    pub enum TestItemEvent {
 812        Edit,
 813    }
 814
 815    impl TestProjectItem {
 816        pub fn new(id: u64, path: &str, cx: &mut AppContext) -> Model<Self> {
 817            let entry_id = Some(ProjectEntryId::from_proto(id));
 818            let project_path = Some(ProjectPath {
 819                worktree_id: WorktreeId::from_usize(0),
 820                path: Path::new(path).into(),
 821            });
 822            cx.new_model(|_| Self {
 823                entry_id,
 824                project_path,
 825            })
 826        }
 827
 828        pub fn new_untitled(cx: &mut AppContext) -> Model<Self> {
 829            cx.new_model(|_| Self {
 830                project_path: None,
 831                entry_id: None,
 832            })
 833        }
 834    }
 835
 836    impl TestItem {
 837        pub fn new(cx: &mut ViewContext<Self>) -> Self {
 838            Self {
 839                state: String::new(),
 840                label: String::new(),
 841                save_count: 0,
 842                save_as_count: 0,
 843                reload_count: 0,
 844                is_dirty: false,
 845                has_conflict: false,
 846                project_items: Vec::new(),
 847                is_singleton: true,
 848                nav_history: None,
 849                tab_descriptions: None,
 850                tab_detail: Default::default(),
 851                workspace_id: 0,
 852                focus_handle: cx.focus_handle(),
 853            }
 854        }
 855
 856        pub fn new_deserialized(id: WorkspaceId, cx: &mut ViewContext<Self>) -> Self {
 857            let mut this = Self::new(cx);
 858            this.workspace_id = id;
 859            this
 860        }
 861
 862        pub fn with_label(mut self, state: &str) -> Self {
 863            self.label = state.to_string();
 864            self
 865        }
 866
 867        pub fn with_singleton(mut self, singleton: bool) -> Self {
 868            self.is_singleton = singleton;
 869            self
 870        }
 871
 872        pub fn with_dirty(mut self, dirty: bool) -> Self {
 873            self.is_dirty = dirty;
 874            self
 875        }
 876
 877        pub fn with_conflict(mut self, has_conflict: bool) -> Self {
 878            self.has_conflict = has_conflict;
 879            self
 880        }
 881
 882        pub fn with_project_items(mut self, items: &[Model<TestProjectItem>]) -> Self {
 883            self.project_items.clear();
 884            self.project_items.extend(items.iter().cloned());
 885            self
 886        }
 887
 888        pub fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
 889            self.push_to_nav_history(cx);
 890            self.state = state;
 891        }
 892
 893        fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
 894            if let Some(history) = &mut self.nav_history {
 895                history.push(Some(Box::new(self.state.clone())), cx);
 896            }
 897        }
 898    }
 899
 900    impl Render for TestItem {
 901        fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
 902            gpui::div().track_focus(&self.focus_handle)
 903        }
 904    }
 905
 906    impl EventEmitter<ItemEvent> for TestItem {}
 907
 908    impl FocusableView for TestItem {
 909        fn focus_handle(&self, _: &AppContext) -> gpui::FocusHandle {
 910            self.focus_handle.clone()
 911        }
 912    }
 913
 914    impl Item for TestItem {
 915        type Event = ItemEvent;
 916
 917        fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
 918            f(*event)
 919        }
 920
 921        fn tab_description(&self, detail: usize, _: &AppContext) -> Option<SharedString> {
 922            self.tab_descriptions.as_ref().and_then(|descriptions| {
 923                let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
 924                Some(description.into())
 925            })
 926        }
 927
 928        fn telemetry_event_text(&self) -> Option<&'static str> {
 929            None
 930        }
 931
 932        fn tab_content(
 933            &self,
 934            detail: Option<usize>,
 935            _selected: bool,
 936            _cx: &ui::prelude::WindowContext,
 937        ) -> AnyElement {
 938            self.tab_detail.set(detail);
 939            gpui::div().into_any_element()
 940        }
 941
 942        fn for_each_project_item(
 943            &self,
 944            cx: &AppContext,
 945            f: &mut dyn FnMut(EntityId, &dyn project::Item),
 946        ) {
 947            self.project_items
 948                .iter()
 949                .for_each(|item| f(item.entity_id(), item.read(cx)))
 950        }
 951
 952        fn is_singleton(&self, _: &AppContext) -> bool {
 953            self.is_singleton
 954        }
 955
 956        fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
 957            self.nav_history = Some(history);
 958        }
 959
 960        fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
 961            let state = *state.downcast::<String>().unwrap_or_default();
 962            if state != self.state {
 963                self.state = state;
 964                true
 965            } else {
 966                false
 967            }
 968        }
 969
 970        fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 971            self.push_to_nav_history(cx);
 972        }
 973
 974        fn clone_on_split(
 975            &self,
 976            _workspace_id: WorkspaceId,
 977            cx: &mut ViewContext<Self>,
 978        ) -> Option<View<Self>>
 979        where
 980            Self: Sized,
 981        {
 982            Some(cx.new_view(|cx| Self {
 983                state: self.state.clone(),
 984                label: self.label.clone(),
 985                save_count: self.save_count,
 986                save_as_count: self.save_as_count,
 987                reload_count: self.reload_count,
 988                is_dirty: self.is_dirty,
 989                is_singleton: self.is_singleton,
 990                has_conflict: self.has_conflict,
 991                project_items: self.project_items.clone(),
 992                nav_history: None,
 993                tab_descriptions: None,
 994                tab_detail: Default::default(),
 995                workspace_id: self.workspace_id,
 996                focus_handle: cx.focus_handle(),
 997            }))
 998        }
 999
1000        fn is_dirty(&self, _: &AppContext) -> bool {
1001            self.is_dirty
1002        }
1003
1004        fn has_conflict(&self, _: &AppContext) -> bool {
1005            self.has_conflict
1006        }
1007
1008        fn can_save(&self, cx: &AppContext) -> bool {
1009            !self.project_items.is_empty()
1010                && self
1011                    .project_items
1012                    .iter()
1013                    .all(|item| item.read(cx).entry_id.is_some())
1014        }
1015
1016        fn save(
1017            &mut self,
1018            _: Model<Project>,
1019            _: &mut ViewContext<Self>,
1020        ) -> Task<anyhow::Result<()>> {
1021            self.save_count += 1;
1022            self.is_dirty = false;
1023            Task::ready(Ok(()))
1024        }
1025
1026        fn save_as(
1027            &mut self,
1028            _: Model<Project>,
1029            _: std::path::PathBuf,
1030            _: &mut ViewContext<Self>,
1031        ) -> Task<anyhow::Result<()>> {
1032            self.save_as_count += 1;
1033            self.is_dirty = false;
1034            Task::ready(Ok(()))
1035        }
1036
1037        fn reload(
1038            &mut self,
1039            _: Model<Project>,
1040            _: &mut ViewContext<Self>,
1041        ) -> Task<anyhow::Result<()>> {
1042            self.reload_count += 1;
1043            self.is_dirty = false;
1044            Task::ready(Ok(()))
1045        }
1046
1047        fn serialized_item_kind() -> Option<&'static str> {
1048            Some("TestItem")
1049        }
1050
1051        fn deserialize(
1052            _project: Model<Project>,
1053            _workspace: WeakView<Workspace>,
1054            workspace_id: WorkspaceId,
1055            _item_id: ItemId,
1056            cx: &mut ViewContext<Pane>,
1057        ) -> Task<anyhow::Result<View<Self>>> {
1058            let view = cx.new_view(|cx| Self::new_deserialized(workspace_id, cx));
1059            Task::Ready(Some(anyhow::Ok(view)))
1060        }
1061    }
1062}