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