item.rs

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