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