item.rs

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