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