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