item.rs

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