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