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