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    fn can_autosave(&self, cx: &App) -> bool {
 568        let is_deleted = self.project_entry_ids(cx).is_empty();
 569        self.is_dirty(cx) && !self.has_conflict(cx) && self.can_save(cx) && !is_deleted
 570    }
 571}
 572
 573pub trait WeakItemHandle: Send + Sync {
 574    fn id(&self) -> EntityId;
 575    fn boxed_clone(&self) -> Box<dyn WeakItemHandle>;
 576    fn upgrade(&self) -> Option<Box<dyn ItemHandle>>;
 577}
 578
 579impl dyn ItemHandle {
 580    pub fn downcast<V: 'static>(&self) -> Option<Entity<V>> {
 581        self.to_any().downcast().ok()
 582    }
 583
 584    pub fn act_as<V: 'static>(&self, cx: &App) -> Option<Entity<V>> {
 585        self.act_as_type(TypeId::of::<V>(), cx)
 586            .and_then(|t| t.downcast().ok())
 587    }
 588}
 589
 590impl<T: Item> ItemHandle for Entity<T> {
 591    fn subscribe_to_item_events(
 592        &self,
 593        window: &mut Window,
 594        cx: &mut App,
 595        handler: Box<dyn Fn(ItemEvent, &mut Window, &mut App)>,
 596    ) -> gpui::Subscription {
 597        window.subscribe(self, cx, move |_, event, window, cx| {
 598            T::to_item_events(event, |item_event| handler(item_event, window, cx));
 599        })
 600    }
 601
 602    fn item_focus_handle(&self, cx: &App) -> FocusHandle {
 603        self.read(cx).focus_handle(cx)
 604    }
 605
 606    fn telemetry_event_text(&self, cx: &App) -> Option<&'static str> {
 607        self.read(cx).telemetry_event_text()
 608    }
 609
 610    fn tab_content(&self, params: TabContentParams, window: &Window, cx: &App) -> AnyElement {
 611        self.read(cx).tab_content(params, window, cx)
 612    }
 613    fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
 614        self.read(cx).tab_content_text(detail, cx)
 615    }
 616
 617    fn tab_icon(&self, window: &Window, cx: &App) -> Option<Icon> {
 618        self.read(cx).tab_icon(window, cx)
 619    }
 620
 621    fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
 622        self.read(cx).tab_tooltip_content(cx)
 623    }
 624
 625    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
 626        self.read(cx).tab_tooltip_text(cx)
 627    }
 628
 629    fn dragged_tab_content(
 630        &self,
 631        params: TabContentParams,
 632        window: &Window,
 633        cx: &App,
 634    ) -> AnyElement {
 635        self.read(cx).tab_content(
 636            TabContentParams {
 637                selected: true,
 638                ..params
 639            },
 640            window,
 641            cx,
 642        )
 643    }
 644
 645    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
 646        let this = self.read(cx);
 647        let mut result = None;
 648        if this.is_singleton(cx) {
 649            this.for_each_project_item(cx, &mut |_, item| {
 650                result = item.project_path(cx);
 651            });
 652        }
 653        result
 654    }
 655
 656    fn workspace_settings<'a>(&self, cx: &'a App) -> &'a WorkspaceSettings {
 657        if let Some(project_path) = self.project_path(cx) {
 658            WorkspaceSettings::get(
 659                Some(SettingsLocation {
 660                    worktree_id: project_path.worktree_id,
 661                    path: &project_path.path,
 662                }),
 663                cx,
 664            )
 665        } else {
 666            WorkspaceSettings::get_global(cx)
 667        }
 668    }
 669
 670    fn project_entry_ids(&self, cx: &App) -> SmallVec<[ProjectEntryId; 3]> {
 671        let mut result = SmallVec::new();
 672        self.read(cx).for_each_project_item(cx, &mut |_, item| {
 673            if let Some(id) = item.entry_id(cx) {
 674                result.push(id);
 675            }
 676        });
 677        result
 678    }
 679
 680    fn project_paths(&self, cx: &App) -> SmallVec<[ProjectPath; 3]> {
 681        let mut result = SmallVec::new();
 682        self.read(cx).for_each_project_item(cx, &mut |_, item| {
 683            if let Some(id) = item.project_path(cx) {
 684                result.push(id);
 685            }
 686        });
 687        result
 688    }
 689
 690    fn project_item_model_ids(&self, cx: &App) -> SmallVec<[EntityId; 3]> {
 691        let mut result = SmallVec::new();
 692        self.read(cx).for_each_project_item(cx, &mut |id, _| {
 693            result.push(id);
 694        });
 695        result
 696    }
 697
 698    fn for_each_project_item(
 699        &self,
 700        cx: &App,
 701        f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
 702    ) {
 703        self.read(cx).for_each_project_item(cx, f)
 704    }
 705
 706    fn is_singleton(&self, cx: &App) -> bool {
 707        self.read(cx).is_singleton(cx)
 708    }
 709
 710    fn boxed_clone(&self) -> Box<dyn ItemHandle> {
 711        Box::new(self.clone())
 712    }
 713
 714    fn clone_on_split(
 715        &self,
 716        workspace_id: Option<WorkspaceId>,
 717        window: &mut Window,
 718        cx: &mut App,
 719    ) -> Option<Box<dyn ItemHandle>> {
 720        self.update(cx, |item, cx| item.clone_on_split(workspace_id, window, cx))
 721            .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
 722    }
 723
 724    fn added_to_pane(
 725        &self,
 726        workspace: &mut Workspace,
 727        pane: Entity<Pane>,
 728        window: &mut Window,
 729        cx: &mut Context<Workspace>,
 730    ) {
 731        let weak_item = self.downgrade();
 732        let history = pane.read(cx).nav_history_for_item(self);
 733        self.update(cx, |this, cx| {
 734            this.set_nav_history(history, window, cx);
 735            this.added_to_workspace(workspace, window, cx);
 736        });
 737
 738        if let Some(serializable_item) = self.to_serializable_item_handle(cx) {
 739            workspace
 740                .enqueue_item_serialization(serializable_item)
 741                .log_err();
 742        }
 743
 744        if workspace
 745            .panes_by_item
 746            .insert(self.item_id(), pane.downgrade())
 747            .is_none()
 748        {
 749            let mut pending_autosave = DelayedDebouncedEditAction::new();
 750            let (pending_update_tx, mut pending_update_rx) = mpsc::unbounded();
 751            let pending_update = Rc::new(RefCell::new(None));
 752
 753            let mut send_follower_updates = None;
 754            if let Some(item) = self.to_followable_item_handle(cx) {
 755                let is_project_item = item.is_project_item(window, cx);
 756                let item = item.downgrade();
 757
 758                send_follower_updates = Some(cx.spawn_in(window, {
 759                    let pending_update = pending_update.clone();
 760                    async move |workspace, cx| {
 761                        while let Some(mut leader_id) = pending_update_rx.next().await {
 762                            while let Ok(Some(id)) = pending_update_rx.try_next() {
 763                                leader_id = id;
 764                            }
 765
 766                            workspace.update_in(cx, |workspace, window, cx| {
 767                                let Some(item) = item.upgrade() else { return };
 768                                workspace.update_followers(
 769                                    is_project_item,
 770                                    proto::update_followers::Variant::UpdateView(
 771                                        proto::UpdateView {
 772                                            id: item
 773                                                .remote_id(workspace.client(), window, cx)
 774                                                .and_then(|id| id.to_proto()),
 775                                            variant: pending_update.borrow_mut().take(),
 776                                            leader_id,
 777                                        },
 778                                    ),
 779                                    window,
 780                                    cx,
 781                                );
 782                            })?;
 783                            cx.background_executor().timer(LEADER_UPDATE_THROTTLE).await;
 784                        }
 785                        anyhow::Ok(())
 786                    }
 787                }));
 788            }
 789
 790            let mut event_subscription = Some(cx.subscribe_in(
 791                self,
 792                window,
 793                move |workspace, item: &Entity<T>, event, window, cx| {
 794                    let pane = if let Some(pane) = workspace
 795                        .panes_by_item
 796                        .get(&item.item_id())
 797                        .and_then(|pane| pane.upgrade())
 798                    {
 799                        pane
 800                    } else {
 801                        return;
 802                    };
 803
 804                    if let Some(item) = item.to_followable_item_handle(cx) {
 805                        let leader_id = workspace.leader_for_pane(&pane);
 806
 807                        if let Some(leader_id) = leader_id {
 808                            if let Some(FollowEvent::Unfollow) = item.to_follow_event(event) {
 809                                workspace.unfollow(leader_id, window, cx);
 810                            }
 811                        }
 812
 813                        if item.item_focus_handle(cx).contains_focused(window, cx) {
 814                            match leader_id {
 815                                Some(CollaboratorId::Agent) => {}
 816                                Some(CollaboratorId::PeerId(leader_peer_id)) => {
 817                                    item.add_event_to_update_proto(
 818                                        event,
 819                                        &mut pending_update.borrow_mut(),
 820                                        window,
 821                                        cx,
 822                                    );
 823                                    pending_update_tx.unbounded_send(Some(leader_peer_id)).ok();
 824                                }
 825                                None => {
 826                                    item.add_event_to_update_proto(
 827                                        event,
 828                                        &mut pending_update.borrow_mut(),
 829                                        window,
 830                                        cx,
 831                                    );
 832                                    pending_update_tx.unbounded_send(None).ok();
 833                                }
 834                            }
 835                        }
 836                    }
 837
 838                    if let Some(item) = item.to_serializable_item_handle(cx) {
 839                        if item.should_serialize(event, cx) {
 840                            workspace.enqueue_item_serialization(item).ok();
 841                        }
 842                    }
 843
 844                    T::to_item_events(event, |event| match event {
 845                        ItemEvent::CloseItem => {
 846                            pane.update(cx, |pane, cx| {
 847                                pane.close_item_by_id(
 848                                    item.item_id(),
 849                                    crate::SaveIntent::Close,
 850                                    window,
 851                                    cx,
 852                                )
 853                            })
 854                            .detach_and_log_err(cx);
 855                        }
 856
 857                        ItemEvent::UpdateTab => {
 858                            workspace.update_item_dirty_state(item, window, cx);
 859
 860                            if item.has_deleted_file(cx)
 861                                && !item.is_dirty(cx)
 862                                && item.workspace_settings(cx).close_on_file_delete
 863                            {
 864                                let item_id = item.item_id();
 865                                let close_item_task = pane.update(cx, |pane, cx| {
 866                                    pane.close_item_by_id(
 867                                        item_id,
 868                                        crate::SaveIntent::Close,
 869                                        window,
 870                                        cx,
 871                                    )
 872                                });
 873                                cx.spawn_in(window, {
 874                                    let pane = pane.clone();
 875                                    async move |_workspace, cx| {
 876                                        close_item_task.await?;
 877                                        pane.update(cx, |pane, _cx| {
 878                                            pane.nav_history_mut().remove_item(item_id);
 879                                        })
 880                                    }
 881                                })
 882                                .detach_and_log_err(cx);
 883                            } else {
 884                                pane.update(cx, |_, cx| {
 885                                    cx.emit(pane::Event::ChangeItemTitle);
 886                                    cx.notify();
 887                                });
 888                            }
 889                        }
 890
 891                        ItemEvent::Edit => {
 892                            let autosave = item.workspace_settings(cx).autosave;
 893
 894                            if let AutosaveSetting::AfterDelay { milliseconds } = autosave {
 895                                let delay = Duration::from_millis(milliseconds);
 896                                let item = item.clone();
 897                                pending_autosave.fire_new(
 898                                    delay,
 899                                    window,
 900                                    cx,
 901                                    move |workspace, window, cx| {
 902                                        Pane::autosave_item(
 903                                            &item,
 904                                            workspace.project().clone(),
 905                                            window,
 906                                            cx,
 907                                        )
 908                                    },
 909                                );
 910                            }
 911                            pane.update(cx, |pane, cx| pane.handle_item_edit(item.item_id(), cx));
 912                        }
 913
 914                        _ => {}
 915                    });
 916                },
 917            ));
 918
 919            cx.on_blur(
 920                &self.read(cx).focus_handle(cx),
 921                window,
 922                move |workspace, window, cx| {
 923                    if let Some(item) = weak_item.upgrade() {
 924                        if item.workspace_settings(cx).autosave == AutosaveSetting::OnFocusChange {
 925                            Pane::autosave_item(&item, workspace.project.clone(), window, cx)
 926                                .detach_and_log_err(cx);
 927                        }
 928                    }
 929                },
 930            )
 931            .detach();
 932
 933            let item_id = self.item_id();
 934            workspace.update_item_dirty_state(self, window, cx);
 935            cx.observe_release_in(self, window, move |workspace, _, _, _| {
 936                workspace.panes_by_item.remove(&item_id);
 937                event_subscription.take();
 938                send_follower_updates.take();
 939            })
 940            .detach();
 941        }
 942
 943        cx.defer_in(window, |workspace, window, cx| {
 944            workspace.serialize_workspace(window, cx);
 945        });
 946    }
 947
 948    fn discarded(&self, project: Entity<Project>, window: &mut Window, cx: &mut App) {
 949        self.update(cx, |this, cx| this.discarded(project, window, cx));
 950    }
 951
 952    fn deactivated(&self, window: &mut Window, cx: &mut App) {
 953        self.update(cx, |this, cx| this.deactivated(window, cx));
 954    }
 955
 956    fn workspace_deactivated(&self, window: &mut Window, cx: &mut App) {
 957        self.update(cx, |this, cx| this.workspace_deactivated(window, cx));
 958    }
 959
 960    fn navigate(&self, data: Box<dyn Any>, window: &mut Window, cx: &mut App) -> bool {
 961        self.update(cx, |this, cx| this.navigate(data, window, cx))
 962    }
 963
 964    fn item_id(&self) -> EntityId {
 965        self.entity_id()
 966    }
 967
 968    fn to_any(&self) -> AnyView {
 969        self.clone().into()
 970    }
 971
 972    fn is_dirty(&self, cx: &App) -> bool {
 973        self.read(cx).is_dirty(cx)
 974    }
 975
 976    fn has_deleted_file(&self, cx: &App) -> bool {
 977        self.read(cx).has_deleted_file(cx)
 978    }
 979
 980    fn has_conflict(&self, cx: &App) -> bool {
 981        self.read(cx).has_conflict(cx)
 982    }
 983
 984    fn can_save(&self, cx: &App) -> bool {
 985        self.read(cx).can_save(cx)
 986    }
 987
 988    fn can_save_as(&self, cx: &App) -> bool {
 989        self.read(cx).can_save_as(cx)
 990    }
 991
 992    fn save(
 993        &self,
 994        format: bool,
 995        project: Entity<Project>,
 996        window: &mut Window,
 997        cx: &mut App,
 998    ) -> Task<Result<()>> {
 999        self.update(cx, |item, cx| item.save(format, project, window, cx))
1000    }
1001
1002    fn save_as(
1003        &self,
1004        project: Entity<Project>,
1005        path: ProjectPath,
1006        window: &mut Window,
1007        cx: &mut App,
1008    ) -> Task<anyhow::Result<()>> {
1009        self.update(cx, |item, cx| item.save_as(project, path, window, cx))
1010    }
1011
1012    fn reload(
1013        &self,
1014        project: Entity<Project>,
1015        window: &mut Window,
1016        cx: &mut App,
1017    ) -> Task<Result<()>> {
1018        self.update(cx, |item, cx| item.reload(project, window, cx))
1019    }
1020
1021    fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a App) -> Option<AnyView> {
1022        self.read(cx).act_as_type(type_id, self, cx)
1023    }
1024
1025    fn to_followable_item_handle(&self, cx: &App) -> Option<Box<dyn FollowableItemHandle>> {
1026        FollowableViewRegistry::to_followable_view(self.clone(), cx)
1027    }
1028
1029    fn on_release(
1030        &self,
1031        cx: &mut App,
1032        callback: Box<dyn FnOnce(&mut App) + Send>,
1033    ) -> gpui::Subscription {
1034        cx.observe_release(self, move |_, cx| callback(cx))
1035    }
1036
1037    fn to_searchable_item_handle(&self, cx: &App) -> Option<Box<dyn SearchableItemHandle>> {
1038        self.read(cx).as_searchable(self)
1039    }
1040
1041    fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
1042        self.read(cx).breadcrumb_location(cx)
1043    }
1044
1045    fn breadcrumbs(&self, theme: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
1046        self.read(cx).breadcrumbs(theme, cx)
1047    }
1048
1049    fn show_toolbar(&self, cx: &App) -> bool {
1050        self.read(cx).show_toolbar()
1051    }
1052
1053    fn pixel_position_of_cursor(&self, cx: &App) -> Option<Point<Pixels>> {
1054        self.read(cx).pixel_position_of_cursor(cx)
1055    }
1056
1057    fn downgrade_item(&self) -> Box<dyn WeakItemHandle> {
1058        Box::new(self.downgrade())
1059    }
1060
1061    fn to_serializable_item_handle(&self, cx: &App) -> Option<Box<dyn SerializableItemHandle>> {
1062        SerializableItemRegistry::view_to_serializable_item_handle(self.to_any(), cx)
1063    }
1064
1065    fn preserve_preview(&self, cx: &App) -> bool {
1066        self.read(cx).preserve_preview(cx)
1067    }
1068
1069    fn include_in_nav_history(&self) -> bool {
1070        T::include_in_nav_history()
1071    }
1072
1073    fn relay_action(&self, action: Box<dyn Action>, window: &mut Window, cx: &mut App) {
1074        self.update(cx, |this, cx| {
1075            this.focus_handle(cx).focus(window);
1076            window.dispatch_action(action, cx);
1077        })
1078    }
1079}
1080
1081impl From<Box<dyn ItemHandle>> for AnyView {
1082    fn from(val: Box<dyn ItemHandle>) -> Self {
1083        val.to_any()
1084    }
1085}
1086
1087impl From<&Box<dyn ItemHandle>> for AnyView {
1088    fn from(val: &Box<dyn ItemHandle>) -> Self {
1089        val.to_any()
1090    }
1091}
1092
1093impl Clone for Box<dyn ItemHandle> {
1094    fn clone(&self) -> Box<dyn ItemHandle> {
1095        self.boxed_clone()
1096    }
1097}
1098
1099impl<T: Item> WeakItemHandle for WeakEntity<T> {
1100    fn id(&self) -> EntityId {
1101        self.entity_id()
1102    }
1103
1104    fn boxed_clone(&self) -> Box<dyn WeakItemHandle> {
1105        Box::new(self.clone())
1106    }
1107
1108    fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
1109        self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
1110    }
1111}
1112
1113#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1114pub struct ProjectItemKind(pub &'static str);
1115
1116pub trait ProjectItem: Item {
1117    type Item: project::ProjectItem;
1118
1119    fn project_item_kind() -> Option<ProjectItemKind> {
1120        None
1121    }
1122
1123    fn for_project_item(
1124        project: Entity<Project>,
1125        pane: Option<&Pane>,
1126        item: Entity<Self::Item>,
1127        window: &mut Window,
1128        cx: &mut Context<Self>,
1129    ) -> Self
1130    where
1131        Self: Sized;
1132}
1133
1134#[derive(Debug)]
1135pub enum FollowEvent {
1136    Unfollow,
1137}
1138
1139pub enum Dedup {
1140    KeepExisting,
1141    ReplaceExisting,
1142}
1143
1144pub trait FollowableItem: Item {
1145    fn remote_id(&self) -> Option<ViewId>;
1146    fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant>;
1147    fn from_state_proto(
1148        project: Entity<Workspace>,
1149        id: ViewId,
1150        state: &mut Option<proto::view::Variant>,
1151        window: &mut Window,
1152        cx: &mut App,
1153    ) -> Option<Task<Result<Entity<Self>>>>;
1154    fn to_follow_event(event: &Self::Event) -> Option<FollowEvent>;
1155    fn add_event_to_update_proto(
1156        &self,
1157        event: &Self::Event,
1158        update: &mut Option<proto::update_view::Variant>,
1159        window: &Window,
1160        cx: &App,
1161    ) -> bool;
1162    fn apply_update_proto(
1163        &mut self,
1164        project: &Entity<Project>,
1165        message: proto::update_view::Variant,
1166        window: &mut Window,
1167        cx: &mut Context<Self>,
1168    ) -> Task<Result<()>>;
1169    fn is_project_item(&self, window: &Window, cx: &App) -> bool;
1170    fn set_leader_id(
1171        &mut self,
1172        leader_peer_id: Option<CollaboratorId>,
1173        window: &mut Window,
1174        cx: &mut Context<Self>,
1175    );
1176    fn dedup(&self, existing: &Self, window: &Window, cx: &App) -> Option<Dedup>;
1177    fn update_agent_location(
1178        &mut self,
1179        _location: language::Anchor,
1180        _window: &mut Window,
1181        _cx: &mut Context<Self>,
1182    ) {
1183    }
1184}
1185
1186pub trait FollowableItemHandle: ItemHandle {
1187    fn remote_id(&self, client: &Arc<Client>, window: &mut Window, cx: &mut App) -> Option<ViewId>;
1188    fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle>;
1189    fn set_leader_id(
1190        &self,
1191        leader_peer_id: Option<CollaboratorId>,
1192        window: &mut Window,
1193        cx: &mut App,
1194    );
1195    fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant>;
1196    fn add_event_to_update_proto(
1197        &self,
1198        event: &dyn Any,
1199        update: &mut Option<proto::update_view::Variant>,
1200        window: &mut Window,
1201        cx: &mut App,
1202    ) -> bool;
1203    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
1204    fn apply_update_proto(
1205        &self,
1206        project: &Entity<Project>,
1207        message: proto::update_view::Variant,
1208        window: &mut Window,
1209        cx: &mut App,
1210    ) -> Task<Result<()>>;
1211    fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool;
1212    fn dedup(
1213        &self,
1214        existing: &dyn FollowableItemHandle,
1215        window: &mut Window,
1216        cx: &mut App,
1217    ) -> Option<Dedup>;
1218    fn update_agent_location(&self, location: language::Anchor, window: &mut Window, cx: &mut App);
1219}
1220
1221impl<T: FollowableItem> FollowableItemHandle for Entity<T> {
1222    fn remote_id(&self, client: &Arc<Client>, _: &mut Window, cx: &mut App) -> Option<ViewId> {
1223        self.read(cx).remote_id().or_else(|| {
1224            client.peer_id().map(|creator| ViewId {
1225                creator: CollaboratorId::PeerId(creator),
1226                id: self.item_id().as_u64(),
1227            })
1228        })
1229    }
1230
1231    fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle> {
1232        Box::new(self.downgrade())
1233    }
1234
1235    fn set_leader_id(&self, leader_id: Option<CollaboratorId>, window: &mut Window, cx: &mut App) {
1236        self.update(cx, |this, cx| this.set_leader_id(leader_id, window, cx))
1237    }
1238
1239    fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant> {
1240        self.read(cx).to_state_proto(window, cx)
1241    }
1242
1243    fn add_event_to_update_proto(
1244        &self,
1245        event: &dyn Any,
1246        update: &mut Option<proto::update_view::Variant>,
1247        window: &mut Window,
1248        cx: &mut App,
1249    ) -> bool {
1250        if let Some(event) = event.downcast_ref() {
1251            self.read(cx)
1252                .add_event_to_update_proto(event, update, window, cx)
1253        } else {
1254            false
1255        }
1256    }
1257
1258    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
1259        T::to_follow_event(event.downcast_ref()?)
1260    }
1261
1262    fn apply_update_proto(
1263        &self,
1264        project: &Entity<Project>,
1265        message: proto::update_view::Variant,
1266        window: &mut Window,
1267        cx: &mut App,
1268    ) -> Task<Result<()>> {
1269        self.update(cx, |this, cx| {
1270            this.apply_update_proto(project, message, window, cx)
1271        })
1272    }
1273
1274    fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool {
1275        self.read(cx).is_project_item(window, cx)
1276    }
1277
1278    fn dedup(
1279        &self,
1280        existing: &dyn FollowableItemHandle,
1281        window: &mut Window,
1282        cx: &mut App,
1283    ) -> Option<Dedup> {
1284        let existing = existing.to_any().downcast::<T>().ok()?;
1285        self.read(cx).dedup(existing.read(cx), window, cx)
1286    }
1287
1288    fn update_agent_location(&self, location: language::Anchor, window: &mut Window, cx: &mut App) {
1289        self.update(cx, |this, cx| {
1290            this.update_agent_location(location, window, cx)
1291        })
1292    }
1293}
1294
1295pub trait WeakFollowableItemHandle: Send + Sync {
1296    fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>>;
1297}
1298
1299impl<T: FollowableItem> WeakFollowableItemHandle for WeakEntity<T> {
1300    fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>> {
1301        Some(Box::new(self.upgrade()?))
1302    }
1303}
1304
1305#[cfg(any(test, feature = "test-support"))]
1306pub mod test {
1307    use super::{Item, ItemEvent, SerializableItem, TabContentParams};
1308    use crate::{ItemId, ItemNavHistory, Workspace, WorkspaceId};
1309    use gpui::{
1310        AnyElement, App, AppContext as _, Context, Entity, EntityId, EventEmitter, Focusable,
1311        InteractiveElement, IntoElement, Render, SharedString, Task, WeakEntity, Window,
1312    };
1313    use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
1314    use std::{any::Any, cell::Cell, path::Path};
1315
1316    pub struct TestProjectItem {
1317        pub entry_id: Option<ProjectEntryId>,
1318        pub project_path: Option<ProjectPath>,
1319        pub is_dirty: bool,
1320    }
1321
1322    pub struct TestItem {
1323        pub workspace_id: Option<WorkspaceId>,
1324        pub state: String,
1325        pub label: String,
1326        pub save_count: usize,
1327        pub save_as_count: usize,
1328        pub reload_count: usize,
1329        pub is_dirty: bool,
1330        pub is_singleton: bool,
1331        pub has_conflict: bool,
1332        pub has_deleted_file: bool,
1333        pub project_items: Vec<Entity<TestProjectItem>>,
1334        pub nav_history: Option<ItemNavHistory>,
1335        pub tab_descriptions: Option<Vec<&'static str>>,
1336        pub tab_detail: Cell<Option<usize>>,
1337        serialize: Option<Box<dyn Fn() -> Option<Task<anyhow::Result<()>>>>>,
1338        focus_handle: gpui::FocusHandle,
1339    }
1340
1341    impl project::ProjectItem for TestProjectItem {
1342        fn try_open(
1343            _project: &Entity<Project>,
1344            _path: &ProjectPath,
1345            _cx: &mut App,
1346        ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
1347            None
1348        }
1349        fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
1350            self.entry_id
1351        }
1352
1353        fn project_path(&self, _: &App) -> Option<ProjectPath> {
1354            self.project_path.clone()
1355        }
1356
1357        fn is_dirty(&self) -> bool {
1358            self.is_dirty
1359        }
1360    }
1361
1362    pub enum TestItemEvent {
1363        Edit,
1364    }
1365
1366    impl TestProjectItem {
1367        pub fn new(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1368            let entry_id = Some(ProjectEntryId::from_proto(id));
1369            let project_path = Some(ProjectPath {
1370                worktree_id: WorktreeId::from_usize(0),
1371                path: Path::new(path).into(),
1372            });
1373            cx.new(|_| Self {
1374                entry_id,
1375                project_path,
1376                is_dirty: false,
1377            })
1378        }
1379
1380        pub fn new_untitled(cx: &mut App) -> Entity<Self> {
1381            cx.new(|_| Self {
1382                project_path: None,
1383                entry_id: None,
1384                is_dirty: false,
1385            })
1386        }
1387
1388        pub fn new_dirty(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1389            let entry_id = Some(ProjectEntryId::from_proto(id));
1390            let project_path = Some(ProjectPath {
1391                worktree_id: WorktreeId::from_usize(0),
1392                path: Path::new(path).into(),
1393            });
1394            cx.new(|_| Self {
1395                entry_id,
1396                project_path,
1397                is_dirty: true,
1398            })
1399        }
1400    }
1401
1402    impl TestItem {
1403        pub fn new(cx: &mut Context<Self>) -> Self {
1404            Self {
1405                state: String::new(),
1406                label: String::new(),
1407                save_count: 0,
1408                save_as_count: 0,
1409                reload_count: 0,
1410                is_dirty: false,
1411                has_conflict: false,
1412                has_deleted_file: false,
1413                project_items: Vec::new(),
1414                is_singleton: true,
1415                nav_history: None,
1416                tab_descriptions: None,
1417                tab_detail: Default::default(),
1418                workspace_id: Default::default(),
1419                focus_handle: cx.focus_handle(),
1420                serialize: None,
1421            }
1422        }
1423
1424        pub fn new_deserialized(id: WorkspaceId, cx: &mut Context<Self>) -> Self {
1425            let mut this = Self::new(cx);
1426            this.workspace_id = Some(id);
1427            this
1428        }
1429
1430        pub fn with_label(mut self, state: &str) -> Self {
1431            self.label = state.to_string();
1432            self
1433        }
1434
1435        pub fn with_singleton(mut self, singleton: bool) -> Self {
1436            self.is_singleton = singleton;
1437            self
1438        }
1439
1440        pub fn set_has_deleted_file(&mut self, deleted: bool) {
1441            self.has_deleted_file = deleted;
1442        }
1443
1444        pub fn with_dirty(mut self, dirty: bool) -> Self {
1445            self.is_dirty = dirty;
1446            self
1447        }
1448
1449        pub fn with_conflict(mut self, has_conflict: bool) -> Self {
1450            self.has_conflict = has_conflict;
1451            self
1452        }
1453
1454        pub fn with_project_items(mut self, items: &[Entity<TestProjectItem>]) -> Self {
1455            self.project_items.clear();
1456            self.project_items.extend(items.iter().cloned());
1457            self
1458        }
1459
1460        pub fn with_serialize(
1461            mut self,
1462            serialize: impl Fn() -> Option<Task<anyhow::Result<()>>> + 'static,
1463        ) -> Self {
1464            self.serialize = Some(Box::new(serialize));
1465            self
1466        }
1467
1468        pub fn set_state(&mut self, state: String, cx: &mut Context<Self>) {
1469            self.push_to_nav_history(cx);
1470            self.state = state;
1471        }
1472
1473        fn push_to_nav_history(&mut self, cx: &mut Context<Self>) {
1474            if let Some(history) = &mut self.nav_history {
1475                history.push(Some(Box::new(self.state.clone())), cx);
1476            }
1477        }
1478    }
1479
1480    impl Render for TestItem {
1481        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1482            gpui::div().track_focus(&self.focus_handle(cx))
1483        }
1484    }
1485
1486    impl EventEmitter<ItemEvent> for TestItem {}
1487
1488    impl Focusable for TestItem {
1489        fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
1490            self.focus_handle.clone()
1491        }
1492    }
1493
1494    impl Item for TestItem {
1495        type Event = ItemEvent;
1496
1497        fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1498            f(*event)
1499        }
1500
1501        fn tab_content_text(&self, detail: usize, _cx: &App) -> SharedString {
1502            self.tab_descriptions
1503                .as_ref()
1504                .and_then(|descriptions| {
1505                    let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
1506                    description.into()
1507                })
1508                .unwrap_or_default()
1509                .into()
1510        }
1511
1512        fn telemetry_event_text(&self) -> Option<&'static str> {
1513            None
1514        }
1515
1516        fn tab_content(&self, params: TabContentParams, _window: &Window, _cx: &App) -> AnyElement {
1517            self.tab_detail.set(params.detail);
1518            gpui::div().into_any_element()
1519        }
1520
1521        fn for_each_project_item(
1522            &self,
1523            cx: &App,
1524            f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
1525        ) {
1526            self.project_items
1527                .iter()
1528                .for_each(|item| f(item.entity_id(), item.read(cx)))
1529        }
1530
1531        fn is_singleton(&self, _: &App) -> bool {
1532            self.is_singleton
1533        }
1534
1535        fn set_nav_history(
1536            &mut self,
1537            history: ItemNavHistory,
1538            _window: &mut Window,
1539            _: &mut Context<Self>,
1540        ) {
1541            self.nav_history = Some(history);
1542        }
1543
1544        fn navigate(
1545            &mut self,
1546            state: Box<dyn Any>,
1547            _window: &mut Window,
1548            _: &mut Context<Self>,
1549        ) -> bool {
1550            let state = *state.downcast::<String>().unwrap_or_default();
1551            if state != self.state {
1552                self.state = state;
1553                true
1554            } else {
1555                false
1556            }
1557        }
1558
1559        fn deactivated(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1560            self.push_to_nav_history(cx);
1561        }
1562
1563        fn clone_on_split(
1564            &self,
1565            _workspace_id: Option<WorkspaceId>,
1566            _: &mut Window,
1567            cx: &mut Context<Self>,
1568        ) -> Option<Entity<Self>>
1569        where
1570            Self: Sized,
1571        {
1572            Some(cx.new(|cx| Self {
1573                state: self.state.clone(),
1574                label: self.label.clone(),
1575                save_count: self.save_count,
1576                save_as_count: self.save_as_count,
1577                reload_count: self.reload_count,
1578                is_dirty: self.is_dirty,
1579                is_singleton: self.is_singleton,
1580                has_conflict: self.has_conflict,
1581                has_deleted_file: self.has_deleted_file,
1582                project_items: self.project_items.clone(),
1583                nav_history: None,
1584                tab_descriptions: None,
1585                tab_detail: Default::default(),
1586                workspace_id: self.workspace_id,
1587                focus_handle: cx.focus_handle(),
1588                serialize: None,
1589            }))
1590        }
1591
1592        fn is_dirty(&self, _: &App) -> bool {
1593            self.is_dirty
1594        }
1595
1596        fn has_conflict(&self, _: &App) -> bool {
1597            self.has_conflict
1598        }
1599
1600        fn has_deleted_file(&self, _: &App) -> bool {
1601            self.has_deleted_file
1602        }
1603
1604        fn can_save(&self, cx: &App) -> bool {
1605            !self.project_items.is_empty()
1606                && self
1607                    .project_items
1608                    .iter()
1609                    .all(|item| item.read(cx).entry_id.is_some())
1610        }
1611
1612        fn can_save_as(&self, _cx: &App) -> bool {
1613            self.is_singleton
1614        }
1615
1616        fn save(
1617            &mut self,
1618            _: bool,
1619            _: Entity<Project>,
1620            _window: &mut Window,
1621            cx: &mut Context<Self>,
1622        ) -> Task<anyhow::Result<()>> {
1623            self.save_count += 1;
1624            self.is_dirty = false;
1625            for item in &self.project_items {
1626                item.update(cx, |item, _| {
1627                    if item.is_dirty {
1628                        item.is_dirty = false;
1629                    }
1630                })
1631            }
1632            Task::ready(Ok(()))
1633        }
1634
1635        fn save_as(
1636            &mut self,
1637            _: Entity<Project>,
1638            _: ProjectPath,
1639            _window: &mut Window,
1640            _: &mut Context<Self>,
1641        ) -> Task<anyhow::Result<()>> {
1642            self.save_as_count += 1;
1643            self.is_dirty = false;
1644            Task::ready(Ok(()))
1645        }
1646
1647        fn reload(
1648            &mut self,
1649            _: Entity<Project>,
1650            _window: &mut Window,
1651            _: &mut Context<Self>,
1652        ) -> Task<anyhow::Result<()>> {
1653            self.reload_count += 1;
1654            self.is_dirty = false;
1655            Task::ready(Ok(()))
1656        }
1657    }
1658
1659    impl SerializableItem for TestItem {
1660        fn serialized_item_kind() -> &'static str {
1661            "TestItem"
1662        }
1663
1664        fn deserialize(
1665            _project: Entity<Project>,
1666            _workspace: WeakEntity<Workspace>,
1667            workspace_id: WorkspaceId,
1668            _item_id: ItemId,
1669            _window: &mut Window,
1670            cx: &mut App,
1671        ) -> Task<anyhow::Result<Entity<Self>>> {
1672            let entity = cx.new(|cx| Self::new_deserialized(workspace_id, cx));
1673            Task::ready(Ok(entity))
1674        }
1675
1676        fn cleanup(
1677            _workspace_id: WorkspaceId,
1678            _alive_items: Vec<ItemId>,
1679            _window: &mut Window,
1680            _cx: &mut App,
1681        ) -> Task<anyhow::Result<()>> {
1682            Task::ready(Ok(()))
1683        }
1684
1685        fn serialize(
1686            &mut self,
1687            _workspace: &mut Workspace,
1688            _item_id: ItemId,
1689            _closing: bool,
1690            _window: &mut Window,
1691            _cx: &mut Context<Self>,
1692        ) -> Option<Task<anyhow::Result<()>>> {
1693            if let Some(serialize) = self.serialize.take() {
1694                let result = serialize();
1695                self.serialize = Some(serialize);
1696                result
1697            } else {
1698                None
1699            }
1700        }
1701
1702        fn should_serialize(&self, _event: &Self::Event) -> bool {
1703            false
1704        }
1705    }
1706}