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