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