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