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