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                        // Also skip autosave if focus moved to a modal (e.g., command palette),
 890                        // since the user is still interacting with the workspace.
 891                        let focus_handle = item.item_focus_handle(cx);
 892                        if !focus_handle.contains_focused(window, cx)
 893                            && !workspace.has_active_modal(window, cx)
 894                        {
 895                            Pane::autosave_item(&item, workspace.project.clone(), window, cx)
 896                                .detach_and_log_err(cx);
 897                        }
 898                    }
 899                },
 900            )
 901            .detach();
 902
 903            let item_id = self.item_id();
 904            workspace.update_item_dirty_state(self, window, cx);
 905            cx.observe_release_in(self, window, move |workspace, _, _, _| {
 906                workspace.panes_by_item.remove(&item_id);
 907                event_subscription.take();
 908                send_follower_updates.take();
 909            })
 910            .detach();
 911        }
 912
 913        cx.defer_in(window, |workspace, window, cx| {
 914            workspace.serialize_workspace(window, cx);
 915        });
 916    }
 917
 918    fn deactivated(&self, window: &mut Window, cx: &mut App) {
 919        self.update(cx, |this, cx| this.deactivated(window, cx));
 920    }
 921
 922    fn on_removed(&self, cx: &App) {
 923        self.read(cx).on_removed(cx);
 924    }
 925
 926    fn workspace_deactivated(&self, window: &mut Window, cx: &mut App) {
 927        self.update(cx, |this, cx| this.workspace_deactivated(window, cx));
 928    }
 929
 930    fn navigate(&self, data: Box<dyn Any>, window: &mut Window, cx: &mut App) -> bool {
 931        self.update(cx, |this, cx| this.navigate(data, window, cx))
 932    }
 933
 934    fn item_id(&self) -> EntityId {
 935        self.entity_id()
 936    }
 937
 938    fn to_any_view(&self) -> AnyView {
 939        self.clone().into()
 940    }
 941
 942    fn is_dirty(&self, cx: &App) -> bool {
 943        self.read(cx).is_dirty(cx)
 944    }
 945
 946    fn has_deleted_file(&self, cx: &App) -> bool {
 947        self.read(cx).has_deleted_file(cx)
 948    }
 949
 950    fn has_conflict(&self, cx: &App) -> bool {
 951        self.read(cx).has_conflict(cx)
 952    }
 953
 954    fn can_save(&self, cx: &App) -> bool {
 955        self.read(cx).can_save(cx)
 956    }
 957
 958    fn can_save_as(&self, cx: &App) -> bool {
 959        self.read(cx).can_save_as(cx)
 960    }
 961
 962    fn save(
 963        &self,
 964        options: SaveOptions,
 965        project: Entity<Project>,
 966        window: &mut Window,
 967        cx: &mut App,
 968    ) -> Task<Result<()>> {
 969        self.update(cx, |item, cx| item.save(options, project, window, cx))
 970    }
 971
 972    fn save_as(
 973        &self,
 974        project: Entity<Project>,
 975        path: ProjectPath,
 976        window: &mut Window,
 977        cx: &mut App,
 978    ) -> Task<anyhow::Result<()>> {
 979        self.update(cx, |item, cx| item.save_as(project, path, window, cx))
 980    }
 981
 982    fn reload(
 983        &self,
 984        project: Entity<Project>,
 985        window: &mut Window,
 986        cx: &mut App,
 987    ) -> Task<Result<()>> {
 988        self.update(cx, |item, cx| item.reload(project, window, cx))
 989    }
 990
 991    fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a App) -> Option<AnyEntity> {
 992        self.read(cx).act_as_type(type_id, self, cx)
 993    }
 994
 995    fn to_followable_item_handle(&self, cx: &App) -> Option<Box<dyn FollowableItemHandle>> {
 996        FollowableViewRegistry::to_followable_view(self.clone(), cx)
 997    }
 998
 999    fn on_release(
1000        &self,
1001        cx: &mut App,
1002        callback: Box<dyn FnOnce(&mut App) + Send>,
1003    ) -> gpui::Subscription {
1004        cx.observe_release(self, move |_, cx| callback(cx))
1005    }
1006
1007    fn to_searchable_item_handle(&self, cx: &App) -> Option<Box<dyn SearchableItemHandle>> {
1008        self.read(cx).as_searchable(self, cx)
1009    }
1010
1011    fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
1012        self.read(cx).breadcrumb_location(cx)
1013    }
1014
1015    fn breadcrumbs(&self, theme: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
1016        self.read(cx).breadcrumbs(theme, cx)
1017    }
1018
1019    fn breadcrumb_prefix(&self, window: &mut Window, cx: &mut App) -> Option<gpui::AnyElement> {
1020        self.update(cx, |item, cx| item.breadcrumb_prefix(window, cx))
1021    }
1022
1023    fn show_toolbar(&self, cx: &App) -> bool {
1024        self.read(cx).show_toolbar()
1025    }
1026
1027    fn pixel_position_of_cursor(&self, cx: &App) -> Option<Point<Pixels>> {
1028        self.read(cx).pixel_position_of_cursor(cx)
1029    }
1030
1031    fn downgrade_item(&self) -> Box<dyn WeakItemHandle> {
1032        Box::new(self.downgrade())
1033    }
1034
1035    fn to_serializable_item_handle(&self, cx: &App) -> Option<Box<dyn SerializableItemHandle>> {
1036        SerializableItemRegistry::view_to_serializable_item_handle(self.to_any_view(), cx)
1037    }
1038
1039    fn preserve_preview(&self, cx: &App) -> bool {
1040        self.read(cx).preserve_preview(cx)
1041    }
1042
1043    fn include_in_nav_history(&self) -> bool {
1044        T::include_in_nav_history()
1045    }
1046
1047    fn relay_action(&self, action: Box<dyn Action>, window: &mut Window, cx: &mut App) {
1048        self.update(cx, |this, cx| {
1049            this.focus_handle(cx).focus(window, cx);
1050            window.dispatch_action(action, cx);
1051        })
1052    }
1053}
1054
1055impl From<Box<dyn ItemHandle>> for AnyView {
1056    fn from(val: Box<dyn ItemHandle>) -> Self {
1057        val.to_any_view()
1058    }
1059}
1060
1061impl From<&Box<dyn ItemHandle>> for AnyView {
1062    fn from(val: &Box<dyn ItemHandle>) -> Self {
1063        val.to_any_view()
1064    }
1065}
1066
1067impl Clone for Box<dyn ItemHandle> {
1068    fn clone(&self) -> Box<dyn ItemHandle> {
1069        self.boxed_clone()
1070    }
1071}
1072
1073impl<T: Item> WeakItemHandle for WeakEntity<T> {
1074    fn id(&self) -> EntityId {
1075        self.entity_id()
1076    }
1077
1078    fn boxed_clone(&self) -> Box<dyn WeakItemHandle> {
1079        Box::new(self.clone())
1080    }
1081
1082    fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
1083        self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
1084    }
1085}
1086
1087#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1088pub struct ProjectItemKind(pub &'static str);
1089
1090pub trait ProjectItem: Item {
1091    type Item: project::ProjectItem;
1092
1093    fn project_item_kind() -> Option<ProjectItemKind> {
1094        None
1095    }
1096
1097    fn for_project_item(
1098        project: Entity<Project>,
1099        pane: Option<&Pane>,
1100        item: Entity<Self::Item>,
1101        window: &mut Window,
1102        cx: &mut Context<Self>,
1103    ) -> Self
1104    where
1105        Self: Sized;
1106
1107    /// A fallback handler, which will be called after [`project::ProjectItem::try_open`] fails,
1108    /// with the error from that failure as an argument.
1109    /// Allows to open an item that can gracefully display and handle errors.
1110    fn for_broken_project_item(
1111        _abs_path: &Path,
1112        _is_local: bool,
1113        _e: &anyhow::Error,
1114        _window: &mut Window,
1115        _cx: &mut App,
1116    ) -> Option<InvalidItemView>
1117    where
1118        Self: Sized,
1119    {
1120        None
1121    }
1122}
1123
1124#[derive(Debug)]
1125pub enum FollowEvent {
1126    Unfollow,
1127}
1128
1129pub enum Dedup {
1130    KeepExisting,
1131    ReplaceExisting,
1132}
1133
1134pub trait FollowableItem: Item {
1135    fn remote_id(&self) -> Option<ViewId>;
1136    fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant>;
1137    fn from_state_proto(
1138        project: Entity<Workspace>,
1139        id: ViewId,
1140        state: &mut Option<proto::view::Variant>,
1141        window: &mut Window,
1142        cx: &mut App,
1143    ) -> Option<Task<Result<Entity<Self>>>>;
1144    fn to_follow_event(event: &Self::Event) -> Option<FollowEvent>;
1145    fn add_event_to_update_proto(
1146        &self,
1147        event: &Self::Event,
1148        update: &mut Option<proto::update_view::Variant>,
1149        window: &Window,
1150        cx: &App,
1151    ) -> bool;
1152    fn apply_update_proto(
1153        &mut self,
1154        project: &Entity<Project>,
1155        message: proto::update_view::Variant,
1156        window: &mut Window,
1157        cx: &mut Context<Self>,
1158    ) -> Task<Result<()>>;
1159    fn is_project_item(&self, window: &Window, cx: &App) -> bool;
1160    fn set_leader_id(
1161        &mut self,
1162        leader_peer_id: Option<CollaboratorId>,
1163        window: &mut Window,
1164        cx: &mut Context<Self>,
1165    );
1166    fn dedup(&self, existing: &Self, window: &Window, cx: &App) -> Option<Dedup>;
1167    fn update_agent_location(
1168        &mut self,
1169        _location: language::Anchor,
1170        _window: &mut Window,
1171        _cx: &mut Context<Self>,
1172    ) {
1173    }
1174}
1175
1176pub trait FollowableItemHandle: ItemHandle {
1177    fn remote_id(&self, client: &Arc<Client>, window: &mut Window, cx: &mut App) -> Option<ViewId>;
1178    fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle>;
1179    fn set_leader_id(
1180        &self,
1181        leader_peer_id: Option<CollaboratorId>,
1182        window: &mut Window,
1183        cx: &mut App,
1184    );
1185    fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant>;
1186    fn add_event_to_update_proto(
1187        &self,
1188        event: &dyn Any,
1189        update: &mut Option<proto::update_view::Variant>,
1190        window: &mut Window,
1191        cx: &mut App,
1192    ) -> bool;
1193    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
1194    fn apply_update_proto(
1195        &self,
1196        project: &Entity<Project>,
1197        message: proto::update_view::Variant,
1198        window: &mut Window,
1199        cx: &mut App,
1200    ) -> Task<Result<()>>;
1201    fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool;
1202    fn dedup(
1203        &self,
1204        existing: &dyn FollowableItemHandle,
1205        window: &mut Window,
1206        cx: &mut App,
1207    ) -> Option<Dedup>;
1208    fn update_agent_location(&self, location: language::Anchor, window: &mut Window, cx: &mut App);
1209}
1210
1211impl<T: FollowableItem> FollowableItemHandle for Entity<T> {
1212    fn remote_id(&self, client: &Arc<Client>, _: &mut Window, cx: &mut App) -> Option<ViewId> {
1213        self.read(cx).remote_id().or_else(|| {
1214            client.peer_id().map(|creator| ViewId {
1215                creator: CollaboratorId::PeerId(creator),
1216                id: self.item_id().as_u64(),
1217            })
1218        })
1219    }
1220
1221    fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle> {
1222        Box::new(self.downgrade())
1223    }
1224
1225    fn set_leader_id(&self, leader_id: Option<CollaboratorId>, window: &mut Window, cx: &mut App) {
1226        self.update(cx, |this, cx| this.set_leader_id(leader_id, window, cx))
1227    }
1228
1229    fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant> {
1230        self.read(cx).to_state_proto(window, cx)
1231    }
1232
1233    fn add_event_to_update_proto(
1234        &self,
1235        event: &dyn Any,
1236        update: &mut Option<proto::update_view::Variant>,
1237        window: &mut Window,
1238        cx: &mut App,
1239    ) -> bool {
1240        if let Some(event) = event.downcast_ref() {
1241            self.read(cx)
1242                .add_event_to_update_proto(event, update, window, cx)
1243        } else {
1244            false
1245        }
1246    }
1247
1248    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
1249        T::to_follow_event(event.downcast_ref()?)
1250    }
1251
1252    fn apply_update_proto(
1253        &self,
1254        project: &Entity<Project>,
1255        message: proto::update_view::Variant,
1256        window: &mut Window,
1257        cx: &mut App,
1258    ) -> Task<Result<()>> {
1259        self.update(cx, |this, cx| {
1260            this.apply_update_proto(project, message, window, cx)
1261        })
1262    }
1263
1264    fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool {
1265        self.read(cx).is_project_item(window, cx)
1266    }
1267
1268    fn dedup(
1269        &self,
1270        existing: &dyn FollowableItemHandle,
1271        window: &mut Window,
1272        cx: &mut App,
1273    ) -> Option<Dedup> {
1274        let existing = existing.to_any_view().downcast::<T>().ok()?;
1275        self.read(cx).dedup(existing.read(cx), window, cx)
1276    }
1277
1278    fn update_agent_location(&self, location: language::Anchor, window: &mut Window, cx: &mut App) {
1279        self.update(cx, |this, cx| {
1280            this.update_agent_location(location, window, cx)
1281        })
1282    }
1283}
1284
1285pub trait WeakFollowableItemHandle: Send + Sync {
1286    fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>>;
1287}
1288
1289impl<T: FollowableItem> WeakFollowableItemHandle for WeakEntity<T> {
1290    fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>> {
1291        Some(Box::new(self.upgrade()?))
1292    }
1293}
1294
1295#[cfg(any(test, feature = "test-support"))]
1296pub mod test {
1297    use super::{Item, ItemEvent, SerializableItem, TabContentParams};
1298    use crate::{
1299        ItemId, ItemNavHistory, Workspace, WorkspaceId,
1300        item::{ItemBufferKind, SaveOptions},
1301    };
1302    use gpui::{
1303        AnyElement, App, AppContext as _, Context, Entity, EntityId, EventEmitter, Focusable,
1304        InteractiveElement, IntoElement, Render, SharedString, Task, WeakEntity, Window,
1305    };
1306    use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
1307    use std::{any::Any, cell::Cell};
1308    use util::rel_path::rel_path;
1309
1310    pub struct TestProjectItem {
1311        pub entry_id: Option<ProjectEntryId>,
1312        pub project_path: Option<ProjectPath>,
1313        pub is_dirty: bool,
1314    }
1315
1316    pub struct TestItem {
1317        pub workspace_id: Option<WorkspaceId>,
1318        pub state: String,
1319        pub label: String,
1320        pub save_count: usize,
1321        pub save_as_count: usize,
1322        pub reload_count: usize,
1323        pub is_dirty: bool,
1324        pub buffer_kind: ItemBufferKind,
1325        pub has_conflict: bool,
1326        pub has_deleted_file: bool,
1327        pub project_items: Vec<Entity<TestProjectItem>>,
1328        pub nav_history: Option<ItemNavHistory>,
1329        pub tab_descriptions: Option<Vec<&'static str>>,
1330        pub tab_detail: Cell<Option<usize>>,
1331        serialize: Option<Box<dyn Fn() -> Option<Task<anyhow::Result<()>>>>>,
1332        focus_handle: gpui::FocusHandle,
1333    }
1334
1335    impl project::ProjectItem for TestProjectItem {
1336        fn try_open(
1337            _project: &Entity<Project>,
1338            _path: &ProjectPath,
1339            _cx: &mut App,
1340        ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
1341            None
1342        }
1343        fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
1344            self.entry_id
1345        }
1346
1347        fn project_path(&self, _: &App) -> Option<ProjectPath> {
1348            self.project_path.clone()
1349        }
1350
1351        fn is_dirty(&self) -> bool {
1352            self.is_dirty
1353        }
1354    }
1355
1356    pub enum TestItemEvent {
1357        Edit,
1358    }
1359
1360    impl TestProjectItem {
1361        pub fn new(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1362            let entry_id = Some(ProjectEntryId::from_proto(id));
1363            let project_path = Some(ProjectPath {
1364                worktree_id: WorktreeId::from_usize(0),
1365                path: rel_path(path).into(),
1366            });
1367            cx.new(|_| Self {
1368                entry_id,
1369                project_path,
1370                is_dirty: false,
1371            })
1372        }
1373
1374        pub fn new_untitled(cx: &mut App) -> Entity<Self> {
1375            cx.new(|_| Self {
1376                project_path: None,
1377                entry_id: None,
1378                is_dirty: false,
1379            })
1380        }
1381
1382        pub fn new_dirty(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1383            let entry_id = Some(ProjectEntryId::from_proto(id));
1384            let project_path = Some(ProjectPath {
1385                worktree_id: WorktreeId::from_usize(0),
1386                path: rel_path(path).into(),
1387            });
1388            cx.new(|_| Self {
1389                entry_id,
1390                project_path,
1391                is_dirty: true,
1392            })
1393        }
1394    }
1395
1396    impl TestItem {
1397        pub fn new(cx: &mut Context<Self>) -> Self {
1398            Self {
1399                state: String::new(),
1400                label: String::new(),
1401                save_count: 0,
1402                save_as_count: 0,
1403                reload_count: 0,
1404                is_dirty: false,
1405                has_conflict: false,
1406                has_deleted_file: false,
1407                project_items: Vec::new(),
1408                buffer_kind: ItemBufferKind::Singleton,
1409                nav_history: None,
1410                tab_descriptions: None,
1411                tab_detail: Default::default(),
1412                workspace_id: Default::default(),
1413                focus_handle: cx.focus_handle(),
1414                serialize: None,
1415            }
1416        }
1417
1418        pub fn new_deserialized(id: WorkspaceId, cx: &mut Context<Self>) -> Self {
1419            let mut this = Self::new(cx);
1420            this.workspace_id = Some(id);
1421            this
1422        }
1423
1424        pub fn with_label(mut self, state: &str) -> Self {
1425            self.label = state.to_string();
1426            self
1427        }
1428
1429        pub fn with_buffer_kind(mut self, buffer_kind: ItemBufferKind) -> Self {
1430            self.buffer_kind = buffer_kind;
1431            self
1432        }
1433
1434        pub fn set_has_deleted_file(&mut self, deleted: bool) {
1435            self.has_deleted_file = deleted;
1436        }
1437
1438        pub fn with_dirty(mut self, dirty: bool) -> Self {
1439            self.is_dirty = dirty;
1440            self
1441        }
1442
1443        pub fn with_conflict(mut self, has_conflict: bool) -> Self {
1444            self.has_conflict = has_conflict;
1445            self
1446        }
1447
1448        pub fn with_project_items(mut self, items: &[Entity<TestProjectItem>]) -> Self {
1449            self.project_items.clear();
1450            self.project_items.extend(items.iter().cloned());
1451            self
1452        }
1453
1454        pub fn with_serialize(
1455            mut self,
1456            serialize: impl Fn() -> Option<Task<anyhow::Result<()>>> + 'static,
1457        ) -> Self {
1458            self.serialize = Some(Box::new(serialize));
1459            self
1460        }
1461
1462        pub fn set_state(&mut self, state: String, cx: &mut Context<Self>) {
1463            self.push_to_nav_history(cx);
1464            self.state = state;
1465        }
1466
1467        fn push_to_nav_history(&mut self, cx: &mut Context<Self>) {
1468            if let Some(history) = &mut self.nav_history {
1469                history.push(Some(Box::new(self.state.clone())), cx);
1470            }
1471        }
1472    }
1473
1474    impl Render for TestItem {
1475        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1476            gpui::div().track_focus(&self.focus_handle(cx))
1477        }
1478    }
1479
1480    impl EventEmitter<ItemEvent> for TestItem {}
1481
1482    impl Focusable for TestItem {
1483        fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
1484            self.focus_handle.clone()
1485        }
1486    }
1487
1488    impl Item for TestItem {
1489        type Event = ItemEvent;
1490
1491        fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1492            f(*event)
1493        }
1494
1495        fn tab_content_text(&self, detail: usize, _cx: &App) -> SharedString {
1496            self.tab_descriptions
1497                .as_ref()
1498                .and_then(|descriptions| {
1499                    let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
1500                    description.into()
1501                })
1502                .unwrap_or_default()
1503                .into()
1504        }
1505
1506        fn telemetry_event_text(&self) -> Option<&'static str> {
1507            None
1508        }
1509
1510        fn tab_content(&self, params: TabContentParams, _window: &Window, _cx: &App) -> AnyElement {
1511            self.tab_detail.set(params.detail);
1512            gpui::div().into_any_element()
1513        }
1514
1515        fn for_each_project_item(
1516            &self,
1517            cx: &App,
1518            f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
1519        ) {
1520            self.project_items
1521                .iter()
1522                .for_each(|item| f(item.entity_id(), item.read(cx)))
1523        }
1524
1525        fn buffer_kind(&self, _: &App) -> ItemBufferKind {
1526            self.buffer_kind
1527        }
1528
1529        fn set_nav_history(
1530            &mut self,
1531            history: ItemNavHistory,
1532            _window: &mut Window,
1533            _: &mut Context<Self>,
1534        ) {
1535            self.nav_history = Some(history);
1536        }
1537
1538        fn navigate(
1539            &mut self,
1540            state: Box<dyn Any>,
1541            _window: &mut Window,
1542            _: &mut Context<Self>,
1543        ) -> bool {
1544            let state = *state.downcast::<String>().unwrap_or_default();
1545            if state != self.state {
1546                self.state = state;
1547                true
1548            } else {
1549                false
1550            }
1551        }
1552
1553        fn deactivated(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1554            self.push_to_nav_history(cx);
1555        }
1556
1557        fn can_split(&self) -> bool {
1558            true
1559        }
1560
1561        fn clone_on_split(
1562            &self,
1563            _workspace_id: Option<WorkspaceId>,
1564            _: &mut Window,
1565            cx: &mut Context<Self>,
1566        ) -> Task<Option<Entity<Self>>>
1567        where
1568            Self: Sized,
1569        {
1570            Task::ready(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}