item.rs

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