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