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