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