item.rs

   1use crate::{
   2    CollaboratorId, DelayedDebouncedEditAction, FollowableViewRegistry, ItemNavHistory,
   3    SerializableItemRegistry, 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::{Client, proto};
  11use futures::{StreamExt, channel::mpsc};
  12use gpui::{
  13    Action, AnyElement, AnyView, App, Context, Entity, EntityId, EventEmitter, FocusHandle,
  14    Focusable, Font, HighlightStyle, Pixels, Point, Render, SharedString, Task, WeakEntity, Window,
  15};
  16use project::{Project, ProjectEntryId, ProjectPath};
  17use schemars::JsonSchema;
  18use serde::{Deserialize, Serialize};
  19use settings::{Settings, SettingsLocation, SettingsSources};
  20use smallvec::SmallVec;
  21use std::{
  22    any::{Any, TypeId},
  23    cell::RefCell,
  24    ops::Range,
  25    rc::Rc,
  26    sync::Arc,
  27    time::Duration,
  28};
  29use theme::Theme;
  30use ui::{Color, Icon, IntoElement, Label, LabelCommon};
  31use util::ResultExt;
  32
  33pub const LEADER_UPDATE_THROTTLE: Duration = Duration::from_millis(200);
  34
  35#[derive(Deserialize)]
  36pub struct ItemSettings {
  37    pub git_status: bool,
  38    pub close_position: ClosePosition,
  39    pub activate_on_close: ActivateOnClose,
  40    pub file_icons: bool,
  41    pub show_diagnostics: ShowDiagnostics,
  42    pub show_close_button: ShowCloseButton,
  43}
  44
  45#[derive(Deserialize)]
  46pub struct PreviewTabsSettings {
  47    pub enabled: bool,
  48    pub enable_preview_from_file_finder: bool,
  49    pub enable_preview_from_code_navigation: bool,
  50}
  51
  52#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  53#[serde(rename_all = "lowercase")]
  54pub enum ClosePosition {
  55    Left,
  56    #[default]
  57    Right,
  58}
  59
  60#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  61#[serde(rename_all = "lowercase")]
  62pub enum ShowCloseButton {
  63    Always,
  64    #[default]
  65    Hover,
  66    Hidden,
  67}
  68
  69#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
  70#[serde(rename_all = "snake_case")]
  71pub enum ShowDiagnostics {
  72    #[default]
  73    Off,
  74    Errors,
  75    All,
  76}
  77
  78#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  79#[serde(rename_all = "snake_case")]
  80pub enum ActivateOnClose {
  81    #[default]
  82    History,
  83    Neighbour,
  84    LeftNeighbour,
  85}
  86
  87#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  88pub struct ItemSettingsContent {
  89    /// Whether to show the Git file status on a tab item.
  90    ///
  91    /// Default: false
  92    git_status: Option<bool>,
  93    /// Position of the close button in a tab.
  94    ///
  95    /// Default: right
  96    close_position: Option<ClosePosition>,
  97    /// Whether to show the file icon for a tab.
  98    ///
  99    /// Default: false
 100    file_icons: Option<bool>,
 101    /// What to do after closing the current tab.
 102    ///
 103    /// Default: history
 104    pub activate_on_close: Option<ActivateOnClose>,
 105    /// Which files containing diagnostic errors/warnings to mark in the tabs.
 106    /// This setting can take the following three values:
 107    ///
 108    /// Default: off
 109    show_diagnostics: Option<ShowDiagnostics>,
 110    /// Whether to always show the close button on tabs.
 111    ///
 112    /// Default: false
 113    show_close_button: Option<ShowCloseButton>,
 114}
 115
 116#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
 117pub struct PreviewTabsSettingsContent {
 118    /// Whether to show opened editors as preview tabs.
 119    /// 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.
 120    ///
 121    /// Default: true
 122    enabled: Option<bool>,
 123    /// Whether to open tabs in preview mode when selected from the file finder.
 124    ///
 125    /// Default: false
 126    enable_preview_from_file_finder: Option<bool>,
 127    /// Whether a preview tab gets replaced when code navigation is used to navigate away from the tab.
 128    ///
 129    /// Default: false
 130    enable_preview_from_code_navigation: Option<bool>,
 131}
 132
 133impl Settings for ItemSettings {
 134    const KEY: Option<&'static str> = Some("tabs");
 135
 136    type FileContent = ItemSettingsContent;
 137
 138    fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
 139        sources.json_merge()
 140    }
 141
 142    fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut Self::FileContent) {
 143        if let Some(b) = vscode.read_bool("workbench.editor.tabActionCloseVisibility") {
 144            current.show_close_button = Some(if b {
 145                ShowCloseButton::Always
 146            } else {
 147                ShowCloseButton::Hidden
 148            })
 149        }
 150        vscode.enum_setting(
 151            "workbench.editor.tabActionLocation",
 152            &mut current.close_position,
 153            |s| match s {
 154                "right" => Some(ClosePosition::Right),
 155                "left" => Some(ClosePosition::Left),
 156                _ => None,
 157            },
 158        );
 159        if let Some(b) = vscode.read_bool("workbench.editor.focusRecentEditorAfterClose") {
 160            current.activate_on_close = Some(if b {
 161                ActivateOnClose::History
 162            } else {
 163                ActivateOnClose::LeftNeighbour
 164            })
 165        }
 166
 167        vscode.bool_setting("workbench.editor.showIcons", &mut current.file_icons);
 168        vscode.bool_setting("git.decorations.enabled", &mut current.git_status);
 169    }
 170}
 171
 172impl Settings for PreviewTabsSettings {
 173    const KEY: Option<&'static str> = Some("preview_tabs");
 174
 175    type FileContent = PreviewTabsSettingsContent;
 176
 177    fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
 178        sources.json_merge()
 179    }
 180
 181    fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut Self::FileContent) {
 182        vscode.bool_setting("workbench.editor.enablePreview", &mut current.enabled);
 183        vscode.bool_setting(
 184            "workbench.editor.enablePreviewFromCodeNavigation",
 185            &mut current.enable_preview_from_code_navigation,
 186        );
 187        vscode.bool_setting(
 188            "workbench.editor.enablePreviewFromQuickOpen",
 189            &mut current.enable_preview_from_file_finder,
 190        );
 191    }
 192}
 193
 194#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
 195pub enum ItemEvent {
 196    CloseItem,
 197    UpdateTab,
 198    UpdateBreadcrumbs,
 199    Edit,
 200}
 201
 202// TODO: Combine this with existing HighlightedText struct?
 203pub struct BreadcrumbText {
 204    pub text: String,
 205    pub highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
 206    pub font: Option<Font>,
 207}
 208
 209#[derive(Clone, Copy, Default, Debug)]
 210pub struct TabContentParams {
 211    pub detail: Option<usize>,
 212    pub selected: bool,
 213    pub preview: bool,
 214    /// Tab content should be deemphasized when active pane does not have focus.
 215    pub deemphasized: bool,
 216}
 217
 218impl TabContentParams {
 219    /// Returns the text color to be used for the tab content.
 220    pub fn text_color(&self) -> Color {
 221        if self.deemphasized {
 222            if self.selected {
 223                Color::Muted
 224            } else {
 225                Color::Hidden
 226            }
 227        } else if self.selected {
 228            Color::Default
 229        } else {
 230            Color::Muted
 231        }
 232    }
 233}
 234
 235pub enum TabTooltipContent {
 236    Text(SharedString),
 237    Custom(Box<dyn Fn(&mut Window, &mut App) -> AnyView>),
 238}
 239
 240pub trait Item: Focusable + EventEmitter<Self::Event> + Render + Sized {
 241    type Event;
 242
 243    /// Returns the tab contents.
 244    ///
 245    /// By default this returns a [`Label`] that displays that text from
 246    /// `tab_content_text`.
 247    fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
 248        let text = self.tab_content_text(params.detail.unwrap_or_default(), cx);
 249
 250        Label::new(text)
 251            .color(params.text_color())
 252            .into_any_element()
 253    }
 254
 255    /// Returns the textual contents of the tab.
 256    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString;
 257
 258    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
 259        None
 260    }
 261
 262    /// Returns the tab tooltip text.
 263    ///
 264    /// Use this if you don't need to customize the tab tooltip content.
 265    fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
 266        None
 267    }
 268
 269    /// Returns the tab tooltip content.
 270    ///
 271    /// By default this returns a Tooltip text from
 272    /// `tab_tooltip_text`.
 273    fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
 274        self.tab_tooltip_text(cx).map(TabTooltipContent::Text)
 275    }
 276
 277    fn to_item_events(_event: &Self::Event, _f: impl FnMut(ItemEvent)) {}
 278
 279    fn deactivated(&mut self, _window: &mut Window, _: &mut Context<Self>) {}
 280    fn discarded(&self, _project: Entity<Project>, _window: &mut Window, _cx: &mut Context<Self>) {}
 281    fn workspace_deactivated(&mut self, _window: &mut Window, _: &mut Context<Self>) {}
 282    fn navigate(&mut self, _: Box<dyn Any>, _window: &mut Window, _: &mut Context<Self>) -> bool {
 283        false
 284    }
 285
 286    fn telemetry_event_text(&self) -> Option<&'static str> {
 287        None
 288    }
 289
 290    /// (model id, Item)
 291    fn for_each_project_item(
 292        &self,
 293        _: &App,
 294        _: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 295    ) {
 296    }
 297    fn is_singleton(&self, _cx: &App) -> bool {
 298        false
 299    }
 300    fn set_nav_history(&mut self, _: ItemNavHistory, _window: &mut Window, _: &mut Context<Self>) {}
 301    fn clone_on_split(
 302        &self,
 303        _workspace_id: Option<WorkspaceId>,
 304        _window: &mut Window,
 305        _: &mut Context<Self>,
 306    ) -> Option<Entity<Self>>
 307    where
 308        Self: Sized,
 309    {
 310        None
 311    }
 312    fn is_dirty(&self, _: &App) -> bool {
 313        false
 314    }
 315    fn has_deleted_file(&self, _: &App) -> bool {
 316        false
 317    }
 318    fn has_conflict(&self, _: &App) -> bool {
 319        false
 320    }
 321    fn can_save(&self, _cx: &App) -> bool {
 322        false
 323    }
 324    fn can_save_as(&self, _: &App) -> bool {
 325        false
 326    }
 327    fn save(
 328        &mut self,
 329        _format: bool,
 330        _project: Entity<Project>,
 331        _window: &mut Window,
 332        _cx: &mut Context<Self>,
 333    ) -> Task<Result<()>> {
 334        unimplemented!("save() must be implemented if can_save() returns true")
 335    }
 336    fn save_as(
 337        &mut self,
 338        _project: Entity<Project>,
 339        _path: ProjectPath,
 340        _window: &mut Window,
 341        _cx: &mut Context<Self>,
 342    ) -> Task<Result<()>> {
 343        unimplemented!("save_as() must be implemented if can_save() returns true")
 344    }
 345    fn reload(
 346        &mut self,
 347        _project: Entity<Project>,
 348        _window: &mut Window,
 349        _cx: &mut Context<Self>,
 350    ) -> Task<Result<()>> {
 351        unimplemented!("reload() must be implemented if can_save() returns true")
 352    }
 353
 354    fn act_as_type<'a>(
 355        &'a self,
 356        type_id: TypeId,
 357        self_handle: &'a Entity<Self>,
 358        _: &'a App,
 359    ) -> Option<AnyView> {
 360        if TypeId::of::<Self>() == type_id {
 361            Some(self_handle.clone().into())
 362        } else {
 363            None
 364        }
 365    }
 366
 367    fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 368        None
 369    }
 370
 371    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
 372        ToolbarItemLocation::Hidden
 373    }
 374
 375    fn breadcrumbs(&self, _theme: &Theme, _cx: &App) -> Option<Vec<BreadcrumbText>> {
 376        None
 377    }
 378
 379    fn added_to_workspace(
 380        &mut self,
 381        _workspace: &mut Workspace,
 382        _window: &mut Window,
 383        _cx: &mut Context<Self>,
 384    ) {
 385    }
 386
 387    fn show_toolbar(&self) -> bool {
 388        true
 389    }
 390
 391    fn pixel_position_of_cursor(&self, _: &App) -> Option<Point<Pixels>> {
 392        None
 393    }
 394
 395    fn preserve_preview(&self, _cx: &App) -> bool {
 396        false
 397    }
 398
 399    fn include_in_nav_history() -> bool {
 400        true
 401    }
 402}
 403
 404pub trait SerializableItem: Item {
 405    fn serialized_item_kind() -> &'static str;
 406
 407    fn cleanup(
 408        workspace_id: WorkspaceId,
 409        alive_items: Vec<ItemId>,
 410        window: &mut Window,
 411        cx: &mut App,
 412    ) -> Task<Result<()>>;
 413
 414    fn deserialize(
 415        _project: Entity<Project>,
 416        _workspace: WeakEntity<Workspace>,
 417        _workspace_id: WorkspaceId,
 418        _item_id: ItemId,
 419        _window: &mut Window,
 420        _cx: &mut App,
 421    ) -> Task<Result<Entity<Self>>>;
 422
 423    fn serialize(
 424        &mut self,
 425        workspace: &mut Workspace,
 426        item_id: ItemId,
 427        closing: bool,
 428        window: &mut Window,
 429        cx: &mut Context<Self>,
 430    ) -> Option<Task<Result<()>>>;
 431
 432    fn should_serialize(&self, event: &Self::Event) -> bool;
 433}
 434
 435pub trait SerializableItemHandle: ItemHandle {
 436    fn serialized_item_kind(&self) -> &'static str;
 437    fn serialize(
 438        &self,
 439        workspace: &mut Workspace,
 440        closing: bool,
 441        window: &mut Window,
 442        cx: &mut App,
 443    ) -> Option<Task<Result<()>>>;
 444    fn should_serialize(&self, event: &dyn Any, cx: &App) -> bool;
 445}
 446
 447impl<T> SerializableItemHandle for Entity<T>
 448where
 449    T: SerializableItem,
 450{
 451    fn serialized_item_kind(&self) -> &'static str {
 452        T::serialized_item_kind()
 453    }
 454
 455    fn serialize(
 456        &self,
 457        workspace: &mut Workspace,
 458        closing: bool,
 459        window: &mut Window,
 460        cx: &mut App,
 461    ) -> Option<Task<Result<()>>> {
 462        self.update(cx, |this, cx| {
 463            this.serialize(workspace, cx.entity_id().as_u64(), closing, window, cx)
 464        })
 465    }
 466
 467    fn should_serialize(&self, event: &dyn Any, cx: &App) -> bool {
 468        event
 469            .downcast_ref::<T::Event>()
 470            .map_or(false, |event| self.read(cx).should_serialize(event))
 471    }
 472}
 473
 474pub trait ItemHandle: 'static + Send {
 475    fn item_focus_handle(&self, cx: &App) -> FocusHandle;
 476    fn subscribe_to_item_events(
 477        &self,
 478        window: &mut Window,
 479        cx: &mut App,
 480        handler: Box<dyn Fn(ItemEvent, &mut Window, &mut App)>,
 481    ) -> gpui::Subscription;
 482    fn tab_content(&self, params: TabContentParams, window: &Window, cx: &App) -> AnyElement;
 483    fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString;
 484    fn tab_icon(&self, window: &Window, cx: &App) -> Option<Icon>;
 485    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString>;
 486    fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent>;
 487    fn telemetry_event_text(&self, cx: &App) -> Option<&'static str>;
 488    fn dragged_tab_content(
 489        &self,
 490        params: TabContentParams,
 491        window: &Window,
 492        cx: &App,
 493    ) -> AnyElement;
 494    fn project_path(&self, cx: &App) -> Option<ProjectPath>;
 495    fn project_entry_ids(&self, cx: &App) -> SmallVec<[ProjectEntryId; 3]>;
 496    fn project_paths(&self, cx: &App) -> SmallVec<[ProjectPath; 3]>;
 497    fn project_item_model_ids(&self, cx: &App) -> SmallVec<[EntityId; 3]>;
 498    fn for_each_project_item(
 499        &self,
 500        _: &App,
 501        _: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 502    );
 503    fn is_singleton(&self, cx: &App) -> bool;
 504    fn boxed_clone(&self) -> Box<dyn ItemHandle>;
 505    fn clone_on_split(
 506        &self,
 507        workspace_id: Option<WorkspaceId>,
 508        window: &mut Window,
 509        cx: &mut App,
 510    ) -> Option<Box<dyn ItemHandle>>;
 511    fn added_to_pane(
 512        &self,
 513        workspace: &mut Workspace,
 514        pane: Entity<Pane>,
 515        window: &mut Window,
 516        cx: &mut Context<Workspace>,
 517    );
 518    fn deactivated(&self, window: &mut Window, cx: &mut App);
 519    fn discarded(&self, project: Entity<Project>, window: &mut Window, cx: &mut App);
 520    fn workspace_deactivated(&self, window: &mut Window, cx: &mut App);
 521    fn navigate(&self, data: Box<dyn Any>, window: &mut Window, cx: &mut App) -> bool;
 522    fn item_id(&self) -> EntityId;
 523    fn to_any(&self) -> AnyView;
 524    fn is_dirty(&self, cx: &App) -> bool;
 525    fn has_deleted_file(&self, cx: &App) -> bool;
 526    fn has_conflict(&self, cx: &App) -> bool;
 527    fn can_save(&self, cx: &App) -> bool;
 528    fn can_save_as(&self, cx: &App) -> bool;
 529    fn save(
 530        &self,
 531        format: bool,
 532        project: Entity<Project>,
 533        window: &mut Window,
 534        cx: &mut App,
 535    ) -> Task<Result<()>>;
 536    fn save_as(
 537        &self,
 538        project: Entity<Project>,
 539        path: ProjectPath,
 540        window: &mut Window,
 541        cx: &mut App,
 542    ) -> Task<Result<()>>;
 543    fn reload(
 544        &self,
 545        project: Entity<Project>,
 546        window: &mut Window,
 547        cx: &mut App,
 548    ) -> Task<Result<()>>;
 549    fn act_as_type(&self, type_id: TypeId, cx: &App) -> Option<AnyView>;
 550    fn to_followable_item_handle(&self, cx: &App) -> Option<Box<dyn FollowableItemHandle>>;
 551    fn to_serializable_item_handle(&self, cx: &App) -> Option<Box<dyn SerializableItemHandle>>;
 552    fn on_release(
 553        &self,
 554        cx: &mut App,
 555        callback: Box<dyn FnOnce(&mut App) + Send>,
 556    ) -> gpui::Subscription;
 557    fn to_searchable_item_handle(&self, cx: &App) -> Option<Box<dyn SearchableItemHandle>>;
 558    fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation;
 559    fn breadcrumbs(&self, theme: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>>;
 560    fn show_toolbar(&self, cx: &App) -> bool;
 561    fn pixel_position_of_cursor(&self, cx: &App) -> Option<Point<Pixels>>;
 562    fn downgrade_item(&self) -> Box<dyn WeakItemHandle>;
 563    fn workspace_settings<'a>(&self, cx: &'a App) -> &'a WorkspaceSettings;
 564    fn preserve_preview(&self, cx: &App) -> bool;
 565    fn include_in_nav_history(&self) -> bool;
 566    fn relay_action(&self, action: Box<dyn Action>, window: &mut Window, cx: &mut App);
 567}
 568
 569pub trait WeakItemHandle: Send + Sync {
 570    fn id(&self) -> EntityId;
 571    fn boxed_clone(&self) -> Box<dyn WeakItemHandle>;
 572    fn upgrade(&self) -> Option<Box<dyn ItemHandle>>;
 573}
 574
 575impl dyn ItemHandle {
 576    pub fn downcast<V: 'static>(&self) -> Option<Entity<V>> {
 577        self.to_any().downcast().ok()
 578    }
 579
 580    pub fn act_as<V: 'static>(&self, cx: &App) -> Option<Entity<V>> {
 581        self.act_as_type(TypeId::of::<V>(), cx)
 582            .and_then(|t| t.downcast().ok())
 583    }
 584}
 585
 586impl<T: Item> ItemHandle for Entity<T> {
 587    fn subscribe_to_item_events(
 588        &self,
 589        window: &mut Window,
 590        cx: &mut App,
 591        handler: Box<dyn Fn(ItemEvent, &mut Window, &mut App)>,
 592    ) -> gpui::Subscription {
 593        window.subscribe(self, cx, move |_, event, window, cx| {
 594            T::to_item_events(event, |item_event| handler(item_event, window, cx));
 595        })
 596    }
 597
 598    fn item_focus_handle(&self, cx: &App) -> FocusHandle {
 599        self.read(cx).focus_handle(cx)
 600    }
 601
 602    fn telemetry_event_text(&self, cx: &App) -> Option<&'static str> {
 603        self.read(cx).telemetry_event_text()
 604    }
 605
 606    fn tab_content(&self, params: TabContentParams, window: &Window, cx: &App) -> AnyElement {
 607        self.read(cx).tab_content(params, window, cx)
 608    }
 609    fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
 610        self.read(cx).tab_content_text(detail, cx)
 611    }
 612
 613    fn tab_icon(&self, window: &Window, cx: &App) -> Option<Icon> {
 614        self.read(cx).tab_icon(window, cx)
 615    }
 616
 617    fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
 618        self.read(cx).tab_tooltip_content(cx)
 619    }
 620
 621    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
 622        self.read(cx).tab_tooltip_text(cx)
 623    }
 624
 625    fn dragged_tab_content(
 626        &self,
 627        params: TabContentParams,
 628        window: &Window,
 629        cx: &App,
 630    ) -> AnyElement {
 631        self.read(cx).tab_content(
 632            TabContentParams {
 633                selected: true,
 634                ..params
 635            },
 636            window,
 637            cx,
 638        )
 639    }
 640
 641    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
 642        let this = self.read(cx);
 643        let mut result = None;
 644        if this.is_singleton(cx) {
 645            this.for_each_project_item(cx, &mut |_, item| {
 646                result = item.project_path(cx);
 647            });
 648        }
 649        result
 650    }
 651
 652    fn workspace_settings<'a>(&self, cx: &'a App) -> &'a WorkspaceSettings {
 653        if let Some(project_path) = self.project_path(cx) {
 654            WorkspaceSettings::get(
 655                Some(SettingsLocation {
 656                    worktree_id: project_path.worktree_id,
 657                    path: &project_path.path,
 658                }),
 659                cx,
 660            )
 661        } else {
 662            WorkspaceSettings::get_global(cx)
 663        }
 664    }
 665
 666    fn project_entry_ids(&self, cx: &App) -> SmallVec<[ProjectEntryId; 3]> {
 667        let mut result = SmallVec::new();
 668        self.read(cx).for_each_project_item(cx, &mut |_, item| {
 669            if let Some(id) = item.entry_id(cx) {
 670                result.push(id);
 671            }
 672        });
 673        result
 674    }
 675
 676    fn project_paths(&self, cx: &App) -> SmallVec<[ProjectPath; 3]> {
 677        let mut result = SmallVec::new();
 678        self.read(cx).for_each_project_item(cx, &mut |_, item| {
 679            if let Some(id) = item.project_path(cx) {
 680                result.push(id);
 681            }
 682        });
 683        result
 684    }
 685
 686    fn project_item_model_ids(&self, cx: &App) -> SmallVec<[EntityId; 3]> {
 687        let mut result = SmallVec::new();
 688        self.read(cx).for_each_project_item(cx, &mut |id, _| {
 689            result.push(id);
 690        });
 691        result
 692    }
 693
 694    fn for_each_project_item(
 695        &self,
 696        cx: &App,
 697        f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 698    ) {
 699        self.read(cx).for_each_project_item(cx, f)
 700    }
 701
 702    fn is_singleton(&self, cx: &App) -> bool {
 703        self.read(cx).is_singleton(cx)
 704    }
 705
 706    fn boxed_clone(&self) -> Box<dyn ItemHandle> {
 707        Box::new(self.clone())
 708    }
 709
 710    fn clone_on_split(
 711        &self,
 712        workspace_id: Option<WorkspaceId>,
 713        window: &mut Window,
 714        cx: &mut App,
 715    ) -> Option<Box<dyn ItemHandle>> {
 716        self.update(cx, |item, cx| item.clone_on_split(workspace_id, window, cx))
 717            .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
 718    }
 719
 720    fn added_to_pane(
 721        &self,
 722        workspace: &mut Workspace,
 723        pane: Entity<Pane>,
 724        window: &mut Window,
 725        cx: &mut Context<Workspace>,
 726    ) {
 727        let weak_item = self.downgrade();
 728        let history = pane.read(cx).nav_history_for_item(self);
 729        self.update(cx, |this, cx| {
 730            this.set_nav_history(history, window, cx);
 731            this.added_to_workspace(workspace, window, cx);
 732        });
 733
 734        if let Some(serializable_item) = self.to_serializable_item_handle(cx) {
 735            workspace
 736                .enqueue_item_serialization(serializable_item)
 737                .log_err();
 738        }
 739
 740        if workspace
 741            .panes_by_item
 742            .insert(self.item_id(), pane.downgrade())
 743            .is_none()
 744        {
 745            let mut pending_autosave = DelayedDebouncedEditAction::new();
 746            let (pending_update_tx, mut pending_update_rx) = mpsc::unbounded();
 747            let pending_update = Rc::new(RefCell::new(None));
 748
 749            let mut send_follower_updates = None;
 750            if let Some(item) = self.to_followable_item_handle(cx) {
 751                let is_project_item = item.is_project_item(window, cx);
 752                let item = item.downgrade();
 753
 754                send_follower_updates = Some(cx.spawn_in(window, {
 755                    let pending_update = pending_update.clone();
 756                    async move |workspace, cx| {
 757                        while let Some(mut leader_id) = pending_update_rx.next().await {
 758                            while let Ok(Some(id)) = pending_update_rx.try_next() {
 759                                leader_id = id;
 760                            }
 761
 762                            workspace.update_in(cx, |workspace, window, cx| {
 763                                let Some(item) = item.upgrade() else { return };
 764                                workspace.update_followers(
 765                                    is_project_item,
 766                                    proto::update_followers::Variant::UpdateView(
 767                                        proto::UpdateView {
 768                                            id: item
 769                                                .remote_id(workspace.client(), window, cx)
 770                                                .and_then(|id| id.to_proto()),
 771                                            variant: pending_update.borrow_mut().take(),
 772                                            leader_id,
 773                                        },
 774                                    ),
 775                                    window,
 776                                    cx,
 777                                );
 778                            })?;
 779                            cx.background_executor().timer(LEADER_UPDATE_THROTTLE).await;
 780                        }
 781                        anyhow::Ok(())
 782                    }
 783                }));
 784            }
 785
 786            let mut event_subscription = Some(cx.subscribe_in(
 787                self,
 788                window,
 789                move |workspace, item: &Entity<T>, event, window, cx| {
 790                    let pane = if let Some(pane) = workspace
 791                        .panes_by_item
 792                        .get(&item.item_id())
 793                        .and_then(|pane| pane.upgrade())
 794                    {
 795                        pane
 796                    } else {
 797                        return;
 798                    };
 799
 800                    if let Some(item) = item.to_followable_item_handle(cx) {
 801                        let leader_id = workspace.leader_for_pane(&pane);
 802
 803                        if let Some(leader_id) = leader_id {
 804                            if let Some(FollowEvent::Unfollow) = item.to_follow_event(event) {
 805                                workspace.unfollow(leader_id, window, cx);
 806                            }
 807                        }
 808
 809                        if item.item_focus_handle(cx).contains_focused(window, cx) {
 810                            match leader_id {
 811                                Some(CollaboratorId::Agent) => {}
 812                                Some(CollaboratorId::PeerId(leader_peer_id)) => {
 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(Some(leader_peer_id)).ok();
 820                                }
 821                                None => {
 822                                    item.add_event_to_update_proto(
 823                                        event,
 824                                        &mut pending_update.borrow_mut(),
 825                                        window,
 826                                        cx,
 827                                    );
 828                                    pending_update_tx.unbounded_send(None).ok();
 829                                }
 830                            }
 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: Option<&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_id(
1141        &mut self,
1142        leader_peer_id: Option<CollaboratorId>,
1143        window: &mut Window,
1144        cx: &mut Context<Self>,
1145    );
1146    fn dedup(&self, existing: &Self, window: &Window, cx: &App) -> Option<Dedup>;
1147    fn update_agent_location(
1148        &mut self,
1149        _location: language::Anchor,
1150        _window: &mut Window,
1151        _cx: &mut Context<Self>,
1152    ) {
1153    }
1154}
1155
1156pub trait FollowableItemHandle: ItemHandle {
1157    fn remote_id(&self, client: &Arc<Client>, window: &mut Window, cx: &mut App) -> Option<ViewId>;
1158    fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle>;
1159    fn set_leader_id(
1160        &self,
1161        leader_peer_id: Option<CollaboratorId>,
1162        window: &mut Window,
1163        cx: &mut App,
1164    );
1165    fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant>;
1166    fn add_event_to_update_proto(
1167        &self,
1168        event: &dyn Any,
1169        update: &mut Option<proto::update_view::Variant>,
1170        window: &mut Window,
1171        cx: &mut App,
1172    ) -> bool;
1173    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
1174    fn apply_update_proto(
1175        &self,
1176        project: &Entity<Project>,
1177        message: proto::update_view::Variant,
1178        window: &mut Window,
1179        cx: &mut App,
1180    ) -> Task<Result<()>>;
1181    fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool;
1182    fn dedup(
1183        &self,
1184        existing: &dyn FollowableItemHandle,
1185        window: &mut Window,
1186        cx: &mut App,
1187    ) -> Option<Dedup>;
1188    fn update_agent_location(&self, location: language::Anchor, window: &mut Window, cx: &mut App);
1189}
1190
1191impl<T: FollowableItem> FollowableItemHandle for Entity<T> {
1192    fn remote_id(&self, client: &Arc<Client>, _: &mut Window, cx: &mut App) -> Option<ViewId> {
1193        self.read(cx).remote_id().or_else(|| {
1194            client.peer_id().map(|creator| ViewId {
1195                creator: CollaboratorId::PeerId(creator),
1196                id: self.item_id().as_u64(),
1197            })
1198        })
1199    }
1200
1201    fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle> {
1202        Box::new(self.downgrade())
1203    }
1204
1205    fn set_leader_id(&self, leader_id: Option<CollaboratorId>, window: &mut Window, cx: &mut App) {
1206        self.update(cx, |this, cx| this.set_leader_id(leader_id, window, cx))
1207    }
1208
1209    fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant> {
1210        self.read(cx).to_state_proto(window, cx)
1211    }
1212
1213    fn add_event_to_update_proto(
1214        &self,
1215        event: &dyn Any,
1216        update: &mut Option<proto::update_view::Variant>,
1217        window: &mut Window,
1218        cx: &mut App,
1219    ) -> bool {
1220        if let Some(event) = event.downcast_ref() {
1221            self.read(cx)
1222                .add_event_to_update_proto(event, update, window, cx)
1223        } else {
1224            false
1225        }
1226    }
1227
1228    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
1229        T::to_follow_event(event.downcast_ref()?)
1230    }
1231
1232    fn apply_update_proto(
1233        &self,
1234        project: &Entity<Project>,
1235        message: proto::update_view::Variant,
1236        window: &mut Window,
1237        cx: &mut App,
1238    ) -> Task<Result<()>> {
1239        self.update(cx, |this, cx| {
1240            this.apply_update_proto(project, message, window, cx)
1241        })
1242    }
1243
1244    fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool {
1245        self.read(cx).is_project_item(window, cx)
1246    }
1247
1248    fn dedup(
1249        &self,
1250        existing: &dyn FollowableItemHandle,
1251        window: &mut Window,
1252        cx: &mut App,
1253    ) -> Option<Dedup> {
1254        let existing = existing.to_any().downcast::<T>().ok()?;
1255        self.read(cx).dedup(existing.read(cx), window, cx)
1256    }
1257
1258    fn update_agent_location(&self, location: language::Anchor, window: &mut Window, cx: &mut App) {
1259        self.update(cx, |this, cx| {
1260            this.update_agent_location(location, window, cx)
1261        })
1262    }
1263}
1264
1265pub trait WeakFollowableItemHandle: Send + Sync {
1266    fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>>;
1267}
1268
1269impl<T: FollowableItem> WeakFollowableItemHandle for WeakEntity<T> {
1270    fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>> {
1271        Some(Box::new(self.upgrade()?))
1272    }
1273}
1274
1275#[cfg(any(test, feature = "test-support"))]
1276pub mod test {
1277    use super::{Item, ItemEvent, SerializableItem, TabContentParams};
1278    use crate::{ItemId, ItemNavHistory, Workspace, WorkspaceId};
1279    use gpui::{
1280        AnyElement, App, AppContext as _, Context, Entity, EntityId, EventEmitter, Focusable,
1281        InteractiveElement, IntoElement, Render, SharedString, Task, WeakEntity, Window,
1282    };
1283    use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
1284    use std::{any::Any, cell::Cell, path::Path};
1285
1286    pub struct TestProjectItem {
1287        pub entry_id: Option<ProjectEntryId>,
1288        pub project_path: Option<ProjectPath>,
1289        pub is_dirty: bool,
1290    }
1291
1292    pub struct TestItem {
1293        pub workspace_id: Option<WorkspaceId>,
1294        pub state: String,
1295        pub label: String,
1296        pub save_count: usize,
1297        pub save_as_count: usize,
1298        pub reload_count: usize,
1299        pub is_dirty: bool,
1300        pub is_singleton: bool,
1301        pub has_conflict: bool,
1302        pub project_items: Vec<Entity<TestProjectItem>>,
1303        pub nav_history: Option<ItemNavHistory>,
1304        pub tab_descriptions: Option<Vec<&'static str>>,
1305        pub tab_detail: Cell<Option<usize>>,
1306        serialize: Option<Box<dyn Fn() -> Option<Task<anyhow::Result<()>>>>>,
1307        focus_handle: gpui::FocusHandle,
1308    }
1309
1310    impl project::ProjectItem for TestProjectItem {
1311        fn try_open(
1312            _project: &Entity<Project>,
1313            _path: &ProjectPath,
1314            _cx: &mut App,
1315        ) -> Option<Task<gpui::Result<Entity<Self>>>> {
1316            None
1317        }
1318        fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
1319            self.entry_id
1320        }
1321
1322        fn project_path(&self, _: &App) -> Option<ProjectPath> {
1323            self.project_path.clone()
1324        }
1325
1326        fn is_dirty(&self) -> bool {
1327            self.is_dirty
1328        }
1329    }
1330
1331    pub enum TestItemEvent {
1332        Edit,
1333    }
1334
1335    impl TestProjectItem {
1336        pub fn new(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1337            let entry_id = Some(ProjectEntryId::from_proto(id));
1338            let project_path = Some(ProjectPath {
1339                worktree_id: WorktreeId::from_usize(0),
1340                path: Path::new(path).into(),
1341            });
1342            cx.new(|_| Self {
1343                entry_id,
1344                project_path,
1345                is_dirty: false,
1346            })
1347        }
1348
1349        pub fn new_untitled(cx: &mut App) -> Entity<Self> {
1350            cx.new(|_| Self {
1351                project_path: None,
1352                entry_id: None,
1353                is_dirty: false,
1354            })
1355        }
1356
1357        pub fn new_dirty(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1358            let entry_id = Some(ProjectEntryId::from_proto(id));
1359            let project_path = Some(ProjectPath {
1360                worktree_id: WorktreeId::from_usize(0),
1361                path: Path::new(path).into(),
1362            });
1363            cx.new(|_| Self {
1364                entry_id,
1365                project_path,
1366                is_dirty: true,
1367            })
1368        }
1369    }
1370
1371    impl TestItem {
1372        pub fn new(cx: &mut Context<Self>) -> Self {
1373            Self {
1374                state: String::new(),
1375                label: String::new(),
1376                save_count: 0,
1377                save_as_count: 0,
1378                reload_count: 0,
1379                is_dirty: false,
1380                has_conflict: false,
1381                project_items: Vec::new(),
1382                is_singleton: true,
1383                nav_history: None,
1384                tab_descriptions: None,
1385                tab_detail: Default::default(),
1386                workspace_id: Default::default(),
1387                focus_handle: cx.focus_handle(),
1388                serialize: None,
1389            }
1390        }
1391
1392        pub fn new_deserialized(id: WorkspaceId, cx: &mut Context<Self>) -> Self {
1393            let mut this = Self::new(cx);
1394            this.workspace_id = Some(id);
1395            this
1396        }
1397
1398        pub fn with_label(mut self, state: &str) -> Self {
1399            self.label = state.to_string();
1400            self
1401        }
1402
1403        pub fn with_singleton(mut self, singleton: bool) -> Self {
1404            self.is_singleton = singleton;
1405            self
1406        }
1407
1408        pub fn with_dirty(mut self, dirty: bool) -> Self {
1409            self.is_dirty = dirty;
1410            self
1411        }
1412
1413        pub fn with_conflict(mut self, has_conflict: bool) -> Self {
1414            self.has_conflict = has_conflict;
1415            self
1416        }
1417
1418        pub fn with_project_items(mut self, items: &[Entity<TestProjectItem>]) -> Self {
1419            self.project_items.clear();
1420            self.project_items.extend(items.iter().cloned());
1421            self
1422        }
1423
1424        pub fn with_serialize(
1425            mut self,
1426            serialize: impl Fn() -> Option<Task<anyhow::Result<()>>> + 'static,
1427        ) -> Self {
1428            self.serialize = Some(Box::new(serialize));
1429            self
1430        }
1431
1432        pub fn set_state(&mut self, state: String, cx: &mut Context<Self>) {
1433            self.push_to_nav_history(cx);
1434            self.state = state;
1435        }
1436
1437        fn push_to_nav_history(&mut self, cx: &mut Context<Self>) {
1438            if let Some(history) = &mut self.nav_history {
1439                history.push(Some(Box::new(self.state.clone())), cx);
1440            }
1441        }
1442    }
1443
1444    impl Render for TestItem {
1445        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1446            gpui::div().track_focus(&self.focus_handle(cx))
1447        }
1448    }
1449
1450    impl EventEmitter<ItemEvent> for TestItem {}
1451
1452    impl Focusable for TestItem {
1453        fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
1454            self.focus_handle.clone()
1455        }
1456    }
1457
1458    impl Item for TestItem {
1459        type Event = ItemEvent;
1460
1461        fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1462            f(*event)
1463        }
1464
1465        fn tab_content_text(&self, detail: usize, _cx: &App) -> SharedString {
1466            self.tab_descriptions
1467                .as_ref()
1468                .and_then(|descriptions| {
1469                    let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
1470                    description.into()
1471                })
1472                .unwrap_or_default()
1473                .into()
1474        }
1475
1476        fn telemetry_event_text(&self) -> Option<&'static str> {
1477            None
1478        }
1479
1480        fn tab_content(&self, params: TabContentParams, _window: &Window, _cx: &App) -> AnyElement {
1481            self.tab_detail.set(params.detail);
1482            gpui::div().into_any_element()
1483        }
1484
1485        fn for_each_project_item(
1486            &self,
1487            cx: &App,
1488            f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
1489        ) {
1490            self.project_items
1491                .iter()
1492                .for_each(|item| f(item.entity_id(), item.read(cx)))
1493        }
1494
1495        fn is_singleton(&self, _: &App) -> bool {
1496            self.is_singleton
1497        }
1498
1499        fn set_nav_history(
1500            &mut self,
1501            history: ItemNavHistory,
1502            _window: &mut Window,
1503            _: &mut Context<Self>,
1504        ) {
1505            self.nav_history = Some(history);
1506        }
1507
1508        fn navigate(
1509            &mut self,
1510            state: Box<dyn Any>,
1511            _window: &mut Window,
1512            _: &mut Context<Self>,
1513        ) -> bool {
1514            let state = *state.downcast::<String>().unwrap_or_default();
1515            if state != self.state {
1516                self.state = state;
1517                true
1518            } else {
1519                false
1520            }
1521        }
1522
1523        fn deactivated(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1524            self.push_to_nav_history(cx);
1525        }
1526
1527        fn clone_on_split(
1528            &self,
1529            _workspace_id: Option<WorkspaceId>,
1530            _: &mut Window,
1531            cx: &mut Context<Self>,
1532        ) -> Option<Entity<Self>>
1533        where
1534            Self: Sized,
1535        {
1536            Some(cx.new(|cx| Self {
1537                state: self.state.clone(),
1538                label: self.label.clone(),
1539                save_count: self.save_count,
1540                save_as_count: self.save_as_count,
1541                reload_count: self.reload_count,
1542                is_dirty: self.is_dirty,
1543                is_singleton: self.is_singleton,
1544                has_conflict: self.has_conflict,
1545                project_items: self.project_items.clone(),
1546                nav_history: None,
1547                tab_descriptions: None,
1548                tab_detail: Default::default(),
1549                workspace_id: self.workspace_id,
1550                focus_handle: cx.focus_handle(),
1551                serialize: None,
1552            }))
1553        }
1554
1555        fn is_dirty(&self, _: &App) -> bool {
1556            self.is_dirty
1557        }
1558
1559        fn has_conflict(&self, _: &App) -> bool {
1560            self.has_conflict
1561        }
1562
1563        fn can_save(&self, cx: &App) -> bool {
1564            !self.project_items.is_empty()
1565                && self
1566                    .project_items
1567                    .iter()
1568                    .all(|item| item.read(cx).entry_id.is_some())
1569        }
1570
1571        fn can_save_as(&self, _cx: &App) -> bool {
1572            self.is_singleton
1573        }
1574
1575        fn save(
1576            &mut self,
1577            _: bool,
1578            _: Entity<Project>,
1579            _window: &mut Window,
1580            cx: &mut Context<Self>,
1581        ) -> Task<anyhow::Result<()>> {
1582            self.save_count += 1;
1583            self.is_dirty = false;
1584            for item in &self.project_items {
1585                item.update(cx, |item, _| {
1586                    if item.is_dirty {
1587                        item.is_dirty = false;
1588                    }
1589                })
1590            }
1591            Task::ready(Ok(()))
1592        }
1593
1594        fn save_as(
1595            &mut self,
1596            _: Entity<Project>,
1597            _: ProjectPath,
1598            _window: &mut Window,
1599            _: &mut Context<Self>,
1600        ) -> Task<anyhow::Result<()>> {
1601            self.save_as_count += 1;
1602            self.is_dirty = false;
1603            Task::ready(Ok(()))
1604        }
1605
1606        fn reload(
1607            &mut self,
1608            _: Entity<Project>,
1609            _window: &mut Window,
1610            _: &mut Context<Self>,
1611        ) -> Task<anyhow::Result<()>> {
1612            self.reload_count += 1;
1613            self.is_dirty = false;
1614            Task::ready(Ok(()))
1615        }
1616    }
1617
1618    impl SerializableItem for TestItem {
1619        fn serialized_item_kind() -> &'static str {
1620            "TestItem"
1621        }
1622
1623        fn deserialize(
1624            _project: Entity<Project>,
1625            _workspace: WeakEntity<Workspace>,
1626            workspace_id: WorkspaceId,
1627            _item_id: ItemId,
1628            _window: &mut Window,
1629            cx: &mut App,
1630        ) -> Task<anyhow::Result<Entity<Self>>> {
1631            let entity = cx.new(|cx| Self::new_deserialized(workspace_id, cx));
1632            Task::ready(Ok(entity))
1633        }
1634
1635        fn cleanup(
1636            _workspace_id: WorkspaceId,
1637            _alive_items: Vec<ItemId>,
1638            _window: &mut Window,
1639            _cx: &mut App,
1640        ) -> Task<anyhow::Result<()>> {
1641            Task::ready(Ok(()))
1642        }
1643
1644        fn serialize(
1645            &mut self,
1646            _workspace: &mut Workspace,
1647            _item_id: ItemId,
1648            _closing: bool,
1649            _window: &mut Window,
1650            _cx: &mut Context<Self>,
1651        ) -> Option<Task<anyhow::Result<()>>> {
1652            if let Some(serialize) = self.serialize.take() {
1653                let result = serialize();
1654                self.serialize = Some(serialize);
1655                result
1656            } else {
1657                None
1658            }
1659        }
1660
1661        fn should_serialize(&self, _event: &Self::Event) -> bool {
1662            false
1663        }
1664    }
1665}