item.rs

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