item.rs

   1use crate::{
   2    pane::{self, Pane},
   3    persistence::model::ItemId,
   4    searchable::SearchableItemHandle,
   5    workspace_settings::{AutosaveSetting, WorkspaceSettings},
   6    DelayedDebouncedEditAction, FollowableViewRegistry, ItemNavHistory, SerializableItemRegistry,
   7    ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
   8};
   9use anyhow::Result;
  10use client::{
  11    proto::{self, PeerId},
  12    Client,
  13};
  14use futures::{channel::mpsc, StreamExt};
  15use gpui::{
  16    Action, AnyElement, AnyView, App, Context, Entity, EntityId, EventEmitter, FocusHandle,
  17    Focusable, Font, HighlightStyle, Pixels, Point, Render, SharedString, Task, WeakEntity, Window,
  18};
  19use project::{Project, ProjectEntryId, ProjectPath};
  20use schemars::JsonSchema;
  21use serde::{Deserialize, Serialize};
  22use settings::{Settings, SettingsLocation, SettingsSources};
  23use smallvec::SmallVec;
  24use std::{
  25    any::{Any, TypeId},
  26    cell::RefCell,
  27    ops::Range,
  28    rc::Rc,
  29    sync::Arc,
  30    time::Duration,
  31};
  32use theme::Theme;
  33use ui::{Color, Element as _, Icon, IntoElement, Label, LabelCommon};
  34use util::ResultExt;
  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    pub activate_on_close: ActivateOnClose,
  43    pub file_icons: bool,
  44    pub show_diagnostics: ShowDiagnostics,
  45    pub show_close_button: ShowCloseButton,
  46}
  47
  48#[derive(Deserialize)]
  49pub struct PreviewTabsSettings {
  50    pub enabled: bool,
  51    pub enable_preview_from_file_finder: bool,
  52    pub enable_preview_from_code_navigation: bool,
  53}
  54
  55#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  56#[serde(rename_all = "lowercase")]
  57pub enum ClosePosition {
  58    Left,
  59    #[default]
  60    Right,
  61}
  62
  63#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  64#[serde(rename_all = "lowercase")]
  65pub enum ShowCloseButton {
  66    Always,
  67    #[default]
  68    Hover,
  69    Hidden,
  70}
  71
  72#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
  73#[serde(rename_all = "snake_case")]
  74pub enum ShowDiagnostics {
  75    #[default]
  76    Off,
  77    Errors,
  78    All,
  79}
  80
  81#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  82#[serde(rename_all = "snake_case")]
  83pub enum ActivateOnClose {
  84    #[default]
  85    History,
  86    Neighbour,
  87    LeftNeighbour,
  88}
  89
  90#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  91pub struct ItemSettingsContent {
  92    /// Whether to show the Git file status on a tab item.
  93    ///
  94    /// Default: false
  95    git_status: Option<bool>,
  96    /// Position of the close button in a tab.
  97    ///
  98    /// Default: right
  99    close_position: Option<ClosePosition>,
 100    /// Whether to show the file icon for a tab.
 101    ///
 102    /// Default: false
 103    file_icons: Option<bool>,
 104    /// What to do after closing the current tab.
 105    ///
 106    /// Default: history
 107    pub activate_on_close: Option<ActivateOnClose>,
 108    /// Which files containing diagnostic errors/warnings to mark in the tabs.
 109    /// This setting can take the following three values:
 110    ///
 111    /// Default: off
 112    show_diagnostics: Option<ShowDiagnostics>,
 113    /// Whether to always show the close button on tabs.
 114    ///
 115    /// Default: false
 116    show_close_button: Option<ShowCloseButton>,
 117}
 118
 119#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
 120pub struct PreviewTabsSettingsContent {
 121    /// Whether to show opened editors as preview tabs.
 122    /// 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.
 123    ///
 124    /// Default: true
 125    enabled: Option<bool>,
 126    /// Whether to open tabs in preview mode when selected from the file finder.
 127    ///
 128    /// Default: false
 129    enable_preview_from_file_finder: Option<bool>,
 130    /// Whether a preview tab gets replaced when code navigation is used to navigate away from the tab.
 131    ///
 132    /// Default: false
 133    enable_preview_from_code_navigation: Option<bool>,
 134}
 135
 136impl Settings for ItemSettings {
 137    const KEY: Option<&'static str> = Some("tabs");
 138
 139    type FileContent = ItemSettingsContent;
 140
 141    fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
 142        sources.json_merge()
 143    }
 144}
 145
 146impl Settings for PreviewTabsSettings {
 147    const KEY: Option<&'static str> = Some("preview_tabs");
 148
 149    type FileContent = PreviewTabsSettingsContent;
 150
 151    fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
 152        sources.json_merge()
 153    }
 154}
 155
 156#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
 157pub enum ItemEvent {
 158    CloseItem,
 159    UpdateTab,
 160    UpdateBreadcrumbs,
 161    Edit,
 162}
 163
 164// TODO: Combine this with existing HighlightedText struct?
 165pub struct BreadcrumbText {
 166    pub text: String,
 167    pub highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
 168    pub font: Option<Font>,
 169}
 170
 171#[derive(Debug, Clone, Copy)]
 172pub struct TabContentParams {
 173    pub detail: Option<usize>,
 174    pub selected: bool,
 175    pub preview: bool,
 176}
 177
 178impl TabContentParams {
 179    /// Returns the text color to be used for the tab content.
 180    pub fn text_color(&self) -> Color {
 181        if self.selected {
 182            Color::Default
 183        } else {
 184            Color::Muted
 185        }
 186    }
 187}
 188
 189pub enum TabTooltipContent {
 190    Text(SharedString),
 191    Custom(Box<dyn Fn(&mut Window, &mut App) -> AnyView>),
 192}
 193
 194pub trait Item: Focusable + EventEmitter<Self::Event> + Render + Sized {
 195    type Event;
 196
 197    /// Returns the tab contents.
 198    ///
 199    /// By default this returns a [`Label`] that displays that text from
 200    /// `tab_content_text`.
 201    fn tab_content(&self, params: TabContentParams, window: &Window, cx: &App) -> AnyElement {
 202        let Some(text) = self.tab_content_text(window, cx) else {
 203            return gpui::Empty.into_any();
 204        };
 205
 206        Label::new(text)
 207            .color(params.text_color())
 208            .into_any_element()
 209    }
 210
 211    /// Returns the textual contents of the tab.
 212    ///
 213    /// Use this if you don't need to customize the tab contents.
 214    fn tab_content_text(&self, _window: &Window, _cx: &App) -> Option<SharedString> {
 215        None
 216    }
 217
 218    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
 219        None
 220    }
 221
 222    /// Returns the tab tooltip text.
 223    ///
 224    /// Use this if you don't need to customize the tab tooltip content.
 225    fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
 226        None
 227    }
 228
 229    /// Returns the tab tooltip content.
 230    ///
 231    /// By default this returns a Tooltip text from
 232    /// `tab_tooltip_text`.
 233    fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
 234        self.tab_tooltip_text(cx).map(TabTooltipContent::Text)
 235    }
 236
 237    fn tab_description(&self, _: usize, _: &App) -> Option<SharedString> {
 238        None
 239    }
 240
 241    fn to_item_events(_event: &Self::Event, _f: impl FnMut(ItemEvent)) {}
 242
 243    fn deactivated(&mut self, _window: &mut Window, _: &mut Context<Self>) {}
 244    fn discarded(&self, _project: Entity<Project>, _window: &mut Window, _cx: &mut Context<Self>) {}
 245    fn workspace_deactivated(&mut self, _window: &mut Window, _: &mut Context<Self>) {}
 246    fn navigate(&mut self, _: Box<dyn Any>, _window: &mut Window, _: &mut Context<Self>) -> bool {
 247        false
 248    }
 249
 250    fn telemetry_event_text(&self) -> Option<&'static str> {
 251        None
 252    }
 253
 254    /// (model id, Item)
 255    fn for_each_project_item(
 256        &self,
 257        _: &App,
 258        _: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 259    ) {
 260    }
 261    fn is_singleton(&self, _cx: &App) -> bool {
 262        false
 263    }
 264    fn set_nav_history(&mut self, _: ItemNavHistory, _window: &mut Window, _: &mut Context<Self>) {}
 265    fn clone_on_split(
 266        &self,
 267        _workspace_id: Option<WorkspaceId>,
 268        _window: &mut Window,
 269        _: &mut Context<Self>,
 270    ) -> Option<Entity<Self>>
 271    where
 272        Self: Sized,
 273    {
 274        None
 275    }
 276    fn is_dirty(&self, _: &App) -> bool {
 277        false
 278    }
 279    fn has_deleted_file(&self, _: &App) -> bool {
 280        false
 281    }
 282    fn has_conflict(&self, _: &App) -> bool {
 283        false
 284    }
 285    fn can_save(&self, _cx: &App) -> bool {
 286        false
 287    }
 288    fn can_save_as(&self, _: &App) -> bool {
 289        false
 290    }
 291    fn save(
 292        &mut self,
 293        _format: bool,
 294        _project: Entity<Project>,
 295        _window: &mut Window,
 296        _cx: &mut Context<Self>,
 297    ) -> Task<Result<()>> {
 298        unimplemented!("save() must be implemented if can_save() returns true")
 299    }
 300    fn save_as(
 301        &mut self,
 302        _project: Entity<Project>,
 303        _path: ProjectPath,
 304        _window: &mut Window,
 305        _cx: &mut Context<Self>,
 306    ) -> Task<Result<()>> {
 307        unimplemented!("save_as() must be implemented if can_save() returns true")
 308    }
 309    fn reload(
 310        &mut self,
 311        _project: Entity<Project>,
 312        _window: &mut Window,
 313        _cx: &mut Context<Self>,
 314    ) -> Task<Result<()>> {
 315        unimplemented!("reload() must be implemented if can_save() returns true")
 316    }
 317
 318    fn act_as_type<'a>(
 319        &'a self,
 320        type_id: TypeId,
 321        self_handle: &'a Entity<Self>,
 322        _: &'a App,
 323    ) -> Option<AnyView> {
 324        if TypeId::of::<Self>() == type_id {
 325            Some(self_handle.clone().into())
 326        } else {
 327            None
 328        }
 329    }
 330
 331    fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 332        None
 333    }
 334
 335    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 336        ToolbarItemLocation::Hidden
 337    }
 338
 339    fn breadcrumbs(&self, _theme: &Theme, _cx: &App) -> Option<Vec<BreadcrumbText>> {
 340        None
 341    }
 342
 343    fn added_to_workspace(
 344        &mut self,
 345        _workspace: &mut Workspace,
 346        _window: &mut Window,
 347        _cx: &mut Context<Self>,
 348    ) {
 349    }
 350
 351    fn show_toolbar(&self) -> bool {
 352        true
 353    }
 354
 355    fn pixel_position_of_cursor(&self, _: &App) -> Option<Point<Pixels>> {
 356        None
 357    }
 358
 359    fn preserve_preview(&self, _cx: &App) -> bool {
 360        false
 361    }
 362
 363    fn include_in_nav_history() -> bool {
 364        true
 365    }
 366}
 367
 368pub trait SerializableItem: Item {
 369    fn serialized_item_kind() -> &'static str;
 370
 371    fn cleanup(
 372        workspace_id: WorkspaceId,
 373        alive_items: Vec<ItemId>,
 374        window: &mut Window,
 375        cx: &mut App,
 376    ) -> Task<Result<()>>;
 377
 378    fn deserialize(
 379        _project: Entity<Project>,
 380        _workspace: WeakEntity<Workspace>,
 381        _workspace_id: WorkspaceId,
 382        _item_id: ItemId,
 383        _window: &mut Window,
 384        _cx: &mut App,
 385    ) -> Task<Result<Entity<Self>>>;
 386
 387    fn serialize(
 388        &mut self,
 389        workspace: &mut Workspace,
 390        item_id: ItemId,
 391        closing: bool,
 392        window: &mut Window,
 393        cx: &mut Context<Self>,
 394    ) -> Option<Task<Result<()>>>;
 395
 396    fn should_serialize(&self, event: &Self::Event) -> bool;
 397}
 398
 399pub trait SerializableItemHandle: ItemHandle {
 400    fn serialized_item_kind(&self) -> &'static str;
 401    fn serialize(
 402        &self,
 403        workspace: &mut Workspace,
 404        closing: bool,
 405        window: &mut Window,
 406        cx: &mut App,
 407    ) -> Option<Task<Result<()>>>;
 408    fn should_serialize(&self, event: &dyn Any, cx: &App) -> bool;
 409}
 410
 411impl<T> SerializableItemHandle for Entity<T>
 412where
 413    T: SerializableItem,
 414{
 415    fn serialized_item_kind(&self) -> &'static str {
 416        T::serialized_item_kind()
 417    }
 418
 419    fn serialize(
 420        &self,
 421        workspace: &mut Workspace,
 422        closing: bool,
 423        window: &mut Window,
 424        cx: &mut App,
 425    ) -> Option<Task<Result<()>>> {
 426        self.update(cx, |this, cx| {
 427            this.serialize(workspace, cx.entity_id().as_u64(), closing, window, cx)
 428        })
 429    }
 430
 431    fn should_serialize(&self, event: &dyn Any, cx: &App) -> bool {
 432        event
 433            .downcast_ref::<T::Event>()
 434            .map_or(false, |event| self.read(cx).should_serialize(event))
 435    }
 436}
 437
 438pub trait ItemHandle: 'static + Send {
 439    fn item_focus_handle(&self, cx: &App) -> FocusHandle;
 440    fn subscribe_to_item_events(
 441        &self,
 442        window: &mut Window,
 443        cx: &mut App,
 444        handler: Box<dyn Fn(ItemEvent, &mut Window, &mut App)>,
 445    ) -> gpui::Subscription;
 446    fn tab_description(&self, detail: usize, cx: &App) -> Option<SharedString>;
 447    fn tab_content(&self, params: TabContentParams, window: &Window, cx: &App) -> AnyElement;
 448    fn tab_icon(&self, window: &Window, cx: &App) -> Option<Icon>;
 449    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString>;
 450    fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent>;
 451    fn telemetry_event_text(&self, cx: &App) -> Option<&'static str>;
 452    fn dragged_tab_content(
 453        &self,
 454        params: TabContentParams,
 455        window: &Window,
 456        cx: &App,
 457    ) -> AnyElement;
 458    fn project_path(&self, cx: &App) -> Option<ProjectPath>;
 459    fn project_entry_ids(&self, cx: &App) -> SmallVec<[ProjectEntryId; 3]>;
 460    fn project_paths(&self, cx: &App) -> SmallVec<[ProjectPath; 3]>;
 461    fn project_item_model_ids(&self, cx: &App) -> SmallVec<[EntityId; 3]>;
 462    fn for_each_project_item(
 463        &self,
 464        _: &App,
 465        _: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 466    );
 467    fn is_singleton(&self, cx: &App) -> bool;
 468    fn boxed_clone(&self) -> Box<dyn ItemHandle>;
 469    fn clone_on_split(
 470        &self,
 471        workspace_id: Option<WorkspaceId>,
 472        window: &mut Window,
 473        cx: &mut App,
 474    ) -> Option<Box<dyn ItemHandle>>;
 475    fn added_to_pane(
 476        &self,
 477        workspace: &mut Workspace,
 478        pane: Entity<Pane>,
 479        window: &mut Window,
 480        cx: &mut Context<Workspace>,
 481    );
 482    fn deactivated(&self, window: &mut Window, cx: &mut App);
 483    fn discarded(&self, project: Entity<Project>, window: &mut Window, cx: &mut App);
 484    fn workspace_deactivated(&self, window: &mut Window, cx: &mut App);
 485    fn navigate(&self, data: Box<dyn Any>, window: &mut Window, cx: &mut App) -> bool;
 486    fn item_id(&self) -> EntityId;
 487    fn to_any(&self) -> AnyView;
 488    fn is_dirty(&self, cx: &App) -> bool;
 489    fn has_deleted_file(&self, cx: &App) -> bool;
 490    fn has_conflict(&self, cx: &App) -> bool;
 491    fn can_save(&self, cx: &App) -> bool;
 492    fn can_save_as(&self, cx: &App) -> bool;
 493    fn save(
 494        &self,
 495        format: bool,
 496        project: Entity<Project>,
 497        window: &mut Window,
 498        cx: &mut App,
 499    ) -> Task<Result<()>>;
 500    fn save_as(
 501        &self,
 502        project: Entity<Project>,
 503        path: ProjectPath,
 504        window: &mut Window,
 505        cx: &mut App,
 506    ) -> Task<Result<()>>;
 507    fn reload(
 508        &self,
 509        project: Entity<Project>,
 510        window: &mut Window,
 511        cx: &mut App,
 512    ) -> Task<Result<()>>;
 513    fn act_as_type(&self, type_id: TypeId, cx: &App) -> Option<AnyView>;
 514    fn to_followable_item_handle(&self, cx: &App) -> Option<Box<dyn FollowableItemHandle>>;
 515    fn to_serializable_item_handle(&self, cx: &App) -> Option<Box<dyn SerializableItemHandle>>;
 516    fn on_release(
 517        &self,
 518        cx: &mut App,
 519        callback: Box<dyn FnOnce(&mut App) + Send>,
 520    ) -> gpui::Subscription;
 521    fn to_searchable_item_handle(&self, cx: &App) -> Option<Box<dyn SearchableItemHandle>>;
 522    fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation;
 523    fn breadcrumbs(&self, theme: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>>;
 524    fn show_toolbar(&self, cx: &App) -> bool;
 525    fn pixel_position_of_cursor(&self, cx: &App) -> Option<Point<Pixels>>;
 526    fn downgrade_item(&self) -> Box<dyn WeakItemHandle>;
 527    fn workspace_settings<'a>(&self, cx: &'a App) -> &'a WorkspaceSettings;
 528    fn preserve_preview(&self, cx: &App) -> bool;
 529    fn include_in_nav_history(&self) -> bool;
 530    fn relay_action(&self, action: Box<dyn Action>, window: &mut Window, cx: &mut App);
 531}
 532
 533pub trait WeakItemHandle: Send + Sync {
 534    fn id(&self) -> EntityId;
 535    fn boxed_clone(&self) -> Box<dyn WeakItemHandle>;
 536    fn upgrade(&self) -> Option<Box<dyn ItemHandle>>;
 537}
 538
 539impl dyn ItemHandle {
 540    pub fn downcast<V: 'static>(&self) -> Option<Entity<V>> {
 541        self.to_any().downcast().ok()
 542    }
 543
 544    pub fn act_as<V: 'static>(&self, cx: &App) -> Option<Entity<V>> {
 545        self.act_as_type(TypeId::of::<V>(), cx)
 546            .and_then(|t| t.downcast().ok())
 547    }
 548}
 549
 550impl<T: Item> ItemHandle for Entity<T> {
 551    fn subscribe_to_item_events(
 552        &self,
 553        window: &mut Window,
 554        cx: &mut App,
 555        handler: Box<dyn Fn(ItemEvent, &mut Window, &mut App)>,
 556    ) -> gpui::Subscription {
 557        window.subscribe(self, cx, move |_, event, window, cx| {
 558            T::to_item_events(event, |item_event| handler(item_event, window, cx));
 559        })
 560    }
 561
 562    fn item_focus_handle(&self, cx: &App) -> FocusHandle {
 563        self.read(cx).focus_handle(cx)
 564    }
 565
 566    fn telemetry_event_text(&self, cx: &App) -> Option<&'static str> {
 567        self.read(cx).telemetry_event_text()
 568    }
 569
 570    fn tab_description(&self, detail: usize, cx: &App) -> Option<SharedString> {
 571        self.read(cx).tab_description(detail, cx)
 572    }
 573
 574    fn tab_content(&self, params: TabContentParams, window: &Window, cx: &App) -> AnyElement {
 575        self.read(cx).tab_content(params, window, cx)
 576    }
 577
 578    fn tab_icon(&self, window: &Window, cx: &App) -> Option<Icon> {
 579        self.read(cx).tab_icon(window, cx)
 580    }
 581
 582    fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
 583        self.read(cx).tab_tooltip_content(cx)
 584    }
 585
 586    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
 587        self.read(cx).tab_tooltip_text(cx)
 588    }
 589
 590    fn dragged_tab_content(
 591        &self,
 592        params: TabContentParams,
 593        window: &Window,
 594        cx: &App,
 595    ) -> AnyElement {
 596        self.read(cx).tab_content(
 597            TabContentParams {
 598                selected: true,
 599                ..params
 600            },
 601            window,
 602            cx,
 603        )
 604    }
 605
 606    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
 607        let this = self.read(cx);
 608        let mut result = None;
 609        if this.is_singleton(cx) {
 610            this.for_each_project_item(cx, &mut |_, item| {
 611                result = item.project_path(cx);
 612            });
 613        }
 614        result
 615    }
 616
 617    fn workspace_settings<'a>(&self, cx: &'a App) -> &'a WorkspaceSettings {
 618        if let Some(project_path) = self.project_path(cx) {
 619            WorkspaceSettings::get(
 620                Some(SettingsLocation {
 621                    worktree_id: project_path.worktree_id,
 622                    path: &project_path.path,
 623                }),
 624                cx,
 625            )
 626        } else {
 627            WorkspaceSettings::get_global(cx)
 628        }
 629    }
 630
 631    fn project_entry_ids(&self, cx: &App) -> SmallVec<[ProjectEntryId; 3]> {
 632        let mut result = SmallVec::new();
 633        self.read(cx).for_each_project_item(cx, &mut |_, item| {
 634            if let Some(id) = item.entry_id(cx) {
 635                result.push(id);
 636            }
 637        });
 638        result
 639    }
 640
 641    fn project_paths(&self, cx: &App) -> SmallVec<[ProjectPath; 3]> {
 642        let mut result = SmallVec::new();
 643        self.read(cx).for_each_project_item(cx, &mut |_, item| {
 644            if let Some(id) = item.project_path(cx) {
 645                result.push(id);
 646            }
 647        });
 648        result
 649    }
 650
 651    fn project_item_model_ids(&self, cx: &App) -> SmallVec<[EntityId; 3]> {
 652        let mut result = SmallVec::new();
 653        self.read(cx).for_each_project_item(cx, &mut |id, _| {
 654            result.push(id);
 655        });
 656        result
 657    }
 658
 659    fn for_each_project_item(
 660        &self,
 661        cx: &App,
 662        f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 663    ) {
 664        self.read(cx).for_each_project_item(cx, f)
 665    }
 666
 667    fn is_singleton(&self, cx: &App) -> bool {
 668        self.read(cx).is_singleton(cx)
 669    }
 670
 671    fn boxed_clone(&self) -> Box<dyn ItemHandle> {
 672        Box::new(self.clone())
 673    }
 674
 675    fn clone_on_split(
 676        &self,
 677        workspace_id: Option<WorkspaceId>,
 678        window: &mut Window,
 679        cx: &mut App,
 680    ) -> Option<Box<dyn ItemHandle>> {
 681        self.update(cx, |item, cx| item.clone_on_split(workspace_id, window, cx))
 682            .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
 683    }
 684
 685    fn added_to_pane(
 686        &self,
 687        workspace: &mut Workspace,
 688        pane: Entity<Pane>,
 689        window: &mut Window,
 690        cx: &mut Context<Workspace>,
 691    ) {
 692        let weak_item = self.downgrade();
 693        let history = pane.read(cx).nav_history_for_item(self);
 694        self.update(cx, |this, cx| {
 695            this.set_nav_history(history, window, cx);
 696            this.added_to_workspace(workspace, window, cx);
 697        });
 698
 699        if let Some(serializable_item) = self.to_serializable_item_handle(cx) {
 700            workspace
 701                .enqueue_item_serialization(serializable_item)
 702                .log_err();
 703        }
 704
 705        if workspace
 706            .panes_by_item
 707            .insert(self.item_id(), pane.downgrade())
 708            .is_none()
 709        {
 710            let mut pending_autosave = DelayedDebouncedEditAction::new();
 711            let (pending_update_tx, mut pending_update_rx) = mpsc::unbounded();
 712            let pending_update = Rc::new(RefCell::new(None));
 713
 714            let mut send_follower_updates = None;
 715            if let Some(item) = self.to_followable_item_handle(cx) {
 716                let is_project_item = item.is_project_item(window, cx);
 717                let item = item.downgrade();
 718
 719                send_follower_updates = Some(cx.spawn_in(window, {
 720                    let pending_update = pending_update.clone();
 721                    |workspace, mut cx| async move {
 722                        while let Some(mut leader_id) = pending_update_rx.next().await {
 723                            while let Ok(Some(id)) = pending_update_rx.try_next() {
 724                                leader_id = id;
 725                            }
 726
 727                            workspace.update_in(&mut cx, |workspace, window, cx| {
 728                                let Some(item) = item.upgrade() else { return };
 729                                workspace.update_followers(
 730                                    is_project_item,
 731                                    proto::update_followers::Variant::UpdateView(
 732                                        proto::UpdateView {
 733                                            id: item
 734                                                .remote_id(workspace.client(), window, cx)
 735                                                .map(|id| id.to_proto()),
 736                                            variant: pending_update.borrow_mut().take(),
 737                                            leader_id,
 738                                        },
 739                                    ),
 740                                    window,
 741                                    cx,
 742                                );
 743                            })?;
 744                            cx.background_executor().timer(LEADER_UPDATE_THROTTLE).await;
 745                        }
 746                        anyhow::Ok(())
 747                    }
 748                }));
 749            }
 750
 751            let mut event_subscription = Some(cx.subscribe_in(
 752                self,
 753                window,
 754                move |workspace, item: &Entity<T>, event, window, cx| {
 755                    let pane = if let Some(pane) = workspace
 756                        .panes_by_item
 757                        .get(&item.item_id())
 758                        .and_then(|pane| pane.upgrade())
 759                    {
 760                        pane
 761                    } else {
 762                        return;
 763                    };
 764
 765                    if let Some(item) = item.to_followable_item_handle(cx) {
 766                        let leader_id = workspace.leader_for_pane(&pane);
 767
 768                        if let Some(leader_id) = leader_id {
 769                            if let Some(FollowEvent::Unfollow) = item.to_follow_event(event) {
 770                                workspace.unfollow(leader_id, window, cx);
 771                            }
 772                        }
 773
 774                        if item.item_focus_handle(cx).contains_focused(window, cx) {
 775                            item.add_event_to_update_proto(
 776                                event,
 777                                &mut pending_update.borrow_mut(),
 778                                window,
 779                                cx,
 780                            );
 781                            pending_update_tx.unbounded_send(leader_id).ok();
 782                        }
 783                    }
 784
 785                    if let Some(item) = item.to_serializable_item_handle(cx) {
 786                        if item.should_serialize(event, cx) {
 787                            workspace.enqueue_item_serialization(item).ok();
 788                        }
 789                    }
 790
 791                    T::to_item_events(event, |event| match event {
 792                        ItemEvent::CloseItem => {
 793                            pane.update(cx, |pane, cx| {
 794                                pane.close_item_by_id(
 795                                    item.item_id(),
 796                                    crate::SaveIntent::Close,
 797                                    window,
 798                                    cx,
 799                                )
 800                            })
 801                            .detach_and_log_err(cx);
 802                        }
 803
 804                        ItemEvent::UpdateTab => {
 805                            pane.update(cx, |_, cx| {
 806                                cx.emit(pane::Event::ChangeItemTitle);
 807                                cx.notify();
 808                            });
 809                        }
 810
 811                        ItemEvent::Edit => {
 812                            let autosave = item.workspace_settings(cx).autosave;
 813
 814                            if let AutosaveSetting::AfterDelay { milliseconds } = autosave {
 815                                let delay = Duration::from_millis(milliseconds);
 816                                let item = item.clone();
 817                                pending_autosave.fire_new(
 818                                    delay,
 819                                    window,
 820                                    cx,
 821                                    move |workspace, window, cx| {
 822                                        Pane::autosave_item(
 823                                            &item,
 824                                            workspace.project().clone(),
 825                                            window,
 826                                            cx,
 827                                        )
 828                                    },
 829                                );
 830                            }
 831                            pane.update(cx, |pane, cx| pane.handle_item_edit(item.item_id(), cx));
 832                        }
 833
 834                        _ => {}
 835                    });
 836                },
 837            ));
 838
 839            cx.on_blur(
 840                &self.read(cx).focus_handle(cx),
 841                window,
 842                move |workspace, window, cx| {
 843                    if let Some(item) = weak_item.upgrade() {
 844                        if item.workspace_settings(cx).autosave == AutosaveSetting::OnFocusChange {
 845                            Pane::autosave_item(&item, workspace.project.clone(), window, cx)
 846                                .detach_and_log_err(cx);
 847                        }
 848                    }
 849                },
 850            )
 851            .detach();
 852
 853            let item_id = self.item_id();
 854            cx.observe_release_in(self, window, move |workspace, _, _, _| {
 855                workspace.panes_by_item.remove(&item_id);
 856                event_subscription.take();
 857                send_follower_updates.take();
 858            })
 859            .detach();
 860        }
 861
 862        cx.defer_in(window, |workspace, window, cx| {
 863            workspace.serialize_workspace(window, cx);
 864        });
 865    }
 866
 867    fn discarded(&self, project: Entity<Project>, window: &mut Window, cx: &mut App) {
 868        self.update(cx, |this, cx| this.discarded(project, window, cx));
 869    }
 870
 871    fn deactivated(&self, window: &mut Window, cx: &mut App) {
 872        self.update(cx, |this, cx| this.deactivated(window, cx));
 873    }
 874
 875    fn workspace_deactivated(&self, window: &mut Window, cx: &mut App) {
 876        self.update(cx, |this, cx| this.workspace_deactivated(window, cx));
 877    }
 878
 879    fn navigate(&self, data: Box<dyn Any>, window: &mut Window, cx: &mut App) -> bool {
 880        self.update(cx, |this, cx| this.navigate(data, window, cx))
 881    }
 882
 883    fn item_id(&self) -> EntityId {
 884        self.entity_id()
 885    }
 886
 887    fn to_any(&self) -> AnyView {
 888        self.clone().into()
 889    }
 890
 891    fn is_dirty(&self, cx: &App) -> bool {
 892        self.read(cx).is_dirty(cx)
 893    }
 894
 895    fn has_deleted_file(&self, cx: &App) -> bool {
 896        self.read(cx).has_deleted_file(cx)
 897    }
 898
 899    fn has_conflict(&self, cx: &App) -> bool {
 900        self.read(cx).has_conflict(cx)
 901    }
 902
 903    fn can_save(&self, cx: &App) -> bool {
 904        self.read(cx).can_save(cx)
 905    }
 906
 907    fn can_save_as(&self, cx: &App) -> bool {
 908        self.read(cx).can_save_as(cx)
 909    }
 910
 911    fn save(
 912        &self,
 913        format: bool,
 914        project: Entity<Project>,
 915        window: &mut Window,
 916        cx: &mut App,
 917    ) -> Task<Result<()>> {
 918        self.update(cx, |item, cx| item.save(format, project, window, cx))
 919    }
 920
 921    fn save_as(
 922        &self,
 923        project: Entity<Project>,
 924        path: ProjectPath,
 925        window: &mut Window,
 926        cx: &mut App,
 927    ) -> Task<anyhow::Result<()>> {
 928        self.update(cx, |item, cx| item.save_as(project, path, window, cx))
 929    }
 930
 931    fn reload(
 932        &self,
 933        project: Entity<Project>,
 934        window: &mut Window,
 935        cx: &mut App,
 936    ) -> Task<Result<()>> {
 937        self.update(cx, |item, cx| item.reload(project, window, cx))
 938    }
 939
 940    fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a App) -> Option<AnyView> {
 941        self.read(cx).act_as_type(type_id, self, cx)
 942    }
 943
 944    fn to_followable_item_handle(&self, cx: &App) -> Option<Box<dyn FollowableItemHandle>> {
 945        FollowableViewRegistry::to_followable_view(self.clone(), cx)
 946    }
 947
 948    fn on_release(
 949        &self,
 950        cx: &mut App,
 951        callback: Box<dyn FnOnce(&mut App) + Send>,
 952    ) -> gpui::Subscription {
 953        cx.observe_release(self, move |_, cx| callback(cx))
 954    }
 955
 956    fn to_searchable_item_handle(&self, cx: &App) -> Option<Box<dyn SearchableItemHandle>> {
 957        self.read(cx).as_searchable(self)
 958    }
 959
 960    fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
 961        self.read(cx).breadcrumb_location(cx)
 962    }
 963
 964    fn breadcrumbs(&self, theme: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
 965        self.read(cx).breadcrumbs(theme, cx)
 966    }
 967
 968    fn show_toolbar(&self, cx: &App) -> bool {
 969        self.read(cx).show_toolbar()
 970    }
 971
 972    fn pixel_position_of_cursor(&self, cx: &App) -> Option<Point<Pixels>> {
 973        self.read(cx).pixel_position_of_cursor(cx)
 974    }
 975
 976    fn downgrade_item(&self) -> Box<dyn WeakItemHandle> {
 977        Box::new(self.downgrade())
 978    }
 979
 980    fn to_serializable_item_handle(&self, cx: &App) -> Option<Box<dyn SerializableItemHandle>> {
 981        SerializableItemRegistry::view_to_serializable_item_handle(self.to_any(), cx)
 982    }
 983
 984    fn preserve_preview(&self, cx: &App) -> bool {
 985        self.read(cx).preserve_preview(cx)
 986    }
 987
 988    fn include_in_nav_history(&self) -> bool {
 989        T::include_in_nav_history()
 990    }
 991
 992    fn relay_action(&self, action: Box<dyn Action>, window: &mut Window, cx: &mut App) {
 993        self.update(cx, |this, cx| {
 994            this.focus_handle(cx).focus(window);
 995            window.dispatch_action(action, cx);
 996        })
 997    }
 998}
 999
