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