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