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