1000impl From<Box<dyn ItemHandle>> for AnyView {
1001    fn from(val: Box<dyn ItemHandle>) -> Self {
1002        val.to_any()
1003    }
1004}
1005
1006impl From<&Box<dyn ItemHandle>> for AnyView {
1007    fn from(val: &Box<dyn ItemHandle>) -> Self {
1008        val.to_any()
1009    }
1010}
1011
1012impl Clone for Box<dyn ItemHandle> {
1013    fn clone(&self) -> Box<dyn ItemHandle> {
1014        self.boxed_clone()
1015    }
1016}
1017
1018impl<T: Item> WeakItemHandle for WeakEntity<T> {
1019    fn id(&self) -> EntityId {
1020        self.entity_id()
1021    }
1022
1023    fn boxed_clone(&self) -> Box<dyn WeakItemHandle> {
1024        Box::new(self.clone())
1025    }
1026
1027    fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
1028        self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
1029    }
1030}
1031
1032pub trait ProjectItem: Item {
1033    type Item: project::ProjectItem;
1034
1035    fn for_project_item(
1036        project: Entity<Project>,
1037        item: Entity<Self::Item>,
1038        window: &mut Window,
1039        cx: &mut Context<Self>,
1040    ) -> Self
1041    where
1042        Self: Sized;
1043}
1044
1045#[derive(Debug)]
1046pub enum FollowEvent {
1047    Unfollow,
1048}
1049
1050pub enum Dedup {
1051    KeepExisting,
1052    ReplaceExisting,
1053}
1054
1055pub trait FollowableItem: Item {
1056    fn remote_id(&self) -> Option<ViewId>;
1057    fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant>;
1058    fn from_state_proto(
1059        project: Entity<Workspace>,
1060        id: ViewId,
1061        state: &mut Option<proto::view::Variant>,
1062        window: &mut Window,
1063        cx: &mut App,
1064    ) -> Option<Task<Result<Entity<Self>>>>;
1065    fn to_follow_event(event: &Self::Event) -> Option<FollowEvent>;
1066    fn add_event_to_update_proto(
1067        &self,
1068        event: &Self::Event,
1069        update: &mut Option<proto::update_view::Variant>,
1070        window: &Window,
1071        cx: &App,
1072    ) -> bool;
1073    fn apply_update_proto(
1074        &mut self,
1075        project: &Entity<Project>,
1076        message: proto::update_view::Variant,
1077        window: &mut Window,
1078        cx: &mut Context<Self>,
1079    ) -> Task<Result<()>>;
1080    fn is_project_item(&self, window: &Window, cx: &App) -> bool;
1081    fn set_leader_peer_id(
1082        &mut self,
1083        leader_peer_id: Option<PeerId>,
1084        window: &mut Window,
1085        cx: &mut Context<Self>,
1086    );
1087    fn dedup(&self, existing: &Self, window: &Window, cx: &App) -> Option<Dedup>;
1088}
1089
1090pub trait FollowableItemHandle: ItemHandle {
1091    fn remote_id(&self, client: &Arc<Client>, window: &mut Window, cx: &mut App) -> Option<ViewId>;
1092    fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle>;
1093    fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, window: &mut Window, cx: &mut App);
1094    fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant>;
1095    fn add_event_to_update_proto(
1096        &self,
1097        event: &dyn Any,
1098        update: &mut Option<proto::update_view::Variant>,
1099        window: &mut Window,
1100        cx: &mut App,
1101    ) -> bool;
1102    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
1103    fn apply_update_proto(
1104        &self,
1105        project: &Entity<Project>,
1106        message: proto::update_view::Variant,
1107        window: &mut Window,
1108        cx: &mut App,
1109    ) -> Task<Result<()>>;
1110    fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool;
1111    fn dedup(
1112        &self,
1113        existing: &dyn FollowableItemHandle,
1114        window: &mut Window,
1115        cx: &mut App,
1116    ) -> Option<Dedup>;
1117}
1118
1119impl<T: FollowableItem> FollowableItemHandle for Entity<T> {
1120    fn remote_id(&self, client: &Arc<Client>, _: &mut Window, cx: &mut App) -> Option<ViewId> {
1121        self.read(cx).remote_id().or_else(|| {
1122            client.peer_id().map(|creator| ViewId {
1123                creator,
1124                id: self.item_id().as_u64(),
1125            })
1126        })
1127    }
1128
1129    fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle> {
1130        Box::new(self.downgrade())
1131    }
1132
1133    fn set_leader_peer_id(
1134        &self,
1135        leader_peer_id: Option<PeerId>,
1136        window: &mut Window,
1137        cx: &mut App,
1138    ) {
1139        self.update(cx, |this, cx| {
1140            this.set_leader_peer_id(leader_peer_id, window, cx)
1141        })
1142    }
1143
1144    fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant> {
1145        self.read(cx).to_state_proto(window, cx)
1146    }
1147
1148    fn add_event_to_update_proto(
1149        &self,
1150        event: &dyn Any,
1151        update: &mut Option<proto::update_view::Variant>,
1152        window: &mut Window,
1153        cx: &mut App,
1154    ) -> bool {
1155        if let Some(event) = event.downcast_ref() {
1156            self.read(cx)
1157                .add_event_to_update_proto(event, update, window, cx)
1158        } else {
1159            false
1160        }
1161    }
1162
1163    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
1164        T::to_follow_event(event.downcast_ref()?)
1165    }
1166
1167    fn apply_update_proto(
1168        &self,
1169        project: &Entity<Project>,
1170        message: proto::update_view::Variant,
1171        window: &mut Window,
1172        cx: &mut App,
1173    ) -> Task<Result<()>> {
1174        self.update(cx, |this, cx| {
1175            this.apply_update_proto(project, message, window, cx)
1176        })
1177    }
1178
1179    fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool {
1180        self.read(cx).is_project_item(window, cx)
1181    }
1182
1183    fn dedup(
1184        &self,
1185        existing: &dyn FollowableItemHandle,
1186        window: &mut Window,
1187        cx: &mut App,
1188    ) -> Option<Dedup> {
1189        let existing = existing.to_any().downcast::<T>().ok()?;
1190        self.read(cx).dedup(existing.read(cx), window, cx)
1191    }
1192}
1193
1194pub trait WeakFollowableItemHandle: Send + Sync {
1195    fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>>;
1196}
1197
1198impl<T: FollowableItem> WeakFollowableItemHandle for WeakEntity<T> {
1199    fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>> {
1200        Some(Box::new(self.upgrade()?))
1201    }
1202}
1203
1204#[cfg(any(test, feature = "test-support"))]
1205pub mod test {
1206    use super::{Item, ItemEvent, SerializableItem, TabContentParams};
1207    use crate::{ItemId, ItemNavHistory, Workspace, WorkspaceId};
1208    use gpui::{
1209        AnyElement, App, AppContext as _, Context, Entity, EntityId, EventEmitter, Focusable,
1210        InteractiveElement, IntoElement, Render, SharedString, Task, WeakEntity, Window,
1211    };
1212    use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
1213    use std::{any::Any, cell::Cell, path::Path};
1214
1215    pub struct TestProjectItem {
1216        pub entry_id: Option<ProjectEntryId>,
1217        pub project_path: Option<ProjectPath>,
1218        pub is_dirty: bool,
1219    }
1220
1221    pub struct TestItem {
1222        pub workspace_id: Option<WorkspaceId>,
1223        pub state: String,
1224        pub label: String,
1225        pub save_count: usize,
1226        pub save_as_count: usize,
1227        pub reload_count: usize,
1228        pub is_dirty: bool,
1229        pub is_singleton: bool,
1230        pub has_conflict: bool,
1231        pub project_items: Vec<Entity<TestProjectItem>>,
1232        pub nav_history: Option<ItemNavHistory>,
1233        pub tab_descriptions: Option<Vec<&'static str>>,
1234        pub tab_detail: Cell<Option<usize>>,
1235        serialize: Option<Box<dyn Fn() -> Option<Task<anyhow::Result<()>>>>>,
1236        focus_handle: gpui::FocusHandle,
1237    }
1238
1239    impl project::ProjectItem for TestProjectItem {
1240        fn try_open(
1241            _project: &Entity<Project>,
1242            _path: &ProjectPath,
1243            _cx: &mut App,
1244        ) -> Option<Task<gpui::Result<Entity<Self>>>> {
1245            None
1246        }
1247        fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
1248            self.entry_id
1249        }
1250
1251        fn project_path(&self, _: &App) -> Option<ProjectPath> {
1252            self.project_path.clone()
1253        }
1254
1255        fn is_dirty(&self) -> bool {
1256            self.is_dirty
1257        }
1258    }
1259
1260    pub enum TestItemEvent {
1261        Edit,
1262    }
1263
1264    impl TestProjectItem {
1265        pub fn new(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1266            let entry_id = Some(ProjectEntryId::from_proto(id));
1267            let project_path = Some(ProjectPath {
1268                worktree_id: WorktreeId::from_usize(0),
1269                path: Path::new(path).into(),
1270            });
1271            cx.new(|_| Self {
1272                entry_id,
1273                project_path,
1274                is_dirty: false,
1275            })
1276        }
1277
1278        pub fn new_untitled(cx: &mut App) -> Entity<Self> {
1279            cx.new(|_| Self {
1280                project_path: None,
1281                entry_id: None,
1282                is_dirty: false,
1283            })
1284        }
1285
1286        pub fn new_dirty(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1287            let entry_id = Some(ProjectEntryId::from_proto(id));
1288            let project_path = Some(ProjectPath {
1289                worktree_id: WorktreeId::from_usize(0),
1290                path: Path::new(path).into(),
1291            });
1292            cx.new(|_| Self {
1293                entry_id,
1294                project_path,
1295                is_dirty: true,
1296            })
1297        }
1298    }
1299
1300    impl TestItem {
1301        pub fn new(cx: &mut Context<Self>) -> Self {
1302            Self {
1303                state: String::new(),
1304                label: String::new(),
1305                save_count: 0,
1306                save_as_count: 0,
1307                reload_count: 0,
1308                is_dirty: false,
1309                has_conflict: false,
1310                project_items: Vec::new(),
1311                is_singleton: true,
1312                nav_history: None,
1313                tab_descriptions: None,
1314                tab_detail: Default::default(),
1315                workspace_id: Default::default(),
1316                focus_handle: cx.focus_handle(),
1317                serialize: None,
1318            }
1319        }
1320
1321        pub fn new_deserialized(id: WorkspaceId, cx: &mut Context<Self>) -> Self {
1322            let mut this = Self::new(cx);
1323            this.workspace_id = Some(id);
1324            this
1325        }
1326
1327        pub fn with_label(mut self, state: &str) -> Self {
1328            self.label = state.to_string();
1329            self
1330        }
1331
1332        pub fn with_singleton(mut self, singleton: bool) -> Self {
1333            self.is_singleton = singleton;
1334            self
1335        }
1336
1337        pub fn with_dirty(mut self, dirty: bool) -> Self {
1338            self.is_dirty = dirty;
1339            self
1340        }
1341
1342        pub fn with_conflict(mut self, has_conflict: bool) -> Self {
1343            self.has_conflict = has_conflict;
1344            self
1345        }
1346
1347        pub fn with_project_items(mut self, items: &[Entity<TestProjectItem>]) -> Self {
1348            self.project_items.clear();
1349            self.project_items.extend(items.iter().cloned());
1350            self
1351        }
1352
1353        pub fn with_serialize(
1354            mut self,
1355            serialize: impl Fn() -> Option<Task<anyhow::Result<()>>> + 'static,
1356        ) -> Self {
1357            self.serialize = Some(Box::new(serialize));
1358            self
1359        }
1360
1361        pub fn set_state(&mut self, state: String, cx: &mut Context<Self>) {
1362            self.push_to_nav_history(cx);
1363            self.state = state;
1364        }
1365
1366        fn push_to_nav_history(&mut self, cx: &mut Context<Self>) {
1367            if let Some(history) = &mut self.nav_history {
1368                history.push(Some(Box::new(self.state.clone())), cx);
1369            }
1370        }
1371    }
1372
1373    impl Render for TestItem {
1374        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1375            gpui::div().track_focus(&self.focus_handle(cx))
1376        }
1377    }
1378
1379    impl EventEmitter<ItemEvent> for TestItem {}
1380
1381    impl Focusable for TestItem {
1382        fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
1383            self.focus_handle.clone()
1384        }
1385    }
1386
1387    impl Item for TestItem {
1388        type Event = ItemEvent;
1389
1390        fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1391            f(*event)
1392        }
1393
1394        fn tab_description(&self, detail: usize, _: &App) -> Option<SharedString> {
1395            self.tab_descriptions.as_ref().and_then(|descriptions| {
1396                let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
1397                Some(description.into())
1398            })
1399        }
1400
1401        fn telemetry_event_text(&self) -> Option<&'static str> {
1402            None
1403        }
1404
1405        fn tab_content(&self, params: TabContentParams, _window: &Window, _cx: &App) -> AnyElement {
1406            self.tab_detail.set(params.detail);
1407            gpui::div().into_any_element()
1408        }
1409
1410        fn for_each_project_item(
1411            &self,
1412            cx: &App,
1413            f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
1414        ) {
1415            self.project_items
1416                .iter()
1417                .for_each(|item| f(item.entity_id(), item.read(cx)))
1418        }
1419
1420        fn is_singleton(&self, _: &App) -> bool {
1421            self.is_singleton
1422        }
1423
1424        fn set_nav_history(
1425            &mut self,
1426            history: ItemNavHistory,
1427            _window: &mut Window,
1428            _: &mut Context<Self>,
1429        ) {
1430            self.nav_history = Some(history);
1431        }
1432
1433        fn navigate(
1434            &mut self,
1435            state: Box<dyn Any>,
1436            _window: &mut Window,
1437            _: &mut Context<Self>,
1438        ) -> bool {
1439            let state = *state.downcast::<String>().unwrap_or_default();
1440            if state != self.state {
1441                self.state = state;
1442                true
1443            } else {
1444                false
1445            }
1446        }
1447
1448        fn deactivated(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1449            self.push_to_nav_history(cx);
1450        }
1451
1452        fn clone_on_split(
1453            &self,
1454            _workspace_id: Option<WorkspaceId>,
1455            _: &mut Window,
1456            cx: &mut Context<Self>,
1457        ) -> Option<Entity<Self>>
1458        where
1459            Self: Sized,
1460        {
1461            Some(cx.new(|cx| Self {
1462                state: self.state.clone(),
1463                label: self.label.clone(),
1464                save_count: self.save_count,
1465                save_as_count: self.save_as_count,
1466                reload_count: self.reload_count,
1467                is_dirty: self.is_dirty,
1468                is_singleton: self.is_singleton,
1469                has_conflict: self.has_conflict,
1470                project_items: self.project_items.clone(),
1471                nav_history: None,
1472                tab_descriptions: None,
1473                tab_detail: Default::default(),
1474                workspace_id: self.workspace_id,
1475                focus_handle: cx.focus_handle(),
1476                serialize: None,
1477            }))
1478        }
1479
1480        fn is_dirty(&self, _: &App) -> bool {
1481            self.is_dirty
1482        }
1483
1484        fn has_conflict(&self, _: &App) -> bool {
1485            self.has_conflict
1486        }
1487
1488        fn can_save(&self, cx: &App) -> bool {
1489            !self.project_items.is_empty()
1490                && self
1491                    .project_items
1492                    .iter()
1493                    .all(|item| item.read(cx).entry_id.is_some())
1494        }
1495
1496        fn can_save_as(&self, _cx: &App) -> bool {
1497            self.is_singleton
1498        }
1499
1500        fn save(
1501            &mut self,
1502            _: bool,
1503            _: Entity<Project>,
1504            _window: &mut Window,
1505            cx: &mut Context<Self>,
1506        ) -> Task<anyhow::Result<()>> {
1507            self.save_count += 1;
1508            self.is_dirty = false;
1509            for item in &self.project_items {
1510                item.update(cx, |item, _| {
1511                    if item.is_dirty {
1512                        item.is_dirty = false;
1513                    }
1514                })
1515            }
1516            Task::ready(Ok(()))
1517        }
1518
1519        fn save_as(
1520            &mut self,
1521            _: Entity<Project>,
1522            _: ProjectPath,
1523            _window: &mut Window,
1524            _: &mut Context<Self>,
1525        ) -> Task<anyhow::Result<()>> {
1526            self.save_as_count += 1;
1527            self.is_dirty = false;
1528            Task::ready(Ok(()))
1529        }
1530
1531        fn reload(
1532            &mut self,
1533            _: Entity<Project>,
1534            _window: &mut Window,
1535            _: &mut Context<Self>,
1536        ) -> Task<anyhow::Result<()>> {
1537            self.reload_count += 1;
1538            self.is_dirty = false;
1539            Task::ready(Ok(()))
1540        }
1541    }
1542
1543    impl SerializableItem for TestItem {
1544        fn serialized_item_kind() -> &'static str {
1545            "TestItem"
1546        }
1547
1548        fn deserialize(
1549            _project: Entity<Project>,
1550            _workspace: WeakEntity<Workspace>,
1551            workspace_id: WorkspaceId,
1552            _item_id: ItemId,
1553            _window: &mut Window,
1554            cx: &mut App,
1555        ) -> Task<anyhow::Result<Entity<Self>>> {
1556            let entity = cx.new(|cx| Self::new_deserialized(workspace_id, cx));
1557            Task::ready(Ok(entity))
1558        }
1559
1560        fn cleanup(
1561            _workspace_id: WorkspaceId,
1562            _alive_items: Vec<ItemId>,
1563            _window: &mut Window,
1564            _cx: &mut App,
1565        ) -> Task<anyhow::Result<()>> {
1566            Task::ready(Ok(()))
1567        }
1568
1569        fn serialize(
1570            &mut self,
1571            _workspace: &mut Workspace,
1572            _item_id: ItemId,
1573            _closing: bool,
1574            _window: &mut Window,
1575            _cx: &mut Context<Self>,
1576        ) -> Option<Task<anyhow::Result<()>>> {
1577            if let Some(serialize) = self.serialize.take() {
1578                let result = serialize();
1579                self.serialize = Some(serialize);
1580                result
1581            } else {
1582                None
1583            }
1584        }
1585
1586        fn should_serialize(&self, _event: &Self::Event) -> bool {
1587            false
1588        }
1589    }
1590}