item.rs

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