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