item.rs

   1use crate::{
   2    pane::{self, Pane},
   3    persistence::model::ItemId,
   4    searchable::SearchableItemHandle,
   5    workspace_settings::{AutosaveSetting, WorkspaceSettings},
   6    DelayedDebouncedEditAction, FollowableViewRegistry, ItemNavHistory, SerializableItemRegistry,
   7    ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
   8};
   9use anyhow::Result;
  10use client::{
  11    proto::{self, PeerId},
  12    Client,
  13};
  14use futures::{channel::mpsc, StreamExt};
  15use gpui::{
  16    AnyElement, AnyView, AppContext, Entity, EntityId, EventEmitter, FocusHandle, FocusableView,
  17    Font, HighlightStyle, Model, Pixels, Point, SharedString, Task, View, ViewContext, WeakView,
  18    WindowContext,
  19};
  20use project::{Project, ProjectEntryId, ProjectPath};
  21use schemars::JsonSchema;
  22use serde::{Deserialize, Serialize};
  23use settings::{Settings, SettingsLocation, SettingsSources};
  24use smallvec::SmallVec;
  25use std::{
  26    any::{Any, TypeId},
  27    cell::RefCell,
  28    ops::Range,
  29    rc::Rc,
  30    sync::Arc,
  31    time::Duration,
  32};
  33use theme::Theme;
  34use ui::{Color, Element as _, Icon, IntoElement, Label, LabelCommon};
  35use util::ResultExt;
  36
  37pub const LEADER_UPDATE_THROTTLE: Duration = Duration::from_millis(200);
  38
  39#[derive(Deserialize)]
  40pub struct ItemSettings {
  41    pub git_status: bool,
  42    pub close_position: ClosePosition,
  43    pub file_icons: bool,
  44}
  45
  46#[derive(Deserialize)]
  47pub struct PreviewTabsSettings {
  48    pub enabled: bool,
  49    pub enable_preview_from_file_finder: bool,
  50    pub enable_preview_from_code_navigation: bool,
  51}
  52
  53#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  54#[serde(rename_all = "lowercase")]
  55pub enum ClosePosition {
  56    Left,
  57    #[default]
  58    Right,
  59}
  60
  61impl ClosePosition {
  62    pub fn right(&self) -> bool {
  63        match self {
  64            ClosePosition::Left => false,
  65            ClosePosition::Right => true,
  66        }
  67    }
  68}
  69
  70#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  71pub struct ItemSettingsContent {
  72    /// Whether to show the Git file status on a tab item.
  73    ///
  74    /// Default: false
  75    git_status: Option<bool>,
  76    /// Position of the close button in a tab.
  77    ///
  78    /// Default: right
  79    close_position: Option<ClosePosition>,
  80    /// Whether to show the file icon for a tab.
  81    ///
  82    /// Default: true
  83    file_icons: Option<bool>,
  84}
  85
  86#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
  87pub struct PreviewTabsSettingsContent {
  88    /// Whether to show opened editors as preview tabs.
  89    /// Preview tabs do not stay open, are reused until explicitly set to be kept open opened (via double-click or editing) and show file names in italic.
  90    ///
  91    /// Default: true
  92    enabled: Option<bool>,
  93    /// Whether to open tabs in preview mode when selected from the file finder.
  94    ///
  95    /// Default: false
  96    enable_preview_from_file_finder: Option<bool>,
  97    /// Whether a preview tab gets replaced when code navigation is used to navigate away from the tab.
  98    ///
  99    /// Default: false
 100    enable_preview_from_code_navigation: Option<bool>,
 101}
 102
 103impl Settings for ItemSettings {
 104    const KEY: Option<&'static str> = Some("tabs");
 105
 106    type FileContent = ItemSettingsContent;
 107
 108    fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
 109        sources.json_merge()
 110    }
 111}
 112
 113impl Settings for PreviewTabsSettings {
 114    const KEY: Option<&'static str> = Some("preview_tabs");
 115
 116    type FileContent = PreviewTabsSettingsContent;
 117
 118    fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
 119        sources.json_merge()
 120    }
 121}
 122
 123#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
 124pub enum ItemEvent {
 125    CloseItem,
 126    UpdateTab,
 127    UpdateBreadcrumbs,
 128    Edit,
 129}
 130
 131// TODO: Combine this with existing HighlightedText struct?
 132pub struct BreadcrumbText {
 133    pub text: String,
 134    pub highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
 135    pub font: Option<Font>,
 136}
 137
 138#[derive(Debug, Clone, Copy)]
 139pub struct TabContentParams {
 140    pub detail: Option<usize>,
 141    pub selected: bool,
 142    pub preview: bool,
 143}
 144
 145impl TabContentParams {
 146    /// Returns the text color to be used for the tab content.
 147    pub fn text_color(&self) -> Color {
 148        if self.selected {
 149            Color::Default
 150        } else {
 151            Color::Muted
 152        }
 153    }
 154}
 155
 156pub trait Item: FocusableView + EventEmitter<Self::Event> {
 157    type Event;
 158
 159    /// Returns the tab contents.
 160    ///
 161    /// By default this returns a [`Label`] that displays that text from
 162    /// `tab_content_text`.
 163    fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
 164        let Some(text) = self.tab_content_text(cx) else {
 165            return gpui::Empty.into_any();
 166        };
 167
 168        Label::new(text)
 169            .color(params.text_color())
 170            .into_any_element()
 171    }
 172
 173    /// Returns the textual contents of the tab.
 174    ///
 175    /// Use this if you don't need to customize the tab contents.
 176    fn tab_content_text(&self, _cx: &WindowContext) -> Option<SharedString> {
 177        None
 178    }
 179
 180    fn tab_icon(&self, _cx: &WindowContext) -> Option<Icon> {
 181        None
 182    }
 183
 184    fn to_item_events(_event: &Self::Event, _f: impl FnMut(ItemEvent)) {}
 185
 186    fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
 187    fn workspace_deactivated(&mut self, _: &mut ViewContext<Self>) {}
 188    fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
 189        false
 190    }
 191    fn tab_tooltip_text(&self, _: &AppContext) -> Option<SharedString> {
 192        None
 193    }
 194    fn tab_description(&self, _: usize, _: &AppContext) -> Option<SharedString> {
 195        None
 196    }
 197
 198    fn telemetry_event_text(&self) -> Option<&'static str> {
 199        None
 200    }
 201
 202    /// (model id, Item)
 203    fn for_each_project_item(
 204        &self,
 205        _: &AppContext,
 206        _: &mut dyn FnMut(EntityId, &dyn project::Item),
 207    ) {
 208    }
 209    fn is_singleton(&self, _cx: &AppContext) -> bool {
 210        false
 211    }
 212    fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>) {}
 213    fn clone_on_split(
 214        &self,
 215        _workspace_id: Option<WorkspaceId>,
 216        _: &mut ViewContext<Self>,
 217    ) -> Option<View<Self>>
 218    where
 219        Self: Sized,
 220    {
 221        None
 222    }
 223    fn is_dirty(&self, _: &AppContext) -> bool {
 224        false
 225    }
 226    fn has_conflict(&self, _: &AppContext) -> bool {
 227        false
 228    }
 229    fn can_save(&self, _cx: &AppContext) -> bool {
 230        false
 231    }
 232    fn save(
 233        &mut self,
 234        _format: bool,
 235        _project: Model<Project>,
 236        _cx: &mut ViewContext<Self>,
 237    ) -> Task<Result<()>> {
 238        unimplemented!("save() must be implemented if can_save() returns true")
 239    }
 240    fn save_as(
 241        &mut self,
 242        _project: Model<Project>,
 243        _path: ProjectPath,
 244        _cx: &mut ViewContext<Self>,
 245    ) -> Task<Result<()>> {
 246        unimplemented!("save_as() must be implemented if can_save() returns true")
 247    }
 248    fn reload(
 249        &mut self,
 250        _project: Model<Project>,
 251        _cx: &mut ViewContext<Self>,
 252    ) -> Task<Result<()>> {
 253        unimplemented!("reload() must be implemented if can_save() returns true")
 254    }
 255
 256    fn act_as_type<'a>(
 257        &'a self,
 258        type_id: TypeId,
 259        self_handle: &'a View<Self>,
 260        _: &'a AppContext,
 261    ) -> Option<AnyView> {
 262        if TypeId::of::<Self>() == type_id {
 263            Some(self_handle.clone().into())
 264        } else {
 265            None
 266        }
 267    }
 268
 269    fn as_searchable(&self, _: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 270        None
 271    }
 272
 273    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 274        ToolbarItemLocation::Hidden
 275    }
 276
 277    fn breadcrumbs(&self, _theme: &Theme, _cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 278        None
 279    }
 280
 281    fn added_to_workspace(&mut self, _workspace: &mut Workspace, _cx: &mut ViewContext<Self>) {}
 282
 283    fn show_toolbar(&self) -> bool {
 284        true
 285    }
 286
 287    fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<Point<Pixels>> {
 288        None
 289    }
 290
 291    fn preserve_preview(&self, _cx: &AppContext) -> bool {
 292        false
 293    }
 294}
 295
 296pub trait SerializableItem: Item {
 297    fn serialized_item_kind() -> &'static str;
 298
 299    fn cleanup(
 300        workspace_id: WorkspaceId,
 301        alive_items: Vec<ItemId>,
 302        cx: &mut WindowContext,
 303    ) -> Task<Result<()>>;
 304
 305    fn deserialize(
 306        _project: Model<Project>,
 307        _workspace: WeakView<Workspace>,
 308        _workspace_id: WorkspaceId,
 309        _item_id: ItemId,
 310        _cx: &mut ViewContext<Pane>,
 311    ) -> Task<Result<View<Self>>>;
 312
 313    fn serialize(
 314        &mut self,
 315        workspace: &mut Workspace,
 316        item_id: ItemId,
 317        closing: bool,
 318        cx: &mut ViewContext<Self>,
 319    ) -> Option<Task<Result<()>>>;
 320
 321    fn should_serialize(&self, event: &Self::Event) -> bool;
 322}
 323
 324pub trait SerializableItemHandle: ItemHandle {
 325    fn serialized_item_kind(&self) -> &'static str;
 326    fn serialize(
 327        &self,
 328        workspace: &mut Workspace,
 329        closing: bool,
 330        cx: &mut WindowContext,
 331    ) -> Option<Task<Result<()>>>;
 332    fn should_serialize(&self, event: &dyn Any, cx: &AppContext) -> bool;
 333}
 334
 335impl<T> SerializableItemHandle for View<T>
 336where
 337    T: SerializableItem,
 338{
 339    fn serialized_item_kind(&self) -> &'static str {
 340        T::serialized_item_kind()
 341    }
 342
 343    fn serialize(
 344        &self,
 345        workspace: &mut Workspace,
 346        closing: bool,
 347        cx: &mut WindowContext,
 348    ) -> Option<Task<Result<()>>> {
 349        self.update(cx, |this, cx| {
 350            this.serialize(workspace, cx.entity_id().as_u64(), closing, cx)
 351        })
 352    }
 353
 354    fn should_serialize(&self, event: &dyn Any, cx: &AppContext) -> bool {
 355        event
 356            .downcast_ref::<T::Event>()
 357            .map_or(false, |event| self.read(cx).should_serialize(event))
 358    }
 359}
 360
 361pub trait ItemHandle: 'static + Send {
 362    fn subscribe_to_item_events(
 363        &self,
 364        cx: &mut WindowContext,
 365        handler: Box<dyn Fn(ItemEvent, &mut WindowContext)>,
 366    ) -> gpui::Subscription;
 367    fn focus_handle(&self, cx: &WindowContext) -> FocusHandle;
 368    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString>;
 369    fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString>;
 370    fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement;
 371    fn tab_icon(&self, cx: &WindowContext) -> Option<Icon>;
 372    fn telemetry_event_text(&self, cx: &WindowContext) -> Option<&'static str>;
 373    fn dragged_tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement;
 374    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 375    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;
 376    fn project_item_model_ids(&self, cx: &AppContext) -> SmallVec<[EntityId; 3]>;
 377    fn for_each_project_item(
 378        &self,
 379        _: &AppContext,
 380        _: &mut dyn FnMut(EntityId, &dyn project::Item),
 381    );
 382    fn is_singleton(&self, cx: &AppContext) -> bool;
 383    fn boxed_clone(&self) -> Box<dyn ItemHandle>;
 384    fn clone_on_split(
 385        &self,
 386        workspace_id: Option<WorkspaceId>,
 387        cx: &mut WindowContext,
 388    ) -> Option<Box<dyn ItemHandle>>;
 389    fn added_to_pane(
 390        &self,
 391        workspace: &mut Workspace,
 392        pane: View<Pane>,
 393        cx: &mut ViewContext<Workspace>,
 394    );
 395    fn deactivated(&self, cx: &mut WindowContext);
 396    fn workspace_deactivated(&self, cx: &mut WindowContext);
 397    fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool;
 398    fn item_id(&self) -> EntityId;
 399    fn to_any(&self) -> AnyView;
 400    fn is_dirty(&self, cx: &AppContext) -> bool;
 401    fn has_conflict(&self, cx: &AppContext) -> bool;
 402    fn can_save(&self, cx: &AppContext) -> bool;
 403    fn save(
 404        &self,
 405        format: bool,
 406        project: Model<Project>,
 407        cx: &mut WindowContext,
 408    ) -> Task<Result<()>>;
 409    fn save_as(
 410        &self,
 411        project: Model<Project>,
 412        path: ProjectPath,
 413        cx: &mut WindowContext,
 414    ) -> Task<Result<()>>;
 415    fn reload(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>>;
 416    fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyView>;
 417    fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
 418    fn to_serializable_item_handle(
 419        &self,
 420        cx: &AppContext,
 421    ) -> Option<Box<dyn SerializableItemHandle>>;
 422    fn on_release(
 423        &self,
 424        cx: &mut AppContext,
 425        callback: Box<dyn FnOnce(&mut AppContext) + Send>,
 426    ) -> gpui::Subscription;
 427    fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>>;
 428    fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation;
 429    fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>>;
 430    fn show_toolbar(&self, cx: &AppContext) -> bool;
 431    fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Point<Pixels>>;
 432    fn downgrade_item(&self) -> Box<dyn WeakItemHandle>;
 433    fn workspace_settings<'a>(&self, cx: &'a AppContext) -> &'a WorkspaceSettings;
 434    fn preserve_preview(&self, cx: &AppContext) -> bool;
 435}
 436
 437pub trait WeakItemHandle: Send + Sync {
 438    fn id(&self) -> EntityId;
 439    fn boxed_clone(&self) -> Box<dyn WeakItemHandle>;
 440    fn upgrade(&self) -> Option<Box<dyn ItemHandle>>;
 441}
 442
 443impl dyn ItemHandle {
 444    pub fn downcast<V: 'static>(&self) -> Option<View<V>> {
 445        self.to_any().downcast().ok()
 446    }
 447
 448    pub fn act_as<V: 'static>(&self, cx: &AppContext) -> Option<View<V>> {
 449        self.act_as_type(TypeId::of::<V>(), cx)
 450            .and_then(|t| t.downcast().ok())
 451    }
 452}
 453
 454impl<T: Item> ItemHandle for View<T> {
 455    fn subscribe_to_item_events(
 456        &self,
 457        cx: &mut WindowContext,
 458        handler: Box<dyn Fn(ItemEvent, &mut WindowContext)>,
 459    ) -> gpui::Subscription {
 460        cx.subscribe(self, move |_, event, cx| {
 461            T::to_item_events(event, |item_event| handler(item_event, cx));
 462        })
 463    }
 464
 465    fn focus_handle(&self, cx: &WindowContext) -> FocusHandle {
 466        self.focus_handle(cx)
 467    }
 468
 469    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
 470        self.read(cx).tab_tooltip_text(cx)
 471    }
 472
 473    fn telemetry_event_text(&self, cx: &WindowContext) -> Option<&'static str> {
 474        self.read(cx).telemetry_event_text()
 475    }
 476
 477    fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString> {
 478        self.read(cx).tab_description(detail, cx)
 479    }
 480
 481    fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
 482        self.read(cx).tab_content(params, cx)
 483    }
 484
 485    fn tab_icon(&self, cx: &WindowContext) -> Option<Icon> {
 486        self.read(cx).tab_icon(cx)
 487    }
 488
 489    fn dragged_tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
 490        self.read(cx).tab_content(
 491            TabContentParams {
 492                selected: true,
 493                ..params
 494            },
 495            cx,
 496        )
 497    }
 498
 499    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
 500        let this = self.read(cx);
 501        let mut result = None;
 502        if this.is_singleton(cx) {
 503            this.for_each_project_item(cx, &mut |_, item| {
 504                result = item.project_path(cx);
 505            });
 506        }
 507        result
 508    }
 509
 510    fn workspace_settings<'a>(&self, cx: &'a AppContext) -> &'a WorkspaceSettings {
 511        if let Some(project_path) = self.project_path(cx) {
 512            WorkspaceSettings::get(
 513                Some(SettingsLocation {
 514                    worktree_id: project_path.worktree_id.into(),
 515                    path: &project_path.path,
 516                }),
 517                cx,
 518            )
 519        } else {
 520            WorkspaceSettings::get_global(cx)
 521        }
 522    }
 523
 524    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
 525        let mut result = SmallVec::new();
 526        self.read(cx).for_each_project_item(cx, &mut |_, item| {
 527            if let Some(id) = item.entry_id(cx) {
 528                result.push(id);
 529            }
 530        });
 531        result
 532    }
 533
 534    fn project_item_model_ids(&self, cx: &AppContext) -> SmallVec<[EntityId; 3]> {
 535        let mut result = SmallVec::new();
 536        self.read(cx).for_each_project_item(cx, &mut |id, _| {
 537            result.push(id);
 538        });
 539        result
 540    }
 541
 542    fn for_each_project_item(
 543        &self,
 544        cx: &AppContext,
 545        f: &mut dyn FnMut(EntityId, &dyn project::Item),
 546    ) {
 547        self.read(cx).for_each_project_item(cx, f)
 548    }
 549
 550    fn is_singleton(&self, cx: &AppContext) -> bool {
 551        self.read(cx).is_singleton(cx)
 552    }
 553
 554    fn boxed_clone(&self) -> Box<dyn ItemHandle> {
 555        Box::new(self.clone())
 556    }
 557
 558    fn clone_on_split(
 559        &self,
 560        workspace_id: Option<WorkspaceId>,
 561        cx: &mut WindowContext,
 562    ) -> Option<Box<dyn ItemHandle>> {
 563        self.update(cx, |item, cx| item.clone_on_split(workspace_id, cx))
 564            .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
 565    }
 566
 567    fn added_to_pane(
 568        &self,
 569        workspace: &mut Workspace,
 570        pane: View<Pane>,
 571        cx: &mut ViewContext<Workspace>,
 572    ) {
 573        let weak_item = self.downgrade();
 574        let history = pane.read(cx).nav_history_for_item(self);
 575        self.update(cx, |this, cx| {
 576            this.set_nav_history(history, cx);
 577            this.added_to_workspace(workspace, cx);
 578        });
 579
 580        if let Some(serializable_item) = self.to_serializable_item_handle(cx) {
 581            workspace
 582                .enqueue_item_serialization(serializable_item)
 583                .log_err();
 584        }
 585
 586        if workspace
 587            .panes_by_item
 588            .insert(self.item_id(), pane.downgrade())
 589            .is_none()
 590        {
 591            let mut pending_autosave = DelayedDebouncedEditAction::new();
 592            let (pending_update_tx, mut pending_update_rx) = mpsc::unbounded();
 593            let pending_update = Rc::new(RefCell::new(None));
 594
 595            let mut send_follower_updates = None;
 596            if let Some(item) = self.to_followable_item_handle(cx) {
 597                let is_project_item = item.is_project_item(cx);
 598                let item = item.downgrade();
 599
 600                send_follower_updates = Some(cx.spawn({
 601                    let pending_update = pending_update.clone();
 602                    |workspace, mut cx| async move {
 603                        while let Some(mut leader_id) = pending_update_rx.next().await {
 604                            while let Ok(Some(id)) = pending_update_rx.try_next() {
 605                                leader_id = id;
 606                            }
 607
 608                            workspace.update(&mut cx, |workspace, cx| {
 609                                let Some(item) = item.upgrade() else { return };
 610                                workspace.update_followers(
 611                                    is_project_item,
 612                                    proto::update_followers::Variant::UpdateView(
 613                                        proto::UpdateView {
 614                                            id: item
 615                                                .remote_id(workspace.client(), cx)
 616                                                .map(|id| id.to_proto()),
 617                                            variant: pending_update.borrow_mut().take(),
 618                                            leader_id,
 619                                        },
 620                                    ),
 621                                    cx,
 622                                );
 623                            })?;
 624                            cx.background_executor().timer(LEADER_UPDATE_THROTTLE).await;
 625                        }
 626                        anyhow::Ok(())
 627                    }
 628                }));
 629            }
 630
 631            let mut event_subscription = Some(cx.subscribe(
 632                self,
 633                move |workspace, item: View<T>, event, cx| {
 634                    let pane = if let Some(pane) = workspace
 635                        .panes_by_item
 636                        .get(&item.item_id())
 637                        .and_then(|pane| pane.upgrade())
 638                    {
 639                        pane
 640                    } else {
 641                        return;
 642                    };
 643
 644                    if let Some(item) = item.to_followable_item_handle(cx) {
 645                        let leader_id = workspace.leader_for_pane(&pane);
 646
 647                        if let Some(leader_id) = leader_id {
 648                            if let Some(FollowEvent::Unfollow) = item.to_follow_event(event) {
 649                                workspace.unfollow(leader_id, cx);
 650                            }
 651                        }
 652
 653                        if item.focus_handle(cx).contains_focused(cx) {
 654                            item.add_event_to_update_proto(
 655                                event,
 656                                &mut pending_update.borrow_mut(),
 657                                cx,
 658                            );
 659                            pending_update_tx.unbounded_send(leader_id).ok();
 660                        }
 661                    }
 662
 663                    if let Some(item) = item.to_serializable_item_handle(cx) {
 664                        if item.should_serialize(event, cx) {
 665                            workspace.enqueue_item_serialization(item).ok();
 666                        }
 667                    }
 668
 669                    T::to_item_events(event, |event| match event {
 670                        ItemEvent::CloseItem => {
 671                            pane.update(cx, |pane, cx| {
 672                                pane.close_item_by_id(item.item_id(), crate::SaveIntent::Close, cx)
 673                            })
 674                            .detach_and_log_err(cx);
 675                            return;
 676                        }
 677
 678                        ItemEvent::UpdateTab => {
 679                            pane.update(cx, |_, cx| {
 680                                cx.emit(pane::Event::ChangeItemTitle);
 681                                cx.notify();
 682                            });
 683                        }
 684
 685                        ItemEvent::Edit => {
 686                            let autosave = item.workspace_settings(cx).autosave;
 687
 688                            if let AutosaveSetting::AfterDelay { milliseconds } = autosave {
 689                                let delay = Duration::from_millis(milliseconds);
 690                                let item = item.clone();
 691                                pending_autosave.fire_new(delay, cx, move |workspace, cx| {
 692                                    Pane::autosave_item(&item, workspace.project().clone(), cx)
 693                                });
 694                            }
 695                            pane.update(cx, |pane, cx| pane.handle_item_edit(item.item_id(), cx));
 696                        }
 697
 698                        _ => {}
 699                    });
 700                },
 701            ));
 702
 703            cx.on_blur(&self.focus_handle(cx), move |workspace, cx| {
 704                if let Some(item) = weak_item.upgrade() {
 705                    if item.workspace_settings(cx).autosave == AutosaveSetting::OnFocusChange {
 706                        Pane::autosave_item(&item, workspace.project.clone(), cx)
 707                            .detach_and_log_err(cx);
 708                    }
 709                }
 710            })
 711            .detach();
 712
 713            let item_id = self.item_id();
 714            cx.observe_release(self, move |workspace, _, _| {
 715                workspace.panes_by_item.remove(&item_id);
 716                event_subscription.take();
 717                send_follower_updates.take();
 718            })
 719            .detach();
 720        }
 721
 722        cx.defer(|workspace, cx| {
 723            workspace.serialize_workspace(cx);
 724        });
 725    }
 726
 727    fn deactivated(&self, cx: &mut WindowContext) {
 728        self.update(cx, |this, cx| this.deactivated(cx));
 729    }
 730
 731    fn workspace_deactivated(&self, cx: &mut WindowContext) {
 732        self.update(cx, |this, cx| this.workspace_deactivated(cx));
 733    }
 734
 735    fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool {
 736        self.update(cx, |this, cx| this.navigate(data, cx))
 737    }
 738
 739    fn item_id(&self) -> EntityId {
 740        self.entity_id()
 741    }
 742
 743    fn to_any(&self) -> AnyView {
 744        self.clone().into()
 745    }
 746
 747    fn is_dirty(&self, cx: &AppContext) -> bool {
 748        self.read(cx).is_dirty(cx)
 749    }
 750
 751    fn has_conflict(&self, cx: &AppContext) -> bool {
 752        self.read(cx).has_conflict(cx)
 753    }
 754
 755    fn can_save(&self, cx: &AppContext) -> bool {
 756        self.read(cx).can_save(cx)
 757    }
 758
 759    fn save(
 760        &self,
 761        format: bool,
 762        project: Model<Project>,
 763        cx: &mut WindowContext,
 764    ) -> Task<Result<()>> {
 765        self.update(cx, |item, cx| item.save(format, project, cx))
 766    }
 767
 768    fn save_as(
 769        &self,
 770        project: Model<Project>,
 771        path: ProjectPath,
 772        cx: &mut WindowContext,
 773    ) -> Task<anyhow::Result<()>> {
 774        self.update(cx, |item, cx| item.save_as(project, path, cx))
 775    }
 776
 777    fn reload(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
 778        self.update(cx, |item, cx| item.reload(project, cx))
 779    }
 780
 781    fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a AppContext) -> Option<AnyView> {
 782        self.read(cx).act_as_type(type_id, self, cx)
 783    }
 784
 785    fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
 786        FollowableViewRegistry::to_followable_view(self.clone(), cx)
 787    }
 788
 789    fn on_release(
 790        &self,
 791        cx: &mut AppContext,
 792        callback: Box<dyn FnOnce(&mut AppContext) + Send>,
 793    ) -> gpui::Subscription {
 794        cx.observe_release(self, move |_, cx| callback(cx))
 795    }
 796
 797    fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {
 798        self.read(cx).as_searchable(self)
 799    }
 800
 801    fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {
 802        self.read(cx).breadcrumb_location()
 803    }
 804
 805    fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 806        self.read(cx).breadcrumbs(theme, cx)
 807    }
 808
 809    fn show_toolbar(&self, cx: &AppContext) -> bool {
 810        self.read(cx).show_toolbar()
 811    }
 812
 813    fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Point<Pixels>> {
 814        self.read(cx).pixel_position_of_cursor(cx)
 815    }
 816
 817    fn downgrade_item(&self) -> Box<dyn WeakItemHandle> {
 818        Box::new(self.downgrade())
 819    }
 820
 821    fn to_serializable_item_handle(
 822        &self,
 823        cx: &AppContext,
 824    ) -> Option<Box<dyn SerializableItemHandle>> {
 825        SerializableItemRegistry::view_to_serializable_item_handle(self.to_any(), cx)
 826    }
 827
 828    fn preserve_preview(&self, cx: &AppContext) -> bool {
 829        self.read(cx).preserve_preview(cx)
 830    }
 831}
 832
 833impl From<Box<dyn ItemHandle>> for AnyView {
 834    fn from(val: Box<dyn ItemHandle>) -> Self {
 835        val.to_any()
 836    }
 837}
 838
 839impl From<&Box<dyn ItemHandle>> for AnyView {
 840    fn from(val: &Box<dyn ItemHandle>) -> Self {
 841        val.to_any()
 842    }
 843}
 844
 845impl Clone for Box<dyn ItemHandle> {
 846    fn clone(&self) -> Box<dyn ItemHandle> {
 847        self.boxed_clone()
 848    }
 849}
 850
 851impl<T: Item> WeakItemHandle for WeakView<T> {
 852    fn id(&self) -> EntityId {
 853        self.entity_id()
 854    }
 855
 856    fn boxed_clone(&self) -> Box<dyn WeakItemHandle> {
 857        Box::new(self.clone())
 858    }
 859
 860    fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
 861        self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
 862    }
 863}
 864
 865pub trait ProjectItem: Item {
 866    type Item: project::Item;
 867
 868    fn for_project_item(
 869        project: Model<Project>,
 870        item: Model<Self::Item>,
 871        cx: &mut ViewContext<Self>,
 872    ) -> Self
 873    where
 874        Self: Sized;
 875}
 876
 877#[derive(Debug)]
 878pub enum FollowEvent {
 879    Unfollow,
 880}
 881
 882pub enum Dedup {
 883    KeepExisting,
 884    ReplaceExisting,
 885}
 886
 887pub trait FollowableItem: Item {
 888    fn remote_id(&self) -> Option<ViewId>;
 889    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant>;
 890    fn from_state_proto(
 891        project: View<Workspace>,
 892        id: ViewId,
 893        state: &mut Option<proto::view::Variant>,
 894        cx: &mut WindowContext,
 895    ) -> Option<Task<Result<View<Self>>>>;
 896    fn to_follow_event(event: &Self::Event) -> Option<FollowEvent>;
 897    fn add_event_to_update_proto(
 898        &self,
 899        event: &Self::Event,
 900        update: &mut Option<proto::update_view::Variant>,
 901        cx: &WindowContext,
 902    ) -> bool;
 903    fn apply_update_proto(
 904        &mut self,
 905        project: &Model<Project>,
 906        message: proto::update_view::Variant,
 907        cx: &mut ViewContext<Self>,
 908    ) -> Task<Result<()>>;
 909    fn is_project_item(&self, cx: &WindowContext) -> bool;
 910    fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>);
 911    fn dedup(&self, existing: &Self, cx: &WindowContext) -> Option<Dedup>;
 912}
 913
 914pub trait FollowableItemHandle: ItemHandle {
 915    fn remote_id(&self, client: &Arc<Client>, cx: &WindowContext) -> Option<ViewId>;
 916    fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle>;
 917    fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext);
 918    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant>;
 919    fn add_event_to_update_proto(
 920        &self,
 921        event: &dyn Any,
 922        update: &mut Option<proto::update_view::Variant>,
 923        cx: &WindowContext,
 924    ) -> bool;
 925    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
 926    fn apply_update_proto(
 927        &self,
 928        project: &Model<Project>,
 929        message: proto::update_view::Variant,
 930        cx: &mut WindowContext,
 931    ) -> Task<Result<()>>;
 932    fn is_project_item(&self, cx: &WindowContext) -> bool;
 933    fn dedup(&self, existing: &dyn FollowableItemHandle, cx: &WindowContext) -> Option<Dedup>;
 934}
 935
 936impl<T: FollowableItem> FollowableItemHandle for View<T> {
 937    fn remote_id(&self, client: &Arc<Client>, cx: &WindowContext) -> Option<ViewId> {
 938        self.read(cx).remote_id().or_else(|| {
 939            client.peer_id().map(|creator| ViewId {
 940                creator,
 941                id: self.item_id().as_u64(),
 942            })
 943        })
 944    }
 945
 946    fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle> {
 947        Box::new(self.downgrade())
 948    }
 949
 950    fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext) {
 951        self.update(cx, |this, cx| this.set_leader_peer_id(leader_peer_id, cx))
 952    }
 953
 954    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
 955        self.read(cx).to_state_proto(cx)
 956    }
 957
 958    fn add_event_to_update_proto(
 959        &self,
 960        event: &dyn Any,
 961        update: &mut Option<proto::update_view::Variant>,
 962        cx: &WindowContext,
 963    ) -> bool {
 964        if let Some(event) = event.downcast_ref() {
 965            self.read(cx).add_event_to_update_proto(event, update, cx)
 966        } else {
 967            false
 968        }
 969    }
 970
 971    fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
 972        T::to_follow_event(event.downcast_ref()?)
 973    }
 974
 975    fn apply_update_proto(
 976        &self,
 977        project: &Model<Project>,
 978        message: proto::update_view::Variant,
 979        cx: &mut WindowContext,
 980    ) -> Task<Result<()>> {
 981        self.update(cx, |this, cx| this.apply_update_proto(project, message, cx))
 982    }
 983
 984    fn is_project_item(&self, cx: &WindowContext) -> bool {
 985        self.read(cx).is_project_item(cx)
 986    }
 987
 988    fn dedup(&self, existing: &dyn FollowableItemHandle, cx: &WindowContext) -> Option<Dedup> {
 989        let existing = existing.to_any().downcast::<T>().ok()?;
 990        self.read(cx).dedup(existing.read(cx), cx)
 991    }
 992}
 993
 994pub trait WeakFollowableItemHandle: Send + Sync {
 995    fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>>;
 996}
 997
 998impl<T: FollowableItem> WeakFollowableItemHandle for WeakView<T> {
 999    fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>> {
1000        Some(Box::new(self.upgrade()?))
1001    }
1002}
1003
1004#[cfg(any(test, feature = "test-support"))]
1005pub mod test {
1006    use super::{Item, ItemEvent, SerializableItem, TabContentParams};
1007    use crate::{ItemId, ItemNavHistory, Pane, Workspace, WorkspaceId};
1008    use gpui::{
1009        AnyElement, AppContext, Context as _, EntityId, EventEmitter, FocusableView,
1010        InteractiveElement, IntoElement, Model, Render, SharedString, Task, View, ViewContext,
1011        VisualContext, WeakView,
1012    };
1013    use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
1014    use std::{any::Any, cell::Cell, path::Path};
1015
1016    pub struct TestProjectItem {
1017        pub entry_id: Option<ProjectEntryId>,
1018        pub project_path: Option<ProjectPath>,
1019    }
1020
1021    pub struct TestItem {
1022        pub workspace_id: Option<WorkspaceId>,
1023        pub state: String,
1024        pub label: String,
1025        pub save_count: usize,
1026        pub save_as_count: usize,
1027        pub reload_count: usize,
1028        pub is_dirty: bool,
1029        pub is_singleton: bool,
1030        pub has_conflict: bool,
1031        pub project_items: Vec<Model<TestProjectItem>>,
1032        pub nav_history: Option<ItemNavHistory>,
1033        pub tab_descriptions: Option<Vec<&'static str>>,
1034        pub tab_detail: Cell<Option<usize>>,
1035        serialize: Option<Box<dyn Fn() -> Option<Task<anyhow::Result<()>>>>>,
1036        focus_handle: gpui::FocusHandle,
1037    }
1038
1039    impl project::Item for TestProjectItem {
1040        fn try_open(
1041            _project: &Model<Project>,
1042            _path: &ProjectPath,
1043            _cx: &mut AppContext,
1044        ) -> Option<Task<gpui::Result<Model<Self>>>> {
1045            None
1046        }
1047
1048        fn entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
1049            self.entry_id
1050        }
1051
1052        fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
1053            self.project_path.clone()
1054        }
1055    }
1056
1057    pub enum TestItemEvent {
1058        Edit,
1059    }
1060
1061    impl TestProjectItem {
1062        pub fn new(id: u64, path: &str, cx: &mut AppContext) -> Model<Self> {
1063            let entry_id = Some(ProjectEntryId::from_proto(id));
1064            let project_path = Some(ProjectPath {
1065                worktree_id: WorktreeId::from_usize(0),
1066                path: Path::new(path).into(),
1067            });
1068            cx.new_model(|_| Self {
1069                entry_id,
1070                project_path,
1071            })
1072        }
1073
1074        pub fn new_untitled(cx: &mut AppContext) -> Model<Self> {
1075            cx.new_model(|_| Self {
1076                project_path: None,
1077                entry_id: None,
1078            })
1079        }
1080    }
1081
1082    impl TestItem {
1083        pub fn new(cx: &mut ViewContext<Self>) -> Self {
1084            Self {
1085                state: String::new(),
1086                label: String::new(),
1087                save_count: 0,
1088                save_as_count: 0,
1089                reload_count: 0,
1090                is_dirty: false,
1091                has_conflict: false,
1092                project_items: Vec::new(),
1093                is_singleton: true,
1094                nav_history: None,
1095                tab_descriptions: None,
1096                tab_detail: Default::default(),
1097                workspace_id: Default::default(),
1098                focus_handle: cx.focus_handle(),
1099                serialize: None,
1100            }
1101        }
1102
1103        pub fn new_deserialized(id: WorkspaceId, cx: &mut ViewContext<Self>) -> Self {
1104            let mut this = Self::new(cx);
1105            this.workspace_id = Some(id);
1106            this
1107        }
1108
1109        pub fn with_label(mut self, state: &str) -> Self {
1110            self.label = state.to_string();
1111            self
1112        }
1113
1114        pub fn with_singleton(mut self, singleton: bool) -> Self {
1115            self.is_singleton = singleton;
1116            self
1117        }
1118
1119        pub fn with_dirty(mut self, dirty: bool) -> Self {
1120            self.is_dirty = dirty;
1121            self
1122        }
1123
1124        pub fn with_conflict(mut self, has_conflict: bool) -> Self {
1125            self.has_conflict = has_conflict;
1126            self
1127        }
1128
1129        pub fn with_project_items(mut self, items: &[Model<TestProjectItem>]) -> Self {
1130            self.project_items.clear();
1131            self.project_items.extend(items.iter().cloned());
1132            self
1133        }
1134
1135        pub fn with_serialize(
1136            mut self,
1137            serialize: impl Fn() -> Option<Task<anyhow::Result<()>>> + 'static,
1138        ) -> Self {
1139            self.serialize = Some(Box::new(serialize));
1140            self
1141        }
1142
1143        pub fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
1144            self.push_to_nav_history(cx);
1145            self.state = state;
1146        }
1147
1148        fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
1149            if let Some(history) = &mut self.nav_history {
1150                history.push(Some(Box::new(self.state.clone())), cx);
1151            }
1152        }
1153    }
1154
1155    impl Render for TestItem {
1156        fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
1157            gpui::div().track_focus(&self.focus_handle)
1158        }
1159    }
1160
1161    impl EventEmitter<ItemEvent> for TestItem {}
1162
1163    impl FocusableView for TestItem {
1164        fn focus_handle(&self, _: &AppContext) -> gpui::FocusHandle {
1165            self.focus_handle.clone()
1166        }
1167    }
1168
1169    impl Item for TestItem {
1170        type Event = ItemEvent;
1171
1172        fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1173            f(*event)
1174        }
1175
1176        fn tab_description(&self, detail: usize, _: &AppContext) -> Option<SharedString> {
1177            self.tab_descriptions.as_ref().and_then(|descriptions| {
1178                let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
1179                Some(description.into())
1180            })
1181        }
1182
1183        fn telemetry_event_text(&self) -> Option<&'static str> {
1184            None
1185        }
1186
1187        fn tab_content(
1188            &self,
1189            params: TabContentParams,
1190            _cx: &ui::prelude::WindowContext,
1191        ) -> AnyElement {
1192            self.tab_detail.set(params.detail);
1193            gpui::div().into_any_element()
1194        }
1195
1196        fn for_each_project_item(
1197            &self,
1198            cx: &AppContext,
1199            f: &mut dyn FnMut(EntityId, &dyn project::Item),
1200        ) {
1201            self.project_items
1202                .iter()
1203                .for_each(|item| f(item.entity_id(), item.read(cx)))
1204        }
1205
1206        fn is_singleton(&self, _: &AppContext) -> bool {
1207            self.is_singleton
1208        }
1209
1210        fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
1211            self.nav_history = Some(history);
1212        }
1213
1214        fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
1215            let state = *state.downcast::<String>().unwrap_or_default();
1216            if state != self.state {
1217                self.state = state;
1218                true
1219            } else {
1220                false
1221            }
1222        }
1223
1224        fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
1225            self.push_to_nav_history(cx);
1226        }
1227
1228        fn clone_on_split(
1229            &self,
1230            _workspace_id: Option<WorkspaceId>,
1231            cx: &mut ViewContext<Self>,
1232        ) -> Option<View<Self>>
1233        where
1234            Self: Sized,
1235        {
1236            Some(cx.new_view(|cx| Self {
1237                state: self.state.clone(),
1238                label: self.label.clone(),
1239                save_count: self.save_count,
1240                save_as_count: self.save_as_count,
1241                reload_count: self.reload_count,
1242                is_dirty: self.is_dirty,
1243                is_singleton: self.is_singleton,
1244                has_conflict: self.has_conflict,
1245                project_items: self.project_items.clone(),
1246                nav_history: None,
1247                tab_descriptions: None,
1248                tab_detail: Default::default(),
1249                workspace_id: self.workspace_id,
1250                focus_handle: cx.focus_handle(),
1251                serialize: None,
1252            }))
1253        }
1254
1255        fn is_dirty(&self, _: &AppContext) -> bool {
1256            self.is_dirty
1257        }
1258
1259        fn has_conflict(&self, _: &AppContext) -> bool {
1260            self.has_conflict
1261        }
1262
1263        fn can_save(&self, cx: &AppContext) -> bool {
1264            !self.project_items.is_empty()
1265                && self
1266                    .project_items
1267                    .iter()
1268                    .all(|item| item.read(cx).entry_id.is_some())
1269        }
1270
1271        fn save(
1272            &mut self,
1273            _: bool,
1274            _: Model<Project>,
1275            _: &mut ViewContext<Self>,
1276        ) -> Task<anyhow::Result<()>> {
1277            self.save_count += 1;
1278            self.is_dirty = false;
1279            Task::ready(Ok(()))
1280        }
1281
1282        fn save_as(
1283            &mut self,
1284            _: Model<Project>,
1285            _: ProjectPath,
1286            _: &mut ViewContext<Self>,
1287        ) -> Task<anyhow::Result<()>> {
1288            self.save_as_count += 1;
1289            self.is_dirty = false;
1290            Task::ready(Ok(()))
1291        }
1292
1293        fn reload(
1294            &mut self,
1295            _: Model<Project>,
1296            _: &mut ViewContext<Self>,
1297        ) -> Task<anyhow::Result<()>> {
1298            self.reload_count += 1;
1299            self.is_dirty = false;
1300            Task::ready(Ok(()))
1301        }
1302    }
1303
1304    impl SerializableItem for TestItem {
1305        fn serialized_item_kind() -> &'static str {
1306            "TestItem"
1307        }
1308
1309        fn deserialize(
1310            _project: Model<Project>,
1311            _workspace: WeakView<Workspace>,
1312            workspace_id: WorkspaceId,
1313            _item_id: ItemId,
1314            cx: &mut ViewContext<Pane>,
1315        ) -> Task<anyhow::Result<View<Self>>> {
1316            let view = cx.new_view(|cx| Self::new_deserialized(workspace_id, cx));
1317            Task::ready(Ok(view))
1318        }
1319
1320        fn cleanup(
1321            _workspace_id: WorkspaceId,
1322            _alive_items: Vec<ItemId>,
1323            _cx: &mut ui::WindowContext,
1324        ) -> Task<anyhow::Result<()>> {
1325            Task::ready(Ok(()))
1326        }
1327
1328        fn serialize(
1329            &mut self,
1330            _workspace: &mut Workspace,
1331            _item_id: ItemId,
1332            _closing: bool,
1333            _cx: &mut ViewContext<Self>,
1334        ) -> Option<Task<anyhow::Result<()>>> {
1335            if let Some(serialize) = self.serialize.take() {
1336                let result = serialize();
1337                self.serialize = Some(serialize);
1338                result
1339            } else {
1340                None
1341            }
1342        }
1343
1344        fn should_serialize(&self, _event: &Self::Event) -> bool {
1345            false
1346        }
1347    }
1348}