item.rs

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