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    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    path::PathBuf,
  30    rc::Rc,
  31    sync::Arc,
  32    time::Duration,
  33};
  34use theme::Theme;
  35use ui::Element as _;
  36
  37pub const LEADER_UPDATE_THROTTLE: Duration = Duration::from_millis(200);
  38
  39#[derive(Deserialize)]
  40pub struct ItemSettings {
  41    pub git_status: bool,
  42    pub close_position: ClosePosition,
  43}
  44
  45#[derive(Deserialize)]
  46pub struct PreviewTabsSettings {
  47    pub enabled: bool,
  48    pub enable_preview_from_file_finder: bool,
  49}
  50
  51#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  52#[serde(rename_all = "lowercase")]
  53pub enum ClosePosition {
  54    Left,
  55    #[default]
  56    Right,
  57}
  58
  59impl ClosePosition {
  60    pub fn right(&self) -> bool {
  61        match self {
  62            ClosePosition::Left => false,
  63            ClosePosition::Right => true,
  64        }
  65    }
  66}
  67
  68#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  69pub struct ItemSettingsContent {
  70    /// Whether to show the Git file status on a tab item.
  71    ///
  72    /// Default: true
  73    git_status: Option<bool>,
  74    /// Position of the close button in a tab.
  75    ///
  76    /// Default: right
  77    close_position: Option<ClosePosition>,
  78}
  79
  80#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  81pub struct PreviewTabsSettingsContent {
  82    /// Whether to show opened editors as preview editors.
  83    /// 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.
  84    ///
  85    /// Default: true
  86    enabled: Option<bool>,
  87    /// Whether to open a preview editor when opening a file using the file finder.
  88    ///
  89    /// Default: false
  90    enable_preview_from_file_finder: Option<bool>,
  91}
  92
  93impl Settings for ItemSettings {
  94    const KEY: Option<&'static str> = Some("tabs");
  95
  96    type FileContent = ItemSettingsContent;
  97
  98    fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
  99        sources.json_merge()
 100    }
 101}
 102
 103impl Settings for PreviewTabsSettings {
 104    const KEY: Option<&'static str> = Some("preview_tabs");
 105
 106    type FileContent = PreviewTabsSettingsContent;
 107
 108    fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
 109        sources.json_merge()
 110    }
 111}
 112
 113#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
 114pub enum ItemEvent {
 115    CloseItem,
 116    UpdateTab,
 117    UpdateBreadcrumbs,
 118    Edit,
 119}
 120
 121// TODO: Combine this with existing HighlightedText struct?
 122pub struct BreadcrumbText {
 123    pub text: String,
 124    pub highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
 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        _abs_path: PathBuf,
 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        abs_path: PathBuf,
 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 =
 516                Some(cx.subscribe(self, move |workspace, item, event, cx| {
 517                    let pane = if let Some(pane) = workspace
 518                        .panes_by_item
 519                        .get(&item.item_id())
 520                        .and_then(|pane| pane.upgrade())
 521                    {
 522                        pane
 523                    } else {
 524                        log::error!("unexpected item event after pane was dropped");
 525                        return;
 526                    };
 527
 528                    if let Some(item) = item.to_followable_item_handle(cx) {
 529                        let leader_id = workspace.leader_for_pane(&pane);
 530                        let follow_event = item.to_follow_event(event);
 531                        if leader_id.is_some()
 532                            && matches!(follow_event, Some(FollowEvent::Unfollow))
 533                        {
 534                            workspace.unfollow(&pane, cx);
 535                        }
 536
 537                        if item.focus_handle(cx).contains_focused(cx) {
 538                            item.add_event_to_update_proto(
 539                                event,
 540                                &mut pending_update.borrow_mut(),
 541                                cx,
 542                            );
 543                            pending_update_tx.unbounded_send(leader_id).ok();
 544                        }
 545                    }
 546
 547                    T::to_item_events(event, |event| match event {
 548                        ItemEvent::CloseItem => {
 549                            pane.update(cx, |pane, cx| {
 550                                pane.close_item_by_id(item.item_id(), crate::SaveIntent::Close, cx)
 551                            })
 552                            .detach_and_log_err(cx);
 553                            return;
 554                        }
 555
 556                        ItemEvent::UpdateTab => {
 557                            pane.update(cx, |_, cx| {
 558                                cx.emit(pane::Event::ChangeItemTitle);
 559                                cx.notify();
 560                            });
 561                        }
 562
 563                        ItemEvent::Edit => {
 564                            let autosave = WorkspaceSettings::get_global(cx).autosave;
 565                            if let AutosaveSetting::AfterDelay { milliseconds } = autosave {
 566                                let delay = Duration::from_millis(milliseconds);
 567                                let item = item.clone();
 568                                pending_autosave.fire_new(delay, cx, move |workspace, cx| {
 569                                    Pane::autosave_item(&item, workspace.project().clone(), cx)
 570                                });
 571                            }
 572                            pane.update(cx, |pane, cx| pane.handle_item_edit(item.item_id(), cx));
 573                        }
 574
 575                        _ => {}
 576                    });
 577                }));
 578
 579            cx.on_blur(&self.focus_handle(cx), move |workspace, cx| {
 580                if WorkspaceSettings::get_global(cx).autosave == AutosaveSetting::OnFocusChange {
 581                    if let Some(item) = weak_item.upgrade() {
 582                        Pane::autosave_item(&item, workspace.project.clone(), cx)
 583                            .detach_and_log_err(cx);
 584                    }
 585                }
 586            })
 587            .detach();
 588
 589            let item_id = self.item_id();
 590            cx.observe_release(self, move |workspace, _, _| {
 591                workspace.panes_by_item.remove(&item_id);
 592                event_subscription.take();
 593                send_follower_updates.take();
 594            })
 595            .detach();
 596        }
 597
 598        cx.defer(|workspace, cx| {
 599            workspace.serialize_workspace(cx).detach();
 600        });
 601    }
 602
 603    fn deactivated(&self, cx: &mut WindowContext) {
 604        self.update(cx, |this, cx| this.deactivated(cx));
 605    }
 606
 607    fn workspace_deactivated(&self, cx: &mut WindowContext) {
 608        self.update(cx, |this, cx| this.workspace_deactivated(cx));
 609    }
 610
 611    fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool {
 612        self.update(cx, |this, cx| this.navigate(data, cx))
 613    }
 614
 615    fn item_id(&self) -> EntityId {
 616        self.entity_id()
 617    }
 618
 619    fn to_any(&self) -> AnyView {
 620        self.clone().into()
 621    }
 622
 623    fn is_dirty(&self, cx: &AppContext) -> bool {
 624        self.read(cx).is_dirty(cx)
 625    }
 626
 627    fn has_conflict(&self, cx: &AppContext) -> bool {
 628        self.read(cx).has_conflict(cx)
 629    }
 630
 631    fn can_save(&self, cx: &AppContext) -> bool {
 632        self.read(cx).can_save(cx)
 633    }
 634
 635    fn save(
 636        &self,
 637        format: bool,
 638        project: Model<Project>,
 639        cx: &mut WindowContext,
 640    ) -> Task<Result<()>> {
 641        self.update(cx, |item, cx| item.save(format, project, cx))
 642    }
 643
 644    fn save_as(
 645        &self,
 646        project: Model<Project>,
 647        abs_path: PathBuf,
 648        cx: &mut WindowContext,
 649    ) -> Task<anyhow::Result<()>> {
 650        self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
 651    }
 652
 653    fn reload(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
 654        self.update(cx, |item, cx| item.reload(project, cx))
 655    }
 656
 657    fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a AppContext) -> Option<AnyView> {
 658        self.read(cx).act_as_type(type_id, self, cx)
 659    }
 660
 661    fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
 662        let builders = cx.try_global::<FollowableItemBuilders>()?;
 663        let item = self.to_any();
 664        Some(builders.get(&item.entity_type())?.1(&item))
 665    }
 666
 667    fn on_release(
 668        &self,
 669        cx: &mut AppContext,
 670        callback: Box<dyn FnOnce(&mut AppContext) + Send>,
 671    ) -> gpui::Subscription {
 672        cx.observe_release(self, move |_, cx| callback(cx))
 673    }
 674
 675    fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {
 676        self.read(cx).as_searchable(self)
 677    }
 678
 679    fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {
 680        self.read(cx).breadcrumb_location()
 681    }
 682
 683    fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 684        self.read(cx).breadcrumbs(theme, cx)
 685    }
 686
 687    fn serialized_item_kind(&self) -> Option<&'static str> {
 688        T::serialized_item_kind()
 689    }
 690
 691    fn show_toolbar(&self, cx: &AppContext) -> bool {
 692        self.read(cx).show_toolbar()
 693    }
 694
 695    fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Point<Pixels>> {
 696        self.read(cx).pixel_position_of_cursor(cx)
 697    }
 698}
 699
 700impl From<Box<dyn ItemHandle>> for AnyView {
 701    fn from(val: Box<dyn ItemHandle>) -> Self {
 702        val.to_any()
 703    }
 704}
 705
 706impl From<&Box<dyn ItemHandle>> for AnyView {
 707    fn from(val: &Box<dyn ItemHandle>) -> Self {
 708        val.to_any()
 709    }
 710}
 711
 712impl Clone for Box<dyn ItemHandle> {
 713    fn clone(&self) -> Box<dyn ItemHandle> {
 714        self.boxed_clone()
 715    }
 716}
 717
 718impl<T: Item> WeakItemHandle for WeakView<T> {
 719    fn id(&self) -> EntityId {
 720        self.entity_id()
 721    }
 722
 723    fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
 724        self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
 725    }
 726}
 727
 728pub trait ProjectItem: Item {
 729    type Item: project::Item;
 730
 731    fn for_project_item(
 732        project: Model<Project>,
 733        item: Model<Self::Item>,
 734        cx: &mut ViewContext<Self>,
 735    ) -> Self
 736    where
 737        Self: Sized;
 738}
 739
 740#[derive(Debug)]
 741pub enum FollowEvent {
 742    Unfollow,
 743}
 744
 745pub trait FollowableItem: Item {
 746    fn remote_id(&self) -> Option<ViewId>;
 747    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant>;
 748    fn from_state_proto(
 749        pane: View<Pane>,
 750        project: View<Workspace>,
 751        id: ViewId,
 752        state: &mut Option<proto::view::Variant>,
 753        cx: &mut WindowContext,
 754    ) -> Option<Task<Result<View<Self>>>>;
 755    fn to_follow_event(event: &Self::Event) -> Option<FollowEvent>;
 756    fn add_event_to_update_proto(
 757        &self,
 758        event: &Self::Event,
 759        update: &mut Option<proto::update_view::Variant>,
 760        cx: &WindowContext,
 761    ) -> bool;
 762    fn apply_update_proto(
 763        &mut self,
 764        project: &Model<Project>,
 765        message: proto::update_view::Variant,
 766        cx: &mut ViewContext<Self>,
 767    ) -> Task<Result<()>>;
 768    fn is_project_item(&self, cx: &WindowContext) -> bool;
 769    fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>);
 770}
 771
 772pub trait FollowableItemHandle: ItemHandle {
 773    fn remote_id(&self, client: &Arc<Client>, cx: &WindowContext) -> Option<ViewId>;
 774    fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle>;
 775    fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext);
 776    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant>;
 777    fn add_event_to_update_proto(
 778        &self,
 779        event: &dyn Any,
 780        update: &mut Option<proto::update_view::Variant>,
 781        cx: &WindowContext,
 782    ) -> bool;
 783    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
 784    fn apply_update_proto(
 785        &self,
 786        project: &Model<Project>,
 787        message: proto::update_view::Variant,
 788        cx: &mut WindowContext,
 789    ) -> Task<Result<()>>;
 790    fn is_project_item(&self, cx: &WindowContext) -> bool;
 791}
 792
 793impl<T: FollowableItem> FollowableItemHandle for View<T> {
 794    fn remote_id(&self, client: &Arc<Client>, cx: &WindowContext) -> Option<ViewId> {
 795        self.read(cx).remote_id().or_else(|| {
 796            client.peer_id().map(|creator| ViewId {
 797                creator,
 798                id: self.item_id().as_u64(),
 799            })
 800        })
 801    }
 802
 803    fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle> {
 804        Box::new(self.downgrade())
 805    }
 806
 807    fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext) {
 808        self.update(cx, |this, cx| this.set_leader_peer_id(leader_peer_id, cx))
 809    }
 810
 811    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
 812        self.read(cx).to_state_proto(cx)
 813    }
 814
 815    fn add_event_to_update_proto(
 816        &self,
 817        event: &dyn Any,
 818        update: &mut Option<proto::update_view::Variant>,
 819        cx: &WindowContext,
 820    ) -> bool {
 821        if let Some(event) = event.downcast_ref() {
 822            self.read(cx).add_event_to_update_proto(event, update, cx)
 823        } else {
 824            false
 825        }
 826    }
 827
 828    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
 829        T::to_follow_event(event.downcast_ref()?)
 830    }
 831
 832    fn apply_update_proto(
 833        &self,
 834        project: &Model<Project>,
 835        message: proto::update_view::Variant,
 836        cx: &mut WindowContext,
 837    ) -> Task<Result<()>> {
 838        self.update(cx, |this, cx| this.apply_update_proto(project, message, cx))
 839    }
 840
 841    fn is_project_item(&self, cx: &WindowContext) -> bool {
 842        self.read(cx).is_project_item(cx)
 843    }
 844}
 845
 846pub trait WeakFollowableItemHandle: Send + Sync {
 847    fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>>;
 848}
 849
 850impl<T: FollowableItem> WeakFollowableItemHandle for WeakView<T> {
 851    fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>> {
 852        Some(Box::new(self.upgrade()?))
 853    }
 854}
 855
 856#[cfg(any(test, feature = "test-support"))]
 857pub mod test {
 858    use super::{Item, ItemEvent, TabContentParams};
 859    use crate::{ItemId, ItemNavHistory, Pane, Workspace, WorkspaceId};
 860    use gpui::{
 861        AnyElement, AppContext, Context as _, EntityId, EventEmitter, FocusableView,
 862        InteractiveElement, IntoElement, Model, Render, SharedString, Task, View, ViewContext,
 863        VisualContext, WeakView,
 864    };
 865    use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
 866    use std::{any::Any, cell::Cell, path::Path};
 867
 868    pub struct TestProjectItem {
 869        pub entry_id: Option<ProjectEntryId>,
 870        pub project_path: Option<ProjectPath>,
 871    }
 872
 873    pub struct TestItem {
 874        pub workspace_id: WorkspaceId,
 875        pub state: String,
 876        pub label: String,
 877        pub save_count: usize,
 878        pub save_as_count: usize,
 879        pub reload_count: usize,
 880        pub is_dirty: bool,
 881        pub is_singleton: bool,
 882        pub has_conflict: bool,
 883        pub project_items: Vec<Model<TestProjectItem>>,
 884        pub nav_history: Option<ItemNavHistory>,
 885        pub tab_descriptions: Option<Vec<&'static str>>,
 886        pub tab_detail: Cell<Option<usize>>,
 887        focus_handle: gpui::FocusHandle,
 888    }
 889
 890    impl project::Item for TestProjectItem {
 891        fn try_open(
 892            _project: &Model<Project>,
 893            _path: &ProjectPath,
 894            _cx: &mut AppContext,
 895        ) -> Option<Task<gpui::Result<Model<Self>>>> {
 896            None
 897        }
 898
 899        fn entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
 900            self.entry_id
 901        }
 902
 903        fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
 904            self.project_path.clone()
 905        }
 906    }
 907
 908    pub enum TestItemEvent {
 909        Edit,
 910    }
 911
 912    impl TestProjectItem {
 913        pub fn new(id: u64, path: &str, cx: &mut AppContext) -> Model<Self> {
 914            let entry_id = Some(ProjectEntryId::from_proto(id));
 915            let project_path = Some(ProjectPath {
 916                worktree_id: WorktreeId::from_usize(0),
 917                path: Path::new(path).into(),
 918            });
 919            cx.new_model(|_| Self {
 920                entry_id,
 921                project_path,
 922            })
 923        }
 924
 925        pub fn new_untitled(cx: &mut AppContext) -> Model<Self> {
 926            cx.new_model(|_| Self {
 927                project_path: None,
 928                entry_id: None,
 929            })
 930        }
 931    }
 932
 933    impl TestItem {
 934        pub fn new(cx: &mut ViewContext<Self>) -> Self {
 935            Self {
 936                state: String::new(),
 937                label: String::new(),
 938                save_count: 0,
 939                save_as_count: 0,
 940                reload_count: 0,
 941                is_dirty: false,
 942                has_conflict: false,
 943                project_items: Vec::new(),
 944                is_singleton: true,
 945                nav_history: None,
 946                tab_descriptions: None,
 947                tab_detail: Default::default(),
 948                workspace_id: Default::default(),
 949                focus_handle: cx.focus_handle(),
 950            }
 951        }
 952
 953        pub fn new_deserialized(id: WorkspaceId, cx: &mut ViewContext<Self>) -> Self {
 954            let mut this = Self::new(cx);
 955            this.workspace_id = id;
 956            this
 957        }
 958
 959        pub fn with_label(mut self, state: &str) -> Self {
 960            self.label = state.to_string();
 961            self
 962        }
 963
 964        pub fn with_singleton(mut self, singleton: bool) -> Self {
 965            self.is_singleton = singleton;
 966            self
 967        }
 968
 969        pub fn with_dirty(mut self, dirty: bool) -> Self {
 970            self.is_dirty = dirty;
 971            self
 972        }
 973
 974        pub fn with_conflict(mut self, has_conflict: bool) -> Self {
 975            self.has_conflict = has_conflict;
 976            self
 977        }
 978
 979        pub fn with_project_items(mut self, items: &[Model<TestProjectItem>]) -> Self {
 980            self.project_items.clear();
 981            self.project_items.extend(items.iter().cloned());
 982            self
 983        }
 984
 985        pub fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
 986            self.push_to_nav_history(cx);
 987            self.state = state;
 988        }
 989
 990        fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
 991            if let Some(history) = &mut self.nav_history {
 992                history.push(Some(Box::new(self.state.clone())), cx);
 993            }
 994        }
 995    }
 996
 997    impl Render for TestItem {
 998        fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
 999            gpui::div().track_focus(&self.focus_handle)
1000        }
1001    }
1002
1003    impl EventEmitter<ItemEvent> for TestItem {}
1004
1005    impl FocusableView for TestItem {
1006        fn focus_handle(&self, _: &AppContext) -> gpui::FocusHandle {
1007            self.focus_handle.clone()
1008        }
1009    }
1010
1011    impl Item for TestItem {
1012        type Event = ItemEvent;
1013
1014        fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1015            f(*event)
1016        }
1017
1018        fn tab_description(&self, detail: usize, _: &AppContext) -> Option<SharedString> {
1019            self.tab_descriptions.as_ref().and_then(|descriptions| {
1020                let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
1021                Some(description.into())
1022            })
1023        }
1024
1025        fn telemetry_event_text(&self) -> Option<&'static str> {
1026            None
1027        }
1028
1029        fn tab_content(
1030            &self,
1031            params: TabContentParams,
1032            _cx: &ui::prelude::WindowContext,
1033        ) -> AnyElement {
1034            self.tab_detail.set(params.detail);
1035            gpui::div().into_any_element()
1036        }
1037
1038        fn for_each_project_item(
1039            &self,
1040            cx: &AppContext,
1041            f: &mut dyn FnMut(EntityId, &dyn project::Item),
1042        ) {
1043            self.project_items
1044                .iter()
1045                .for_each(|item| f(item.entity_id(), item.read(cx)))
1046        }
1047
1048        fn is_singleton(&self, _: &AppContext) -> bool {
1049            self.is_singleton
1050        }
1051
1052        fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
1053            self.nav_history = Some(history);
1054        }
1055
1056        fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
1057            let state = *state.downcast::<String>().unwrap_or_default();
1058            if state != self.state {
1059                self.state = state;
1060                true
1061            } else {
1062                false
1063            }
1064        }
1065
1066        fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
1067            self.push_to_nav_history(cx);
1068        }
1069
1070        fn clone_on_split(
1071            &self,
1072            _workspace_id: WorkspaceId,
1073            cx: &mut ViewContext<Self>,
1074        ) -> Option<View<Self>>
1075        where
1076            Self: Sized,
1077        {
1078            Some(cx.new_view(|cx| Self {
1079                state: self.state.clone(),
1080                label: self.label.clone(),
1081                save_count: self.save_count,
1082                save_as_count: self.save_as_count,
1083                reload_count: self.reload_count,
1084                is_dirty: self.is_dirty,
1085                is_singleton: self.is_singleton,
1086                has_conflict: self.has_conflict,
1087                project_items: self.project_items.clone(),
1088                nav_history: None,
1089                tab_descriptions: None,
1090                tab_detail: Default::default(),
1091                workspace_id: self.workspace_id,
1092                focus_handle: cx.focus_handle(),
1093            }))
1094        }
1095
1096        fn is_dirty(&self, _: &AppContext) -> bool {
1097            self.is_dirty
1098        }
1099
1100        fn has_conflict(&self, _: &AppContext) -> bool {
1101            self.has_conflict
1102        }
1103
1104        fn can_save(&self, cx: &AppContext) -> bool {
1105            !self.project_items.is_empty()
1106                && self
1107                    .project_items
1108                    .iter()
1109                    .all(|item| item.read(cx).entry_id.is_some())
1110        }
1111
1112        fn save(
1113            &mut self,
1114            _: bool,
1115            _: Model<Project>,
1116            _: &mut ViewContext<Self>,
1117        ) -> Task<anyhow::Result<()>> {
1118            self.save_count += 1;
1119            self.is_dirty = false;
1120            Task::ready(Ok(()))
1121        }
1122
1123        fn save_as(
1124            &mut self,
1125            _: Model<Project>,
1126            _: std::path::PathBuf,
1127            _: &mut ViewContext<Self>,
1128        ) -> Task<anyhow::Result<()>> {
1129            self.save_as_count += 1;
1130            self.is_dirty = false;
1131            Task::ready(Ok(()))
1132        }
1133
1134        fn reload(
1135            &mut self,
1136            _: Model<Project>,
1137            _: &mut ViewContext<Self>,
1138        ) -> Task<anyhow::Result<()>> {
1139            self.reload_count += 1;
1140            self.is_dirty = false;
1141            Task::ready(Ok(()))
1142        }
1143
1144        fn serialized_item_kind() -> Option<&'static str> {
1145            Some("TestItem")
1146        }
1147
1148        fn deserialize(
1149            _project: Model<Project>,
1150            _workspace: WeakView<Workspace>,
1151            workspace_id: WorkspaceId,
1152            _item_id: ItemId,
1153            cx: &mut ViewContext<Pane>,
1154        ) -> Task<anyhow::Result<View<Self>>> {
1155            let view = cx.new_view(|cx| Self::new_deserialized(workspace_id, cx));
1156            Task::Ready(Some(anyhow::Ok(view)))
1157        }
1158    }
1159}