item.rs

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