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