workspace.rs

   1/// NOTE: Focus only 'takes' after an update has flushed_effects. Pane sends an event in on_focus_in
   2/// which the workspace uses to change the activated pane.
   3///
   4/// This may cause issues when you're trying to write tests that use workspace focus to add items at
   5/// specific locations.
   6pub mod pane;
   7pub mod pane_group;
   8pub mod programs;
   9pub mod searchable;
  10pub mod sidebar;
  11mod status_bar;
  12mod toolbar;
  13mod waiting_room;
  14
  15use anyhow::{anyhow, Context, Result};
  16use client::{
  17    proto, Authenticate, Client, Contact, PeerId, Subscription, TypedEnvelope, User, UserStore,
  18};
  19use clock::ReplicaId;
  20use collections::{hash_map, HashMap, HashSet};
  21use drag_and_drop::DragAndDrop;
  22use futures::{channel::oneshot, FutureExt};
  23use gpui::{
  24    actions,
  25    color::Color,
  26    elements::*,
  27    geometry::{rect::RectF, vector::vec2f, PathBuilder},
  28    impl_actions, impl_internal_actions,
  29    json::{self, ToJson},
  30    platform::{CursorStyle, WindowOptions},
  31    AnyModelHandle, AnyViewHandle, AppContext, AsyncAppContext, Border, Entity, ImageData,
  32    ModelContext, ModelHandle, MouseButton, MutableAppContext, PathPromptOptions, PromptLevel,
  33    RenderContext, Task, View, ViewContext, ViewHandle, WeakViewHandle,
  34};
  35use language::LanguageRegistry;
  36use log::error;
  37pub use pane::*;
  38pub use pane_group::*;
  39use postage::prelude::Stream;
  40use programs::ProgramManager;
  41use project::{fs, Fs, Project, ProjectEntryId, ProjectPath, ProjectStore, Worktree, WorktreeId};
  42use searchable::SearchableItemHandle;
  43use serde::Deserialize;
  44use settings::{Autosave, Settings};
  45use sidebar::{Side, Sidebar, SidebarButtons, ToggleSidebarItem};
  46use smallvec::SmallVec;
  47use status_bar::StatusBar;
  48pub use status_bar::StatusItemView;
  49use std::{
  50    any::{Any, TypeId},
  51    borrow::Cow,
  52    cell::RefCell,
  53    fmt,
  54    future::Future,
  55    mem,
  56    ops::Range,
  57    path::{Path, PathBuf},
  58    rc::Rc,
  59    sync::{
  60        atomic::{AtomicBool, Ordering::SeqCst},
  61        Arc,
  62    },
  63    time::Duration,
  64};
  65use theme::{Theme, ThemeRegistry};
  66pub use toolbar::{ToolbarItemLocation, ToolbarItemView};
  67use util::ResultExt;
  68use waiting_room::WaitingRoom;
  69
  70type ProjectItemBuilders = HashMap<
  71    TypeId,
  72    fn(ModelHandle<Project>, AnyModelHandle, &mut ViewContext<Pane>) -> Box<dyn ItemHandle>,
  73>;
  74
  75type FollowableItemBuilder = fn(
  76    ViewHandle<Pane>,
  77    ModelHandle<Project>,
  78    &mut Option<proto::view::Variant>,
  79    &mut MutableAppContext,
  80) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>;
  81type FollowableItemBuilders = HashMap<
  82    TypeId,
  83    (
  84        FollowableItemBuilder,
  85        fn(AnyViewHandle) -> Box<dyn FollowableItemHandle>,
  86    ),
  87>;
  88
  89#[derive(Clone, PartialEq)]
  90pub struct RemoveWorktreeFromProject(pub WorktreeId);
  91
  92actions!(
  93    workspace,
  94    [
  95        Open,
  96        NewFile,
  97        NewWindow,
  98        CloseWindow,
  99        AddFolderToProject,
 100        Unfollow,
 101        Save,
 102        SaveAs,
 103        SaveAll,
 104        ActivatePreviousPane,
 105        ActivateNextPane,
 106        FollowNextCollaborator,
 107        ToggleLeftSidebar,
 108        ToggleRightSidebar,
 109        NewTerminal,
 110        NewSearch
 111    ]
 112);
 113
 114#[derive(Clone, PartialEq)]
 115pub struct OpenPaths {
 116    pub paths: Vec<PathBuf>,
 117}
 118
 119#[derive(Clone, Deserialize, PartialEq)]
 120pub struct ToggleProjectOnline {
 121    #[serde(skip_deserializing)]
 122    pub project: Option<ModelHandle<Project>>,
 123}
 124
 125#[derive(Clone, Deserialize, PartialEq)]
 126pub struct ActivatePane(pub usize);
 127
 128#[derive(Clone, PartialEq)]
 129pub struct ToggleFollow(pub PeerId);
 130
 131#[derive(Clone, PartialEq)]
 132pub struct JoinProject {
 133    pub contact: Arc<Contact>,
 134    pub project_index: usize,
 135}
 136
 137impl_internal_actions!(
 138    workspace,
 139    [
 140        OpenPaths,
 141        ToggleFollow,
 142        JoinProject,
 143        RemoveWorktreeFromProject
 144    ]
 145);
 146impl_actions!(workspace, [ToggleProjectOnline, ActivatePane]);
 147
 148pub fn init(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
 149    // Initialize the program manager immediately
 150    cx.set_global(ProgramManager::new());
 151
 152    pane::init(cx);
 153
 154    cx.add_global_action(open);
 155    cx.add_global_action({
 156        let app_state = Arc::downgrade(&app_state);
 157        move |action: &OpenPaths, cx: &mut MutableAppContext| {
 158            if let Some(app_state) = app_state.upgrade() {
 159                open_paths(&action.paths, &app_state, cx).detach();
 160            }
 161        }
 162    });
 163    cx.add_global_action({
 164        let app_state = Arc::downgrade(&app_state);
 165        move |_: &NewFile, cx: &mut MutableAppContext| {
 166            if let Some(app_state) = app_state.upgrade() {
 167                open_new(&app_state, cx)
 168            }
 169        }
 170    });
 171    cx.add_global_action({
 172        let app_state = Arc::downgrade(&app_state);
 173        move |_: &NewWindow, cx: &mut MutableAppContext| {
 174            if let Some(app_state) = app_state.upgrade() {
 175                open_new(&app_state, cx)
 176            }
 177        }
 178    });
 179    cx.add_global_action({
 180        let app_state = Arc::downgrade(&app_state);
 181        move |action: &JoinProject, cx: &mut MutableAppContext| {
 182            if let Some(app_state) = app_state.upgrade() {
 183                join_project(action.contact.clone(), action.project_index, &app_state, cx);
 184            }
 185        }
 186    });
 187
 188    cx.add_async_action(Workspace::toggle_follow);
 189    cx.add_async_action(Workspace::follow_next_collaborator);
 190    cx.add_async_action(Workspace::close);
 191    cx.add_async_action(Workspace::save_all);
 192    cx.add_action(Workspace::add_folder_to_project);
 193    cx.add_action(Workspace::remove_folder_from_project);
 194    cx.add_action(Workspace::toggle_project_online);
 195    cx.add_action(
 196        |workspace: &mut Workspace, _: &Unfollow, cx: &mut ViewContext<Workspace>| {
 197            let pane = workspace.active_pane().clone();
 198            workspace.unfollow(&pane, cx);
 199        },
 200    );
 201    cx.add_action(
 202        |workspace: &mut Workspace, _: &Save, cx: &mut ViewContext<Workspace>| {
 203            workspace.save_active_item(false, cx).detach_and_log_err(cx);
 204        },
 205    );
 206    cx.add_action(
 207        |workspace: &mut Workspace, _: &SaveAs, cx: &mut ViewContext<Workspace>| {
 208            workspace.save_active_item(true, cx).detach_and_log_err(cx);
 209        },
 210    );
 211    cx.add_action(Workspace::toggle_sidebar_item);
 212    cx.add_action(Workspace::focus_center);
 213    cx.add_action(|workspace: &mut Workspace, _: &ActivatePreviousPane, cx| {
 214        workspace.activate_previous_pane(cx)
 215    });
 216    cx.add_action(|workspace: &mut Workspace, _: &ActivateNextPane, cx| {
 217        workspace.activate_next_pane(cx)
 218    });
 219    cx.add_action(|workspace: &mut Workspace, _: &ToggleLeftSidebar, cx| {
 220        workspace.toggle_sidebar(Side::Left, cx);
 221    });
 222    cx.add_action(|workspace: &mut Workspace, _: &ToggleRightSidebar, cx| {
 223        workspace.toggle_sidebar(Side::Right, cx);
 224    });
 225    cx.add_action(Workspace::activate_pane_at_index);
 226
 227    let client = &app_state.client;
 228    client.add_view_request_handler(Workspace::handle_follow);
 229    client.add_view_message_handler(Workspace::handle_unfollow);
 230    client.add_view_message_handler(Workspace::handle_update_followers);
 231}
 232
 233pub fn register_project_item<I: ProjectItem>(cx: &mut MutableAppContext) {
 234    cx.update_default_global(|builders: &mut ProjectItemBuilders, _| {
 235        builders.insert(TypeId::of::<I::Item>(), |project, model, cx| {
 236            let item = model.downcast::<I::Item>().unwrap();
 237            Box::new(cx.add_view(|cx| I::for_project_item(project, item, cx)))
 238        });
 239    });
 240}
 241
 242pub fn register_followable_item<I: FollowableItem>(cx: &mut MutableAppContext) {
 243    cx.update_default_global(|builders: &mut FollowableItemBuilders, _| {
 244        builders.insert(
 245            TypeId::of::<I>(),
 246            (
 247                |pane, project, state, cx| {
 248                    I::from_state_proto(pane, project, state, cx).map(|task| {
 249                        cx.foreground()
 250                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
 251                    })
 252                },
 253                |this| Box::new(this.downcast::<I>().unwrap()),
 254            ),
 255        );
 256    });
 257}
 258
 259pub struct AppState {
 260    pub languages: Arc<LanguageRegistry>,
 261    pub themes: Arc<ThemeRegistry>,
 262    pub client: Arc<client::Client>,
 263    pub user_store: ModelHandle<client::UserStore>,
 264    pub project_store: ModelHandle<ProjectStore>,
 265    pub fs: Arc<dyn fs::Fs>,
 266    pub build_window_options: fn() -> WindowOptions<'static>,
 267    pub initialize_workspace: fn(&mut Workspace, &Arc<AppState>, &mut ViewContext<Workspace>),
 268}
 269
 270pub trait Item: View {
 271    fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
 272    fn workspace_deactivated(&mut self, _: &mut ViewContext<Self>) {}
 273    fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
 274        false
 275    }
 276    fn tab_description<'a>(&'a self, _: usize, _: &'a AppContext) -> Option<Cow<'a, str>> {
 277        None
 278    }
 279    fn tab_content(&self, detail: Option<usize>, style: &theme::Tab, cx: &AppContext)
 280        -> ElementBox;
 281    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 282    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;
 283    fn is_singleton(&self, cx: &AppContext) -> bool;
 284    fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>);
 285    fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
 286    where
 287        Self: Sized,
 288    {
 289        None
 290    }
 291    fn is_dirty(&self, _: &AppContext) -> bool {
 292        false
 293    }
 294    fn has_conflict(&self, _: &AppContext) -> bool {
 295        false
 296    }
 297    fn can_save(&self, cx: &AppContext) -> bool;
 298    fn save(
 299        &mut self,
 300        project: ModelHandle<Project>,
 301        cx: &mut ViewContext<Self>,
 302    ) -> Task<Result<()>>;
 303    fn save_as(
 304        &mut self,
 305        project: ModelHandle<Project>,
 306        abs_path: PathBuf,
 307        cx: &mut ViewContext<Self>,
 308    ) -> Task<Result<()>>;
 309    fn reload(
 310        &mut self,
 311        project: ModelHandle<Project>,
 312        cx: &mut ViewContext<Self>,
 313    ) -> Task<Result<()>>;
 314    fn should_close_item_on_event(_: &Self::Event) -> bool {
 315        false
 316    }
 317    fn should_update_tab_on_event(_: &Self::Event) -> bool {
 318        false
 319    }
 320    fn is_edit_event(_: &Self::Event) -> bool {
 321        false
 322    }
 323    fn act_as_type(
 324        &self,
 325        type_id: TypeId,
 326        self_handle: &ViewHandle<Self>,
 327        _: &AppContext,
 328    ) -> Option<AnyViewHandle> {
 329        if TypeId::of::<Self>() == type_id {
 330            Some(self_handle.into())
 331        } else {
 332            None
 333        }
 334    }
 335    fn as_searchable(&self, _: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 336        None
 337    }
 338}
 339
 340pub trait ProjectItem: Item {
 341    type Item: project::Item;
 342
 343    fn for_project_item(
 344        project: ModelHandle<Project>,
 345        item: ModelHandle<Self::Item>,
 346        cx: &mut ViewContext<Self>,
 347    ) -> Self;
 348}
 349
 350pub trait FollowableItem: Item {
 351    fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
 352    fn from_state_proto(
 353        pane: ViewHandle<Pane>,
 354        project: ModelHandle<Project>,
 355        state: &mut Option<proto::view::Variant>,
 356        cx: &mut MutableAppContext,
 357    ) -> Option<Task<Result<ViewHandle<Self>>>>;
 358    fn add_event_to_update_proto(
 359        &self,
 360        event: &Self::Event,
 361        update: &mut Option<proto::update_view::Variant>,
 362        cx: &AppContext,
 363    ) -> bool;
 364    fn apply_update_proto(
 365        &mut self,
 366        message: proto::update_view::Variant,
 367        cx: &mut ViewContext<Self>,
 368    ) -> Result<()>;
 369
 370    fn set_leader_replica_id(&mut self, leader_replica_id: Option<u16>, cx: &mut ViewContext<Self>);
 371    fn should_unfollow_on_event(event: &Self::Event, cx: &AppContext) -> bool;
 372}
 373
 374pub trait FollowableItemHandle: ItemHandle {
 375    fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext);
 376    fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
 377    fn add_event_to_update_proto(
 378        &self,
 379        event: &dyn Any,
 380        update: &mut Option<proto::update_view::Variant>,
 381        cx: &AppContext,
 382    ) -> bool;
 383    fn apply_update_proto(
 384        &self,
 385        message: proto::update_view::Variant,
 386        cx: &mut MutableAppContext,
 387    ) -> Result<()>;
 388    fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool;
 389}
 390
 391impl<T: FollowableItem> FollowableItemHandle for ViewHandle<T> {
 392    fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext) {
 393        self.update(cx, |this, cx| {
 394            this.set_leader_replica_id(leader_replica_id, cx)
 395        })
 396    }
 397
 398    fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
 399        self.read(cx).to_state_proto(cx)
 400    }
 401
 402    fn add_event_to_update_proto(
 403        &self,
 404        event: &dyn Any,
 405        update: &mut Option<proto::update_view::Variant>,
 406        cx: &AppContext,
 407    ) -> bool {
 408        if let Some(event) = event.downcast_ref() {
 409            self.read(cx).add_event_to_update_proto(event, update, cx)
 410        } else {
 411            false
 412        }
 413    }
 414
 415    fn apply_update_proto(
 416        &self,
 417        message: proto::update_view::Variant,
 418        cx: &mut MutableAppContext,
 419    ) -> Result<()> {
 420        self.update(cx, |this, cx| this.apply_update_proto(message, cx))
 421    }
 422
 423    fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool {
 424        if let Some(event) = event.downcast_ref() {
 425            T::should_unfollow_on_event(event, cx)
 426        } else {
 427            false
 428        }
 429    }
 430}
 431
 432pub trait ItemHandle: 'static + fmt::Debug {
 433    fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>>;
 434    fn tab_content(&self, detail: Option<usize>, style: &theme::Tab, cx: &AppContext)
 435        -> ElementBox;
 436    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 437    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;
 438    fn is_singleton(&self, cx: &AppContext) -> bool;
 439    fn boxed_clone(&self) -> Box<dyn ItemHandle>;
 440    fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>>;
 441    fn added_to_pane(
 442        &self,
 443        workspace: &mut Workspace,
 444        pane: ViewHandle<Pane>,
 445        cx: &mut ViewContext<Workspace>,
 446    );
 447    fn deactivated(&self, cx: &mut MutableAppContext);
 448    fn workspace_deactivated(&self, cx: &mut MutableAppContext);
 449    fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool;
 450    fn id(&self) -> usize;
 451    fn window_id(&self) -> usize;
 452    fn to_any(&self) -> AnyViewHandle;
 453    fn is_dirty(&self, cx: &AppContext) -> bool;
 454    fn has_conflict(&self, cx: &AppContext) -> bool;
 455    fn can_save(&self, cx: &AppContext) -> bool;
 456    fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>>;
 457    fn save_as(
 458        &self,
 459        project: ModelHandle<Project>,
 460        abs_path: PathBuf,
 461        cx: &mut MutableAppContext,
 462    ) -> Task<Result<()>>;
 463    fn reload(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext)
 464        -> Task<Result<()>>;
 465    fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle>;
 466    fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
 467    fn on_release(
 468        &self,
 469        cx: &mut MutableAppContext,
 470        callback: Box<dyn FnOnce(&mut MutableAppContext)>,
 471    ) -> gpui::Subscription;
 472    fn as_searchable(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>>;
 473}
 474
 475pub trait WeakItemHandle {
 476    fn id(&self) -> usize;
 477    fn window_id(&self) -> usize;
 478    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>>;
 479}
 480
 481impl dyn ItemHandle {
 482    pub fn downcast<T: View>(&self) -> Option<ViewHandle<T>> {
 483        self.to_any().downcast()
 484    }
 485
 486    pub fn act_as<T: View>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
 487        self.act_as_type(TypeId::of::<T>(), cx)
 488            .and_then(|t| t.downcast())
 489    }
 490}
 491
 492impl<T: Item> ItemHandle for ViewHandle<T> {
 493    fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>> {
 494        self.read(cx).tab_description(detail, cx)
 495    }
 496
 497    fn tab_content(
 498        &self,
 499        detail: Option<usize>,
 500        style: &theme::Tab,
 501        cx: &AppContext,
 502    ) -> ElementBox {
 503        self.read(cx).tab_content(detail, style, cx)
 504    }
 505
 506    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
 507        self.read(cx).project_path(cx)
 508    }
 509
 510    fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
 511        self.read(cx).project_entry_ids(cx)
 512    }
 513
 514    fn is_singleton(&self, cx: &AppContext) -> bool {
 515        self.read(cx).is_singleton(cx)
 516    }
 517
 518    fn boxed_clone(&self) -> Box<dyn ItemHandle> {
 519        Box::new(self.clone())
 520    }
 521
 522    fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>> {
 523        self.update(cx, |item, cx| {
 524            cx.add_option_view(|cx| item.clone_on_split(cx))
 525        })
 526        .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
 527    }
 528
 529    fn added_to_pane(
 530        &self,
 531        workspace: &mut Workspace,
 532        pane: ViewHandle<Pane>,
 533        cx: &mut ViewContext<Workspace>,
 534    ) {
 535        let history = pane.read(cx).nav_history_for_item(self);
 536        self.update(cx, |this, cx| this.set_nav_history(history, cx));
 537
 538        if let Some(followed_item) = self.to_followable_item_handle(cx) {
 539            if let Some(message) = followed_item.to_state_proto(cx) {
 540                workspace.update_followers(
 541                    proto::update_followers::Variant::CreateView(proto::View {
 542                        id: followed_item.id() as u64,
 543                        variant: Some(message),
 544                        leader_id: workspace.leader_for_pane(&pane).map(|id| id.0),
 545                    }),
 546                    cx,
 547                );
 548            }
 549        }
 550
 551        if workspace
 552            .panes_by_item
 553            .insert(self.id(), pane.downgrade())
 554            .is_none()
 555        {
 556            let mut pending_autosave = None;
 557            let mut cancel_pending_autosave = oneshot::channel::<()>().0;
 558            let pending_update = Rc::new(RefCell::new(None));
 559            let pending_update_scheduled = Rc::new(AtomicBool::new(false));
 560
 561            let mut event_subscription =
 562                Some(cx.subscribe(self, move |workspace, item, event, cx| {
 563                    let pane = if let Some(pane) = workspace
 564                        .panes_by_item
 565                        .get(&item.id())
 566                        .and_then(|pane| pane.upgrade(cx))
 567                    {
 568                        pane
 569                    } else {
 570                        log::error!("unexpected item event after pane was dropped");
 571                        return;
 572                    };
 573
 574                    if let Some(item) = item.to_followable_item_handle(cx) {
 575                        let leader_id = workspace.leader_for_pane(&pane);
 576
 577                        if leader_id.is_some() && item.should_unfollow_on_event(event, cx) {
 578                            workspace.unfollow(&pane, cx);
 579                        }
 580
 581                        if item.add_event_to_update_proto(
 582                            event,
 583                            &mut *pending_update.borrow_mut(),
 584                            cx,
 585                        ) && !pending_update_scheduled.load(SeqCst)
 586                        {
 587                            pending_update_scheduled.store(true, SeqCst);
 588                            cx.after_window_update({
 589                                let pending_update = pending_update.clone();
 590                                let pending_update_scheduled = pending_update_scheduled.clone();
 591                                move |this, cx| {
 592                                    pending_update_scheduled.store(false, SeqCst);
 593                                    this.update_followers(
 594                                        proto::update_followers::Variant::UpdateView(
 595                                            proto::UpdateView {
 596                                                id: item.id() as u64,
 597                                                variant: pending_update.borrow_mut().take(),
 598                                                leader_id: leader_id.map(|id| id.0),
 599                                            },
 600                                        ),
 601                                        cx,
 602                                    );
 603                                }
 604                            });
 605                        }
 606                    }
 607
 608                    if T::should_close_item_on_event(event) {
 609                        Pane::close_item(workspace, pane, item.id(), cx).detach_and_log_err(cx);
 610                        return;
 611                    }
 612
 613                    if T::should_update_tab_on_event(event) {
 614                        pane.update(cx, |_, cx| {
 615                            cx.emit(pane::Event::ChangeItemTitle);
 616                            cx.notify();
 617                        });
 618                    }
 619
 620                    if T::is_edit_event(event) {
 621                        if let Autosave::AfterDelay { milliseconds } =
 622                            cx.global::<Settings>().autosave
 623                        {
 624                            let prev_autosave = pending_autosave
 625                                .take()
 626                                .unwrap_or_else(|| Task::ready(Some(())));
 627                            let (cancel_tx, mut cancel_rx) = oneshot::channel::<()>();
 628                            let prev_cancel_tx =
 629                                mem::replace(&mut cancel_pending_autosave, cancel_tx);
 630                            let project = workspace.project.downgrade();
 631                            let _ = prev_cancel_tx.send(());
 632                            pending_autosave = Some(cx.spawn_weak(|_, mut cx| async move {
 633                                let mut timer = cx
 634                                    .background()
 635                                    .timer(Duration::from_millis(milliseconds))
 636                                    .fuse();
 637                                prev_autosave.await;
 638                                futures::select_biased! {
 639                                    _ = cancel_rx => return None,
 640                                    _ = timer => {}
 641                                }
 642
 643                                let project = project.upgrade(&cx)?;
 644                                cx.update(|cx| Pane::autosave_item(&item, project, cx))
 645                                    .await
 646                                    .log_err();
 647                                None
 648                            }));
 649                        }
 650                    }
 651                }));
 652
 653            cx.observe_focus(self, move |workspace, item, focused, cx| {
 654                if !focused && cx.global::<Settings>().autosave == Autosave::OnFocusChange {
 655                    Pane::autosave_item(&item, workspace.project.clone(), cx)
 656                        .detach_and_log_err(cx);
 657                }
 658            })
 659            .detach();
 660
 661            let item_id = self.id();
 662            cx.observe_release(self, move |workspace, _, _| {
 663                workspace.panes_by_item.remove(&item_id);
 664                event_subscription.take();
 665            })
 666            .detach();
 667        }
 668    }
 669
 670    fn deactivated(&self, cx: &mut MutableAppContext) {
 671        self.update(cx, |this, cx| this.deactivated(cx));
 672    }
 673
 674    fn workspace_deactivated(&self, cx: &mut MutableAppContext) {
 675        self.update(cx, |this, cx| this.workspace_deactivated(cx));
 676    }
 677
 678    fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool {
 679        self.update(cx, |this, cx| this.navigate(data, cx))
 680    }
 681
 682    fn id(&self) -> usize {
 683        self.id()
 684    }
 685
 686    fn window_id(&self) -> usize {
 687        self.window_id()
 688    }
 689
 690    fn to_any(&self) -> AnyViewHandle {
 691        self.into()
 692    }
 693
 694    fn is_dirty(&self, cx: &AppContext) -> bool {
 695        self.read(cx).is_dirty(cx)
 696    }
 697
 698    fn has_conflict(&self, cx: &AppContext) -> bool {
 699        self.read(cx).has_conflict(cx)
 700    }
 701
 702    fn can_save(&self, cx: &AppContext) -> bool {
 703        self.read(cx).can_save(cx)
 704    }
 705
 706    fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>> {
 707        self.update(cx, |item, cx| item.save(project, cx))
 708    }
 709
 710    fn save_as(
 711        &self,
 712        project: ModelHandle<Project>,
 713        abs_path: PathBuf,
 714        cx: &mut MutableAppContext,
 715    ) -> Task<anyhow::Result<()>> {
 716        self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
 717    }
 718
 719    fn reload(
 720        &self,
 721        project: ModelHandle<Project>,
 722        cx: &mut MutableAppContext,
 723    ) -> Task<Result<()>> {
 724        self.update(cx, |item, cx| item.reload(project, cx))
 725    }
 726
 727    fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle> {
 728        self.read(cx).act_as_type(type_id, self, cx)
 729    }
 730
 731    fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
 732        if cx.has_global::<FollowableItemBuilders>() {
 733            let builders = cx.global::<FollowableItemBuilders>();
 734            let item = self.to_any();
 735            Some(builders.get(&item.view_type())?.1(item))
 736        } else {
 737            None
 738        }
 739    }
 740
 741    fn on_release(
 742        &self,
 743        cx: &mut MutableAppContext,
 744        callback: Box<dyn FnOnce(&mut MutableAppContext)>,
 745    ) -> gpui::Subscription {
 746        cx.observe_release(self, move |_, cx| callback(cx))
 747    }
 748
 749    fn as_searchable(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {
 750        self.read(cx).as_searchable(self)
 751    }
 752}
 753
 754impl From<Box<dyn ItemHandle>> for AnyViewHandle {
 755    fn from(val: Box<dyn ItemHandle>) -> Self {
 756        val.to_any()
 757    }
 758}
 759
 760impl From<&Box<dyn ItemHandle>> for AnyViewHandle {
 761    fn from(val: &Box<dyn ItemHandle>) -> Self {
 762        val.to_any()
 763    }
 764}
 765
 766impl Clone for Box<dyn ItemHandle> {
 767    fn clone(&self) -> Box<dyn ItemHandle> {
 768        self.boxed_clone()
 769    }
 770}
 771
 772impl<T: Item> WeakItemHandle for WeakViewHandle<T> {
 773    fn id(&self) -> usize {
 774        self.id()
 775    }
 776
 777    fn window_id(&self) -> usize {
 778        self.window_id()
 779    }
 780
 781    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
 782        self.upgrade(cx).map(|v| Box::new(v) as Box<dyn ItemHandle>)
 783    }
 784}
 785
 786pub trait Notification: View {
 787    fn should_dismiss_notification_on_event(&self, event: &<Self as Entity>::Event) -> bool;
 788}
 789
 790pub trait NotificationHandle {
 791    fn id(&self) -> usize;
 792    fn to_any(&self) -> AnyViewHandle;
 793}
 794
 795impl<T: Notification> NotificationHandle for ViewHandle<T> {
 796    fn id(&self) -> usize {
 797        self.id()
 798    }
 799
 800    fn to_any(&self) -> AnyViewHandle {
 801        self.into()
 802    }
 803}
 804
 805impl From<&dyn NotificationHandle> for AnyViewHandle {
 806    fn from(val: &dyn NotificationHandle) -> Self {
 807        val.to_any()
 808    }
 809}
 810
 811impl AppState {
 812    #[cfg(any(test, feature = "test-support"))]
 813    pub fn test(cx: &mut MutableAppContext) -> Arc<Self> {
 814        let settings = Settings::test(cx);
 815        cx.set_global(settings);
 816
 817        let fs = project::FakeFs::new(cx.background().clone());
 818        let languages = Arc::new(LanguageRegistry::test());
 819        let http_client = client::test::FakeHttpClient::with_404_response();
 820        let client = Client::new(http_client.clone());
 821        let project_store = cx.add_model(|_| ProjectStore::new(project::Db::open_fake()));
 822        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 823        let themes = ThemeRegistry::new((), cx.font_cache().clone());
 824        Arc::new(Self {
 825            client,
 826            themes,
 827            fs,
 828            languages,
 829            user_store,
 830            project_store,
 831            initialize_workspace: |_, _, _| {},
 832            build_window_options: Default::default,
 833        })
 834    }
 835}
 836
 837pub enum Event {
 838    PaneAdded(ViewHandle<Pane>),
 839    ContactRequestedJoin(u64),
 840}
 841
 842pub struct Workspace {
 843    weak_self: WeakViewHandle<Self>,
 844    client: Arc<Client>,
 845    user_store: ModelHandle<client::UserStore>,
 846    remote_entity_subscription: Option<Subscription>,
 847    fs: Arc<dyn Fs>,
 848    modal: Option<AnyViewHandle>,
 849    center: PaneGroup,
 850    left_sidebar: ViewHandle<Sidebar>,
 851    right_sidebar: ViewHandle<Sidebar>,
 852    panes: Vec<ViewHandle<Pane>>,
 853    panes_by_item: HashMap<usize, WeakViewHandle<Pane>>,
 854    active_pane: ViewHandle<Pane>,
 855    status_bar: ViewHandle<StatusBar>,
 856    notifications: Vec<(TypeId, usize, Box<dyn NotificationHandle>)>,
 857    project: ModelHandle<Project>,
 858    leader_state: LeaderState,
 859    follower_states_by_leader: FollowerStatesByLeader,
 860    last_leaders_by_pane: HashMap<WeakViewHandle<Pane>, PeerId>,
 861    window_edited: bool,
 862    _observe_current_user: Task<()>,
 863}
 864
 865#[derive(Default)]
 866struct LeaderState {
 867    followers: HashSet<PeerId>,
 868}
 869
 870type FollowerStatesByLeader = HashMap<PeerId, HashMap<ViewHandle<Pane>, FollowerState>>;
 871
 872#[derive(Default)]
 873struct FollowerState {
 874    active_view_id: Option<u64>,
 875    items_by_leader_view_id: HashMap<u64, FollowerItem>,
 876}
 877
 878#[derive(Debug)]
 879enum FollowerItem {
 880    Loading(Vec<proto::update_view::Variant>),
 881    Loaded(Box<dyn FollowableItemHandle>),
 882}
 883
 884impl Workspace {
 885    pub fn new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
 886        cx.observe_fullscreen(|_, _, cx| cx.notify()).detach();
 887
 888        cx.observe_window_activation(Self::on_window_activation_changed)
 889            .detach();
 890        cx.observe(&project, |_, _, cx| cx.notify()).detach();
 891        cx.subscribe(&project, move |this, _, event, cx| {
 892            match event {
 893                project::Event::RemoteIdChanged(remote_id) => {
 894                    this.project_remote_id_changed(*remote_id, cx);
 895                }
 896                project::Event::CollaboratorLeft(peer_id) => {
 897                    this.collaborator_left(*peer_id, cx);
 898                }
 899                project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded => {
 900                    this.update_window_title(cx);
 901                }
 902                project::Event::DisconnectedFromHost => {
 903                    this.update_window_edited(cx);
 904                    cx.blur();
 905                }
 906                _ => {}
 907            }
 908            cx.notify()
 909        })
 910        .detach();
 911
 912        let pane = cx.add_view(Pane::new);
 913        let pane_id = pane.id();
 914        cx.subscribe(&pane, move |this, _, event, cx| {
 915            this.handle_pane_event(pane_id, event, cx)
 916        })
 917        .detach();
 918        cx.focus(&pane);
 919        cx.emit(Event::PaneAdded(pane.clone()));
 920
 921        let fs = project.read(cx).fs().clone();
 922        let user_store = project.read(cx).user_store();
 923        let client = project.read(cx).client();
 924        let mut current_user = user_store.read(cx).watch_current_user();
 925        let mut connection_status = client.status();
 926        let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
 927            current_user.recv().await;
 928            connection_status.recv().await;
 929            let mut stream =
 930                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 931
 932            while stream.recv().await.is_some() {
 933                cx.update(|cx| {
 934                    if let Some(this) = this.upgrade(cx) {
 935                        this.update(cx, |_, cx| cx.notify());
 936                    }
 937                })
 938            }
 939        });
 940
 941        let weak_self = cx.weak_handle();
 942
 943        cx.emit_global(WorkspaceCreated(weak_self.clone()));
 944
 945        let left_sidebar = cx.add_view(|_| Sidebar::new(Side::Left));
 946        let right_sidebar = cx.add_view(|_| Sidebar::new(Side::Right));
 947        let left_sidebar_buttons = cx.add_view(|cx| SidebarButtons::new(left_sidebar.clone(), cx));
 948        let right_sidebar_buttons =
 949            cx.add_view(|cx| SidebarButtons::new(right_sidebar.clone(), cx));
 950        let status_bar = cx.add_view(|cx| {
 951            let mut status_bar = StatusBar::new(&pane.clone(), cx);
 952            status_bar.add_left_item(left_sidebar_buttons, cx);
 953            status_bar.add_right_item(right_sidebar_buttons, cx);
 954            status_bar
 955        });
 956
 957        cx.update_default_global::<DragAndDrop<Workspace>, _, _>(|drag_and_drop, _| {
 958            drag_and_drop.register_container(weak_self.clone());
 959        });
 960
 961        let mut this = Workspace {
 962            modal: None,
 963            weak_self,
 964            center: PaneGroup::new(pane.clone()),
 965            panes: vec![pane.clone()],
 966            panes_by_item: Default::default(),
 967            active_pane: pane.clone(),
 968            status_bar,
 969            notifications: Default::default(),
 970            client,
 971            remote_entity_subscription: None,
 972            user_store,
 973            fs,
 974            left_sidebar,
 975            right_sidebar,
 976            project,
 977            leader_state: Default::default(),
 978            follower_states_by_leader: Default::default(),
 979            last_leaders_by_pane: Default::default(),
 980            window_edited: false,
 981            _observe_current_user,
 982        };
 983        this.project_remote_id_changed(this.project.read(cx).remote_id(), cx);
 984        cx.defer(|this, cx| this.update_window_title(cx));
 985
 986        this
 987    }
 988
 989    pub fn weak_handle(&self) -> WeakViewHandle<Self> {
 990        self.weak_self.clone()
 991    }
 992
 993    pub fn left_sidebar(&self) -> &ViewHandle<Sidebar> {
 994        &self.left_sidebar
 995    }
 996
 997    pub fn right_sidebar(&self) -> &ViewHandle<Sidebar> {
 998        &self.right_sidebar
 999    }
1000
1001    pub fn status_bar(&self) -> &ViewHandle<StatusBar> {
1002        &self.status_bar
1003    }
1004
1005    pub fn user_store(&self) -> &ModelHandle<UserStore> {
1006        &self.user_store
1007    }
1008
1009    pub fn project(&self) -> &ModelHandle<Project> {
1010        &self.project
1011    }
1012
1013    /// Call the given callback with a workspace whose project is local.
1014    ///
1015    /// If the given workspace has a local project, then it will be passed
1016    /// to the callback. Otherwise, a new empty window will be created.
1017    pub fn with_local_workspace<T, F>(
1018        &mut self,
1019        cx: &mut ViewContext<Self>,
1020        app_state: Arc<AppState>,
1021        callback: F,
1022    ) -> T
1023    where
1024        T: 'static,
1025        F: FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,
1026    {
1027        if self.project.read(cx).is_local() {
1028            callback(self, cx)
1029        } else {
1030            let (_, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
1031                let mut workspace = Workspace::new(
1032                    Project::local(
1033                        false,
1034                        app_state.client.clone(),
1035                        app_state.user_store.clone(),
1036                        app_state.project_store.clone(),
1037                        app_state.languages.clone(),
1038                        app_state.fs.clone(),
1039                        cx,
1040                    ),
1041                    cx,
1042                );
1043                (app_state.initialize_workspace)(&mut workspace, &app_state, cx);
1044                workspace
1045            });
1046            workspace.update(cx, callback)
1047        }
1048    }
1049
1050    pub fn worktrees<'a>(
1051        &self,
1052        cx: &'a AppContext,
1053    ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
1054        self.project.read(cx).worktrees(cx)
1055    }
1056
1057    pub fn visible_worktrees<'a>(
1058        &self,
1059        cx: &'a AppContext,
1060    ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
1061        self.project.read(cx).visible_worktrees(cx)
1062    }
1063
1064    pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
1065        let futures = self
1066            .worktrees(cx)
1067            .filter_map(|worktree| worktree.read(cx).as_local())
1068            .map(|worktree| worktree.scan_complete())
1069            .collect::<Vec<_>>();
1070        async move {
1071            for future in futures {
1072                future.await;
1073            }
1074        }
1075    }
1076
1077    pub fn close(
1078        &mut self,
1079        _: &CloseWindow,
1080        cx: &mut ViewContext<Self>,
1081    ) -> Option<Task<Result<()>>> {
1082        let prepare = self.prepare_to_close(cx);
1083        Some(cx.spawn(|this, mut cx| async move {
1084            if prepare.await? {
1085                this.update(&mut cx, |_, cx| {
1086                    let window_id = cx.window_id();
1087                    cx.remove_window(window_id);
1088                });
1089            }
1090            Ok(())
1091        }))
1092    }
1093
1094    pub fn prepare_to_close(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<bool>> {
1095        self.save_all_internal(true, cx)
1096    }
1097
1098    fn save_all(&mut self, _: &SaveAll, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
1099        let save_all = self.save_all_internal(false, cx);
1100        Some(cx.foreground().spawn(async move {
1101            save_all.await?;
1102            Ok(())
1103        }))
1104    }
1105
1106    fn save_all_internal(
1107        &mut self,
1108        should_prompt_to_save: bool,
1109        cx: &mut ViewContext<Self>,
1110    ) -> Task<Result<bool>> {
1111        if self.project.read(cx).is_read_only() {
1112            return Task::ready(Ok(true));
1113        }
1114
1115        let dirty_items = self
1116            .panes
1117            .iter()
1118            .flat_map(|pane| {
1119                pane.read(cx).items().filter_map(|item| {
1120                    if item.is_dirty(cx) {
1121                        Some((pane.clone(), item.boxed_clone()))
1122                    } else {
1123                        None
1124                    }
1125                })
1126            })
1127            .collect::<Vec<_>>();
1128
1129        let project = self.project.clone();
1130        cx.spawn_weak(|_, mut cx| async move {
1131            for (pane, item) in dirty_items {
1132                let (singleton, project_entry_ids) =
1133                    cx.read(|cx| (item.is_singleton(cx), item.project_entry_ids(cx)));
1134                if singleton || !project_entry_ids.is_empty() {
1135                    if let Some(ix) =
1136                        pane.read_with(&cx, |pane, _| pane.index_for_item(item.as_ref()))
1137                    {
1138                        if !Pane::save_item(
1139                            project.clone(),
1140                            &pane,
1141                            ix,
1142                            &*item,
1143                            should_prompt_to_save,
1144                            &mut cx,
1145                        )
1146                        .await?
1147                        {
1148                            return Ok(false);
1149                        }
1150                    }
1151                }
1152            }
1153            Ok(true)
1154        })
1155    }
1156
1157    #[allow(clippy::type_complexity)]
1158    pub fn open_paths(
1159        &mut self,
1160        mut abs_paths: Vec<PathBuf>,
1161        visible: bool,
1162        cx: &mut ViewContext<Self>,
1163    ) -> Task<Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>> {
1164        let fs = self.fs.clone();
1165
1166        // Sort the paths to ensure we add worktrees for parents before their children.
1167        abs_paths.sort_unstable();
1168        cx.spawn(|this, mut cx| async move {
1169            let mut project_paths = Vec::new();
1170            for path in &abs_paths {
1171                project_paths.push(
1172                    this.update(&mut cx, |this, cx| {
1173                        this.project_path_for_path(path, visible, cx)
1174                    })
1175                    .await
1176                    .log_err(),
1177                );
1178            }
1179
1180            let tasks = abs_paths
1181                .iter()
1182                .cloned()
1183                .zip(project_paths.into_iter())
1184                .map(|(abs_path, project_path)| {
1185                    let this = this.clone();
1186                    cx.spawn(|mut cx| {
1187                        let fs = fs.clone();
1188                        async move {
1189                            let (_worktree, project_path) = project_path?;
1190                            if fs.is_file(&abs_path).await {
1191                                Some(
1192                                    this.update(&mut cx, |this, cx| {
1193                                        this.open_path(project_path, true, cx)
1194                                    })
1195                                    .await,
1196                                )
1197                            } else {
1198                                None
1199                            }
1200                        }
1201                    })
1202                })
1203                .collect::<Vec<_>>();
1204
1205            futures::future::join_all(tasks).await
1206        })
1207    }
1208
1209    fn add_folder_to_project(&mut self, _: &AddFolderToProject, cx: &mut ViewContext<Self>) {
1210        let mut paths = cx.prompt_for_paths(PathPromptOptions {
1211            files: false,
1212            directories: true,
1213            multiple: true,
1214        });
1215        cx.spawn(|this, mut cx| async move {
1216            if let Some(paths) = paths.recv().await.flatten() {
1217                let results = this
1218                    .update(&mut cx, |this, cx| this.open_paths(paths, true, cx))
1219                    .await;
1220                for result in results.into_iter().flatten() {
1221                    result.log_err();
1222                }
1223            }
1224        })
1225        .detach();
1226    }
1227
1228    fn remove_folder_from_project(
1229        &mut self,
1230        RemoveWorktreeFromProject(worktree_id): &RemoveWorktreeFromProject,
1231        cx: &mut ViewContext<Self>,
1232    ) {
1233        self.project
1234            .update(cx, |project, cx| project.remove_worktree(*worktree_id, cx));
1235    }
1236
1237    fn toggle_project_online(&mut self, action: &ToggleProjectOnline, cx: &mut ViewContext<Self>) {
1238        let project = action
1239            .project
1240            .clone()
1241            .unwrap_or_else(|| self.project.clone());
1242        project.update(cx, |project, cx| {
1243            let public = !project.is_online();
1244            project.set_online(public, cx);
1245        });
1246    }
1247
1248    fn project_path_for_path(
1249        &self,
1250        abs_path: &Path,
1251        visible: bool,
1252        cx: &mut ViewContext<Self>,
1253    ) -> Task<Result<(ModelHandle<Worktree>, ProjectPath)>> {
1254        let entry = self.project().update(cx, |project, cx| {
1255            project.find_or_create_local_worktree(abs_path, visible, cx)
1256        });
1257        cx.spawn(|_, cx| async move {
1258            let (worktree, path) = entry.await?;
1259            let worktree_id = worktree.read_with(&cx, |t, _| t.id());
1260            Ok((
1261                worktree,
1262                ProjectPath {
1263                    worktree_id,
1264                    path: path.into(),
1265                },
1266            ))
1267        })
1268    }
1269
1270    /// Returns the modal that was toggled closed if it was open.
1271    pub fn toggle_modal<V, F>(
1272        &mut self,
1273        cx: &mut ViewContext<Self>,
1274        add_view: F,
1275    ) -> Option<ViewHandle<V>>
1276    where
1277        V: 'static + View,
1278        F: FnOnce(&mut Self, &mut ViewContext<Self>) -> ViewHandle<V>,
1279    {
1280        cx.notify();
1281        // Whatever modal was visible is getting clobbered. If its the same type as V, then return
1282        // it. Otherwise, create a new modal and set it as active.
1283        let already_open_modal = self.modal.take().and_then(|modal| modal.downcast::<V>());
1284        if let Some(already_open_modal) = already_open_modal {
1285            cx.focus_self();
1286            Some(already_open_modal)
1287        } else {
1288            let modal = add_view(self, cx);
1289            cx.focus(&modal);
1290            self.modal = Some(modal.into());
1291            None
1292        }
1293    }
1294
1295    pub fn modal<V: 'static + View>(&self) -> Option<ViewHandle<V>> {
1296        self.modal
1297            .as_ref()
1298            .and_then(|modal| modal.clone().downcast::<V>())
1299    }
1300
1301    pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
1302        if self.modal.take().is_some() {
1303            cx.focus(&self.active_pane);
1304            cx.notify();
1305        }
1306    }
1307
1308    pub fn show_notification<V: Notification>(
1309        &mut self,
1310        id: usize,
1311        cx: &mut ViewContext<Self>,
1312        build_notification: impl FnOnce(&mut ViewContext<Self>) -> ViewHandle<V>,
1313    ) {
1314        let type_id = TypeId::of::<V>();
1315        if self
1316            .notifications
1317            .iter()
1318            .all(|(existing_type_id, existing_id, _)| {
1319                (*existing_type_id, *existing_id) != (type_id, id)
1320            })
1321        {
1322            let notification = build_notification(cx);
1323            cx.subscribe(&notification, move |this, handle, event, cx| {
1324                if handle.read(cx).should_dismiss_notification_on_event(event) {
1325                    this.dismiss_notification(type_id, id, cx);
1326                }
1327            })
1328            .detach();
1329            self.notifications
1330                .push((type_id, id, Box::new(notification)));
1331            cx.notify();
1332        }
1333    }
1334
1335    fn dismiss_notification(&mut self, type_id: TypeId, id: usize, cx: &mut ViewContext<Self>) {
1336        self.notifications
1337            .retain(|(existing_type_id, existing_id, _)| {
1338                if (*existing_type_id, *existing_id) == (type_id, id) {
1339                    cx.notify();
1340                    false
1341                } else {
1342                    true
1343                }
1344            });
1345    }
1346
1347    pub fn items<'a>(
1348        &'a self,
1349        cx: &'a AppContext,
1350    ) -> impl 'a + Iterator<Item = &Box<dyn ItemHandle>> {
1351        self.panes.iter().flat_map(|pane| pane.read(cx).items())
1352    }
1353
1354    pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
1355        self.items_of_type(cx).max_by_key(|item| item.id())
1356    }
1357
1358    pub fn items_of_type<'a, T: Item>(
1359        &'a self,
1360        cx: &'a AppContext,
1361    ) -> impl 'a + Iterator<Item = ViewHandle<T>> {
1362        self.panes
1363            .iter()
1364            .flat_map(|pane| pane.read(cx).items_of_type())
1365    }
1366
1367    pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
1368        self.active_pane().read(cx).active_item()
1369    }
1370
1371    fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
1372        self.active_item(cx).and_then(|item| item.project_path(cx))
1373    }
1374
1375    pub fn save_active_item(
1376        &mut self,
1377        force_name_change: bool,
1378        cx: &mut ViewContext<Self>,
1379    ) -> Task<Result<()>> {
1380        let project = self.project.clone();
1381        if let Some(item) = self.active_item(cx) {
1382            if !force_name_change && item.can_save(cx) {
1383                if item.has_conflict(cx.as_ref()) {
1384                    const CONFLICT_MESSAGE: &str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1385
1386                    let mut answer = cx.prompt(
1387                        PromptLevel::Warning,
1388                        CONFLICT_MESSAGE,
1389                        &["Overwrite", "Cancel"],
1390                    );
1391                    cx.spawn(|_, mut cx| async move {
1392                        let answer = answer.recv().await;
1393                        if answer == Some(0) {
1394                            cx.update(|cx| item.save(project, cx)).await?;
1395                        }
1396                        Ok(())
1397                    })
1398                } else {
1399                    item.save(project, cx)
1400                }
1401            } else if item.is_singleton(cx) {
1402                let worktree = self.worktrees(cx).next();
1403                let start_abs_path = worktree
1404                    .and_then(|w| w.read(cx).as_local())
1405                    .map_or(Path::new(""), |w| w.abs_path())
1406                    .to_path_buf();
1407                let mut abs_path = cx.prompt_for_new_path(&start_abs_path);
1408                cx.spawn(|_, mut cx| async move {
1409                    if let Some(abs_path) = abs_path.recv().await.flatten() {
1410                        cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
1411                    }
1412                    Ok(())
1413                })
1414            } else {
1415                Task::ready(Ok(()))
1416            }
1417        } else {
1418            Task::ready(Ok(()))
1419        }
1420    }
1421
1422    pub fn toggle_sidebar(&mut self, side: Side, cx: &mut ViewContext<Self>) {
1423        let sidebar = match side {
1424            Side::Left => &mut self.left_sidebar,
1425            Side::Right => &mut self.right_sidebar,
1426        };
1427        sidebar.update(cx, |sidebar, cx| {
1428            sidebar.set_open(!sidebar.is_open(), cx);
1429        });
1430        cx.focus_self();
1431        cx.notify();
1432    }
1433
1434    pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
1435        let sidebar = match action.side {
1436            Side::Left => &mut self.left_sidebar,
1437            Side::Right => &mut self.right_sidebar,
1438        };
1439        let active_item = sidebar.update(cx, |sidebar, cx| {
1440            if sidebar.is_open() && sidebar.active_item_ix() == action.item_index {
1441                sidebar.set_open(false, cx);
1442                None
1443            } else {
1444                sidebar.set_open(true, cx);
1445                sidebar.activate_item(action.item_index, cx);
1446                sidebar.active_item().cloned()
1447            }
1448        });
1449        if let Some(active_item) = active_item {
1450            if active_item.is_focused(cx) {
1451                cx.focus_self();
1452            } else {
1453                cx.focus(active_item.to_any());
1454            }
1455        } else {
1456            cx.focus_self();
1457        }
1458        cx.notify();
1459    }
1460
1461    pub fn toggle_sidebar_item_focus(
1462        &mut self,
1463        side: Side,
1464        item_index: usize,
1465        cx: &mut ViewContext<Self>,
1466    ) {
1467        let sidebar = match side {
1468            Side::Left => &mut self.left_sidebar,
1469            Side::Right => &mut self.right_sidebar,
1470        };
1471        let active_item = sidebar.update(cx, |sidebar, cx| {
1472            sidebar.set_open(true, cx);
1473            sidebar.activate_item(item_index, cx);
1474            sidebar.active_item().cloned()
1475        });
1476        if let Some(active_item) = active_item {
1477            if active_item.is_focused(cx) {
1478                cx.focus_self();
1479            } else {
1480                cx.focus(active_item.to_any());
1481            }
1482        }
1483        cx.notify();
1484    }
1485
1486    pub fn focus_center(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
1487        cx.focus_self();
1488        cx.notify();
1489    }
1490
1491    fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
1492        let pane = cx.add_view(Pane::new);
1493        let pane_id = pane.id();
1494        cx.subscribe(&pane, move |this, _, event, cx| {
1495            this.handle_pane_event(pane_id, event, cx)
1496        })
1497        .detach();
1498        self.panes.push(pane.clone());
1499        cx.focus(pane.clone());
1500        cx.emit(Event::PaneAdded(pane.clone()));
1501        pane
1502    }
1503
1504    pub fn add_item(&mut self, item: Box<dyn ItemHandle>, cx: &mut ViewContext<Self>) {
1505        let active_pane = self.active_pane().clone();
1506        Pane::add_item(self, &active_pane, item, true, true, None, cx);
1507    }
1508
1509    pub fn open_path(
1510        &mut self,
1511        path: impl Into<ProjectPath>,
1512        focus_item: bool,
1513        cx: &mut ViewContext<Self>,
1514    ) -> Task<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>> {
1515        let pane = self.active_pane().downgrade();
1516        let task = self.load_path(path.into(), cx);
1517        cx.spawn(|this, mut cx| async move {
1518            let (project_entry_id, build_item) = task.await?;
1519            let pane = pane
1520                .upgrade(&cx)
1521                .ok_or_else(|| anyhow!("pane was closed"))?;
1522            this.update(&mut cx, |this, cx| {
1523                Ok(Pane::open_item(
1524                    this,
1525                    pane,
1526                    project_entry_id,
1527                    focus_item,
1528                    cx,
1529                    build_item,
1530                ))
1531            })
1532        })
1533    }
1534
1535    pub(crate) fn load_path(
1536        &mut self,
1537        path: ProjectPath,
1538        cx: &mut ViewContext<Self>,
1539    ) -> Task<
1540        Result<(
1541            ProjectEntryId,
1542            impl 'static + FnOnce(&mut ViewContext<Pane>) -> Box<dyn ItemHandle>,
1543        )>,
1544    > {
1545        let project = self.project().clone();
1546        let project_item = project.update(cx, |project, cx| project.open_path(path, cx));
1547        cx.as_mut().spawn(|mut cx| async move {
1548            let (project_entry_id, project_item) = project_item.await?;
1549            let build_item = cx.update(|cx| {
1550                cx.default_global::<ProjectItemBuilders>()
1551                    .get(&project_item.model_type())
1552                    .ok_or_else(|| anyhow!("no item builder for project item"))
1553                    .cloned()
1554            })?;
1555            let build_item =
1556                move |cx: &mut ViewContext<Pane>| build_item(project, project_item, cx);
1557            Ok((project_entry_id, build_item))
1558        })
1559    }
1560
1561    pub fn open_project_item<T>(
1562        &mut self,
1563        project_item: ModelHandle<T::Item>,
1564        cx: &mut ViewContext<Self>,
1565    ) -> ViewHandle<T>
1566    where
1567        T: ProjectItem,
1568    {
1569        use project::Item as _;
1570
1571        let entry_id = project_item.read(cx).entry_id(cx);
1572        if let Some(item) = entry_id
1573            .and_then(|entry_id| self.active_pane().read(cx).item_for_entry(entry_id, cx))
1574            .and_then(|item| item.downcast())
1575        {
1576            self.activate_item(&item, cx);
1577            return item;
1578        }
1579
1580        let item = cx.add_view(|cx| T::for_project_item(self.project().clone(), project_item, cx));
1581        self.add_item(Box::new(item.clone()), cx);
1582        item
1583    }
1584
1585    pub fn activate_item(&mut self, item: &dyn ItemHandle, cx: &mut ViewContext<Self>) -> bool {
1586        let result = self.panes.iter().find_map(|pane| {
1587            pane.read(cx)
1588                .index_for_item(item)
1589                .map(|ix| (pane.clone(), ix))
1590        });
1591        if let Some((pane, ix)) = result {
1592            pane.update(cx, |pane, cx| pane.activate_item(ix, true, true, cx));
1593            true
1594        } else {
1595            false
1596        }
1597    }
1598
1599    fn activate_pane_at_index(&mut self, action: &ActivatePane, cx: &mut ViewContext<Self>) {
1600        let panes = self.center.panes();
1601        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
1602            cx.focus(pane);
1603        } else {
1604            self.split_pane(self.active_pane.clone(), SplitDirection::Right, cx);
1605        }
1606    }
1607
1608    pub fn activate_next_pane(&mut self, cx: &mut ViewContext<Self>) {
1609        let next_pane = {
1610            let panes = self.center.panes();
1611            let ix = panes
1612                .iter()
1613                .position(|pane| **pane == self.active_pane)
1614                .unwrap();
1615            let next_ix = (ix + 1) % panes.len();
1616            panes[next_ix].clone()
1617        };
1618        cx.focus(next_pane);
1619    }
1620
1621    pub fn activate_previous_pane(&mut self, cx: &mut ViewContext<Self>) {
1622        let prev_pane = {
1623            let panes = self.center.panes();
1624            let ix = panes
1625                .iter()
1626                .position(|pane| **pane == self.active_pane)
1627                .unwrap();
1628            let prev_ix = if ix == 0 { panes.len() - 1 } else { ix - 1 };
1629            panes[prev_ix].clone()
1630        };
1631        cx.focus(prev_pane);
1632    }
1633
1634    fn handle_pane_focused(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1635        if self.active_pane != pane {
1636            self.active_pane
1637                .update(cx, |pane, cx| pane.set_active(false, cx));
1638            self.active_pane = pane.clone();
1639            self.active_pane
1640                .update(cx, |pane, cx| pane.set_active(true, cx));
1641            self.status_bar.update(cx, |status_bar, cx| {
1642                status_bar.set_active_pane(&self.active_pane, cx);
1643            });
1644            self.active_item_path_changed(cx);
1645            cx.notify();
1646        }
1647
1648        self.update_followers(
1649            proto::update_followers::Variant::UpdateActiveView(proto::UpdateActiveView {
1650                id: self.active_item(cx).map(|item| item.id() as u64),
1651                leader_id: self.leader_for_pane(&pane).map(|id| id.0),
1652            }),
1653            cx,
1654        );
1655    }
1656
1657    fn handle_pane_event(
1658        &mut self,
1659        pane_id: usize,
1660        event: &pane::Event,
1661        cx: &mut ViewContext<Self>,
1662    ) {
1663        if let Some(pane) = self.pane(pane_id) {
1664            match event {
1665                pane::Event::Split(direction) => {
1666                    self.split_pane(pane, *direction, cx);
1667                }
1668                pane::Event::Remove => {
1669                    self.remove_pane(pane, cx);
1670                }
1671                pane::Event::Focused => {
1672                    self.handle_pane_focused(pane, cx);
1673                }
1674                pane::Event::ActivateItem { local } => {
1675                    if *local {
1676                        self.unfollow(&pane, cx);
1677                    }
1678                    if pane == self.active_pane {
1679                        self.active_item_path_changed(cx);
1680                    }
1681                }
1682                pane::Event::ChangeItemTitle => {
1683                    if pane == self.active_pane {
1684                        self.active_item_path_changed(cx);
1685                    }
1686                    self.update_window_edited(cx);
1687                }
1688                pane::Event::RemoveItem { item_id } => {
1689                    self.update_window_edited(cx);
1690                    if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(*item_id) {
1691                        if entry.get().id() == pane.id() {
1692                            entry.remove();
1693                        }
1694                    }
1695                }
1696            }
1697        } else {
1698            error!("pane {} not found", pane_id);
1699        }
1700    }
1701
1702    pub fn split_pane(
1703        &mut self,
1704        pane: ViewHandle<Pane>,
1705        direction: SplitDirection,
1706        cx: &mut ViewContext<Self>,
1707    ) -> Option<ViewHandle<Pane>> {
1708        pane.read(cx).active_item().map(|item| {
1709            let new_pane = self.add_pane(cx);
1710            if let Some(clone) = item.clone_on_split(cx.as_mut()) {
1711                Pane::add_item(self, &new_pane, clone, true, true, None, cx);
1712            }
1713            self.center.split(&pane, &new_pane, direction).unwrap();
1714            cx.notify();
1715            new_pane
1716        })
1717    }
1718
1719    fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1720        if self.center.remove(&pane).unwrap() {
1721            self.panes.retain(|p| p != &pane);
1722            cx.focus(self.panes.last().unwrap().clone());
1723            self.unfollow(&pane, cx);
1724            self.last_leaders_by_pane.remove(&pane.downgrade());
1725            for removed_item in pane.read(cx).items() {
1726                self.panes_by_item.remove(&removed_item.id());
1727            }
1728            cx.notify();
1729        } else {
1730            self.active_item_path_changed(cx);
1731        }
1732    }
1733
1734    pub fn panes(&self) -> &[ViewHandle<Pane>] {
1735        &self.panes
1736    }
1737
1738    fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1739        self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1740    }
1741
1742    pub fn active_pane(&self) -> &ViewHandle<Pane> {
1743        &self.active_pane
1744    }
1745
1746    fn project_remote_id_changed(&mut self, remote_id: Option<u64>, cx: &mut ViewContext<Self>) {
1747        if let Some(remote_id) = remote_id {
1748            self.remote_entity_subscription =
1749                Some(self.client.add_view_for_remote_entity(remote_id, cx));
1750        } else {
1751            self.remote_entity_subscription.take();
1752        }
1753    }
1754
1755    fn collaborator_left(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
1756        self.leader_state.followers.remove(&peer_id);
1757        if let Some(states_by_pane) = self.follower_states_by_leader.remove(&peer_id) {
1758            for state in states_by_pane.into_values() {
1759                for item in state.items_by_leader_view_id.into_values() {
1760                    if let FollowerItem::Loaded(item) = item {
1761                        item.set_leader_replica_id(None, cx);
1762                    }
1763                }
1764            }
1765        }
1766        cx.notify();
1767    }
1768
1769    pub fn toggle_follow(
1770        &mut self,
1771        ToggleFollow(leader_id): &ToggleFollow,
1772        cx: &mut ViewContext<Self>,
1773    ) -> Option<Task<Result<()>>> {
1774        let leader_id = *leader_id;
1775        let pane = self.active_pane().clone();
1776
1777        if let Some(prev_leader_id) = self.unfollow(&pane, cx) {
1778            if leader_id == prev_leader_id {
1779                return None;
1780            }
1781        }
1782
1783        self.last_leaders_by_pane
1784            .insert(pane.downgrade(), leader_id);
1785        self.follower_states_by_leader
1786            .entry(leader_id)
1787            .or_default()
1788            .insert(pane.clone(), Default::default());
1789        cx.notify();
1790
1791        let project_id = self.project.read(cx).remote_id()?;
1792        let request = self.client.request(proto::Follow {
1793            project_id,
1794            leader_id: leader_id.0,
1795        });
1796        Some(cx.spawn_weak(|this, mut cx| async move {
1797            let response = request.await?;
1798            if let Some(this) = this.upgrade(&cx) {
1799                this.update(&mut cx, |this, _| {
1800                    let state = this
1801                        .follower_states_by_leader
1802                        .get_mut(&leader_id)
1803                        .and_then(|states_by_pane| states_by_pane.get_mut(&pane))
1804                        .ok_or_else(|| anyhow!("following interrupted"))?;
1805                    state.active_view_id = response.active_view_id;
1806                    Ok::<_, anyhow::Error>(())
1807                })?;
1808                Self::add_views_from_leader(this, leader_id, vec![pane], response.views, &mut cx)
1809                    .await?;
1810            }
1811            Ok(())
1812        }))
1813    }
1814
1815    pub fn follow_next_collaborator(
1816        &mut self,
1817        _: &FollowNextCollaborator,
1818        cx: &mut ViewContext<Self>,
1819    ) -> Option<Task<Result<()>>> {
1820        let collaborators = self.project.read(cx).collaborators();
1821        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
1822            let mut collaborators = collaborators.keys().copied();
1823            for peer_id in collaborators.by_ref() {
1824                if peer_id == leader_id {
1825                    break;
1826                }
1827            }
1828            collaborators.next()
1829        } else if let Some(last_leader_id) =
1830            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
1831        {
1832            if collaborators.contains_key(last_leader_id) {
1833                Some(*last_leader_id)
1834            } else {
1835                None
1836            }
1837        } else {
1838            None
1839        };
1840
1841        next_leader_id
1842            .or_else(|| collaborators.keys().copied().next())
1843            .and_then(|leader_id| self.toggle_follow(&ToggleFollow(leader_id), cx))
1844    }
1845
1846    pub fn unfollow(
1847        &mut self,
1848        pane: &ViewHandle<Pane>,
1849        cx: &mut ViewContext<Self>,
1850    ) -> Option<PeerId> {
1851        for (leader_id, states_by_pane) in &mut self.follower_states_by_leader {
1852            let leader_id = *leader_id;
1853            if let Some(state) = states_by_pane.remove(pane) {
1854                for (_, item) in state.items_by_leader_view_id {
1855                    if let FollowerItem::Loaded(item) = item {
1856                        item.set_leader_replica_id(None, cx);
1857                    }
1858                }
1859
1860                if states_by_pane.is_empty() {
1861                    self.follower_states_by_leader.remove(&leader_id);
1862                    if let Some(project_id) = self.project.read(cx).remote_id() {
1863                        self.client
1864                            .send(proto::Unfollow {
1865                                project_id,
1866                                leader_id: leader_id.0,
1867                            })
1868                            .log_err();
1869                    }
1870                }
1871
1872                cx.notify();
1873                return Some(leader_id);
1874            }
1875        }
1876        None
1877    }
1878
1879    fn render_connection_status(&self, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1880        let theme = &cx.global::<Settings>().theme;
1881        match &*self.client.status().borrow() {
1882            client::Status::ConnectionError
1883            | client::Status::ConnectionLost
1884            | client::Status::Reauthenticating { .. }
1885            | client::Status::Reconnecting { .. }
1886            | client::Status::ReconnectionError { .. } => Some(
1887                Container::new(
1888                    Align::new(
1889                        ConstrainedBox::new(
1890                            Svg::new("icons/cloud_slash_12.svg")
1891                                .with_color(theme.workspace.titlebar.offline_icon.color)
1892                                .boxed(),
1893                        )
1894                        .with_width(theme.workspace.titlebar.offline_icon.width)
1895                        .boxed(),
1896                    )
1897                    .boxed(),
1898                )
1899                .with_style(theme.workspace.titlebar.offline_icon.container)
1900                .boxed(),
1901            ),
1902            client::Status::UpgradeRequired => Some(
1903                Label::new(
1904                    "Please update Zed to collaborate".to_string(),
1905                    theme.workspace.titlebar.outdated_warning.text.clone(),
1906                )
1907                .contained()
1908                .with_style(theme.workspace.titlebar.outdated_warning.container)
1909                .aligned()
1910                .boxed(),
1911            ),
1912            _ => None,
1913        }
1914    }
1915
1916    fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1917        let project = &self.project.read(cx);
1918        let replica_id = project.replica_id();
1919        let mut worktree_root_names = String::new();
1920        for (i, name) in project.worktree_root_names(cx).enumerate() {
1921            if i > 0 {
1922                worktree_root_names.push_str(", ");
1923            }
1924            worktree_root_names.push_str(name);
1925        }
1926
1927        // TODO: There should be a better system in place for this
1928        // (https://github.com/zed-industries/zed/issues/1290)
1929        let is_fullscreen = cx.window_is_fullscreen(cx.window_id());
1930        let container_theme = if is_fullscreen {
1931            let mut container_theme = theme.workspace.titlebar.container;
1932            container_theme.padding.left = container_theme.padding.right;
1933            container_theme
1934        } else {
1935            theme.workspace.titlebar.container
1936        };
1937
1938        ConstrainedBox::new(
1939            MouseEventHandler::new::<Self, _, _>(0, cx, |_, cx| {
1940                Container::new(
1941                    Stack::new()
1942                        .with_child(
1943                            Label::new(worktree_root_names, theme.workspace.titlebar.title.clone())
1944                                .aligned()
1945                                .left()
1946                                .boxed(),
1947                        )
1948                        .with_child(
1949                            Align::new(
1950                                Flex::row()
1951                                    .with_children(self.render_collaborators(theme, cx))
1952                                    .with_children(self.render_current_user(
1953                                        self.user_store.read(cx).current_user().as_ref(),
1954                                        replica_id,
1955                                        theme,
1956                                        cx,
1957                                    ))
1958                                    .with_children(self.render_connection_status(cx))
1959                                    .boxed(),
1960                            )
1961                            .right()
1962                            .boxed(),
1963                        )
1964                        .boxed(),
1965                )
1966                .with_style(container_theme)
1967                .boxed()
1968            })
1969            .on_click(MouseButton::Left, |event, cx| {
1970                if event.click_count == 2 {
1971                    cx.zoom_window(cx.window_id());
1972                }
1973            })
1974            .boxed(),
1975        )
1976        .with_height(theme.workspace.titlebar.height)
1977        .named("titlebar")
1978    }
1979
1980    fn active_item_path_changed(&mut self, cx: &mut ViewContext<Self>) {
1981        let active_entry = self.active_project_path(cx);
1982        self.project
1983            .update(cx, |project, cx| project.set_active_path(active_entry, cx));
1984        self.update_window_title(cx);
1985    }
1986
1987    fn update_window_title(&mut self, cx: &mut ViewContext<Self>) {
1988        let mut title = String::new();
1989        let project = self.project().read(cx);
1990        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
1991            let filename = path
1992                .path
1993                .file_name()
1994                .map(|s| s.to_string_lossy())
1995                .or_else(|| {
1996                    Some(Cow::Borrowed(
1997                        project
1998                            .worktree_for_id(path.worktree_id, cx)?
1999                            .read(cx)
2000                            .root_name(),
2001                    ))
2002                });
2003            if let Some(filename) = filename {
2004                title.push_str(filename.as_ref());
2005                title.push_str("");
2006            }
2007        }
2008        for (i, name) in project.worktree_root_names(cx).enumerate() {
2009            if i > 0 {
2010                title.push_str(", ");
2011            }
2012            title.push_str(name);
2013        }
2014        if title.is_empty() {
2015            title = "empty project".to_string();
2016        }
2017        cx.set_window_title(&title);
2018    }
2019
2020    fn update_window_edited(&mut self, cx: &mut ViewContext<Self>) {
2021        let is_edited = !self.project.read(cx).is_read_only()
2022            && self
2023                .items(cx)
2024                .any(|item| item.has_conflict(cx) || item.is_dirty(cx));
2025        if is_edited != self.window_edited {
2026            self.window_edited = is_edited;
2027            cx.set_window_edited(self.window_edited)
2028        }
2029    }
2030
2031    fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
2032        let mut collaborators = self
2033            .project
2034            .read(cx)
2035            .collaborators()
2036            .values()
2037            .cloned()
2038            .collect::<Vec<_>>();
2039        collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
2040        collaborators
2041            .into_iter()
2042            .filter_map(|collaborator| {
2043                Some(self.render_avatar(
2044                    collaborator.user.avatar.clone()?,
2045                    collaborator.replica_id,
2046                    Some((collaborator.peer_id, &collaborator.user.github_login)),
2047                    theme,
2048                    cx,
2049                ))
2050            })
2051            .collect()
2052    }
2053
2054    fn render_current_user(
2055        &self,
2056        user: Option<&Arc<User>>,
2057        replica_id: ReplicaId,
2058        theme: &Theme,
2059        cx: &mut RenderContext<Self>,
2060    ) -> Option<ElementBox> {
2061        let status = *self.client.status().borrow();
2062        if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
2063            Some(self.render_avatar(avatar, replica_id, None, theme, cx))
2064        } else if matches!(status, client::Status::UpgradeRequired) {
2065            None
2066        } else {
2067            Some(
2068                MouseEventHandler::new::<Authenticate, _, _>(0, cx, |state, _| {
2069                    let style = theme
2070                        .workspace
2071                        .titlebar
2072                        .sign_in_prompt
2073                        .style_for(state, false);
2074                    Label::new("Sign in".to_string(), style.text.clone())
2075                        .contained()
2076                        .with_style(style.container)
2077                        .boxed()
2078                })
2079                .on_click(MouseButton::Left, |_, cx| cx.dispatch_action(Authenticate))
2080                .with_cursor_style(CursorStyle::PointingHand)
2081                .aligned()
2082                .boxed(),
2083            )
2084        }
2085    }
2086
2087    fn render_avatar(
2088        &self,
2089        avatar: Arc<ImageData>,
2090        replica_id: ReplicaId,
2091        peer: Option<(PeerId, &str)>,
2092        theme: &Theme,
2093        cx: &mut RenderContext<Self>,
2094    ) -> ElementBox {
2095        let replica_color = theme.editor.replica_selection_style(replica_id).cursor;
2096        let is_followed = peer.map_or(false, |(peer_id, _)| {
2097            self.follower_states_by_leader.contains_key(&peer_id)
2098        });
2099        let mut avatar_style = theme.workspace.titlebar.avatar;
2100        if is_followed {
2101            avatar_style.border = Border::all(1.0, replica_color);
2102        }
2103        let content = Stack::new()
2104            .with_child(
2105                Image::new(avatar)
2106                    .with_style(avatar_style)
2107                    .constrained()
2108                    .with_width(theme.workspace.titlebar.avatar_width)
2109                    .aligned()
2110                    .boxed(),
2111            )
2112            .with_child(
2113                AvatarRibbon::new(replica_color)
2114                    .constrained()
2115                    .with_width(theme.workspace.titlebar.avatar_ribbon.width)
2116                    .with_height(theme.workspace.titlebar.avatar_ribbon.height)
2117                    .aligned()
2118                    .bottom()
2119                    .boxed(),
2120            )
2121            .constrained()
2122            .with_width(theme.workspace.titlebar.avatar_width)
2123            .contained()
2124            .with_margin_left(theme.workspace.titlebar.avatar_margin)
2125            .boxed();
2126
2127        if let Some((peer_id, peer_github_login)) = peer {
2128            MouseEventHandler::new::<ToggleFollow, _, _>(replica_id.into(), cx, move |_, _| content)
2129                .with_cursor_style(CursorStyle::PointingHand)
2130                .on_click(MouseButton::Left, move |_, cx| {
2131                    cx.dispatch_action(ToggleFollow(peer_id))
2132                })
2133                .with_tooltip::<ToggleFollow, _>(
2134                    peer_id.0 as usize,
2135                    if is_followed {
2136                        format!("Unfollow {}", peer_github_login)
2137                    } else {
2138                        format!("Follow {}", peer_github_login)
2139                    },
2140                    Some(Box::new(FollowNextCollaborator)),
2141                    theme.tooltip.clone(),
2142                    cx,
2143                )
2144                .boxed()
2145        } else {
2146            content
2147        }
2148    }
2149
2150    fn render_disconnected_overlay(&self, cx: &mut RenderContext<Workspace>) -> Option<ElementBox> {
2151        if self.project.read(cx).is_read_only() {
2152            Some(
2153                MouseEventHandler::new::<Workspace, _, _>(0, cx, |_, cx| {
2154                    let theme = &cx.global::<Settings>().theme;
2155                    Label::new(
2156                        "Your connection to the remote project has been lost.".to_string(),
2157                        theme.workspace.disconnected_overlay.text.clone(),
2158                    )
2159                    .aligned()
2160                    .contained()
2161                    .with_style(theme.workspace.disconnected_overlay.container)
2162                    .boxed()
2163                })
2164                .capture_all()
2165                .boxed(),
2166            )
2167        } else {
2168            None
2169        }
2170    }
2171
2172    fn render_notifications(&self, theme: &theme::Workspace) -> Option<ElementBox> {
2173        if self.notifications.is_empty() {
2174            None
2175        } else {
2176            Some(
2177                Flex::column()
2178                    .with_children(self.notifications.iter().map(|(_, _, notification)| {
2179                        ChildView::new(notification.as_ref())
2180                            .contained()
2181                            .with_style(theme.notification)
2182                            .boxed()
2183                    }))
2184                    .constrained()
2185                    .with_width(theme.notifications.width)
2186                    .contained()
2187                    .with_style(theme.notifications.container)
2188                    .aligned()
2189                    .bottom()
2190                    .right()
2191                    .boxed(),
2192            )
2193        }
2194    }
2195
2196    // RPC handlers
2197
2198    async fn handle_follow(
2199        this: ViewHandle<Self>,
2200        envelope: TypedEnvelope<proto::Follow>,
2201        _: Arc<Client>,
2202        mut cx: AsyncAppContext,
2203    ) -> Result<proto::FollowResponse> {
2204        this.update(&mut cx, |this, cx| {
2205            this.leader_state
2206                .followers
2207                .insert(envelope.original_sender_id()?);
2208
2209            let active_view_id = this
2210                .active_item(cx)
2211                .and_then(|i| i.to_followable_item_handle(cx))
2212                .map(|i| i.id() as u64);
2213            Ok(proto::FollowResponse {
2214                active_view_id,
2215                views: this
2216                    .panes()
2217                    .iter()
2218                    .flat_map(|pane| {
2219                        let leader_id = this.leader_for_pane(pane).map(|id| id.0);
2220                        pane.read(cx).items().filter_map({
2221                            let cx = &cx;
2222                            move |item| {
2223                                let id = item.id() as u64;
2224                                let item = item.to_followable_item_handle(cx)?;
2225                                let variant = item.to_state_proto(cx)?;
2226                                Some(proto::View {
2227                                    id,
2228                                    leader_id,
2229                                    variant: Some(variant),
2230                                })
2231                            }
2232                        })
2233                    })
2234                    .collect(),
2235            })
2236        })
2237    }
2238
2239    async fn handle_unfollow(
2240        this: ViewHandle<Self>,
2241        envelope: TypedEnvelope<proto::Unfollow>,
2242        _: Arc<Client>,
2243        mut cx: AsyncAppContext,
2244    ) -> Result<()> {
2245        this.update(&mut cx, |this, _| {
2246            this.leader_state
2247                .followers
2248                .remove(&envelope.original_sender_id()?);
2249            Ok(())
2250        })
2251    }
2252
2253    async fn handle_update_followers(
2254        this: ViewHandle<Self>,
2255        envelope: TypedEnvelope<proto::UpdateFollowers>,
2256        _: Arc<Client>,
2257        mut cx: AsyncAppContext,
2258    ) -> Result<()> {
2259        let leader_id = envelope.original_sender_id()?;
2260        match envelope
2261            .payload
2262            .variant
2263            .ok_or_else(|| anyhow!("invalid update"))?
2264        {
2265            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
2266                this.update(&mut cx, |this, cx| {
2267                    this.update_leader_state(leader_id, cx, |state, _| {
2268                        state.active_view_id = update_active_view.id;
2269                    });
2270                    Ok::<_, anyhow::Error>(())
2271                })
2272            }
2273            proto::update_followers::Variant::UpdateView(update_view) => {
2274                this.update(&mut cx, |this, cx| {
2275                    let variant = update_view
2276                        .variant
2277                        .ok_or_else(|| anyhow!("missing update view variant"))?;
2278                    this.update_leader_state(leader_id, cx, |state, cx| {
2279                        let variant = variant.clone();
2280                        match state
2281                            .items_by_leader_view_id
2282                            .entry(update_view.id)
2283                            .or_insert(FollowerItem::Loading(Vec::new()))
2284                        {
2285                            FollowerItem::Loaded(item) => {
2286                                item.apply_update_proto(variant, cx).log_err();
2287                            }
2288                            FollowerItem::Loading(updates) => updates.push(variant),
2289                        }
2290                    });
2291                    Ok(())
2292                })
2293            }
2294            proto::update_followers::Variant::CreateView(view) => {
2295                let panes = this.read_with(&cx, |this, _| {
2296                    this.follower_states_by_leader
2297                        .get(&leader_id)
2298                        .into_iter()
2299                        .flat_map(|states_by_pane| states_by_pane.keys())
2300                        .cloned()
2301                        .collect()
2302                });
2303                Self::add_views_from_leader(this.clone(), leader_id, panes, vec![view], &mut cx)
2304                    .await?;
2305                Ok(())
2306            }
2307        }
2308        .log_err();
2309
2310        Ok(())
2311    }
2312
2313    async fn add_views_from_leader(
2314        this: ViewHandle<Self>,
2315        leader_id: PeerId,
2316        panes: Vec<ViewHandle<Pane>>,
2317        views: Vec<proto::View>,
2318        cx: &mut AsyncAppContext,
2319    ) -> Result<()> {
2320        let project = this.read_with(cx, |this, _| this.project.clone());
2321        let replica_id = project
2322            .read_with(cx, |project, _| {
2323                project
2324                    .collaborators()
2325                    .get(&leader_id)
2326                    .map(|c| c.replica_id)
2327            })
2328            .ok_or_else(|| anyhow!("no such collaborator {}", leader_id))?;
2329
2330        let item_builders = cx.update(|cx| {
2331            cx.default_global::<FollowableItemBuilders>()
2332                .values()
2333                .map(|b| b.0)
2334                .collect::<Vec<_>>()
2335        });
2336
2337        let mut item_tasks_by_pane = HashMap::default();
2338        for pane in panes {
2339            let mut item_tasks = Vec::new();
2340            let mut leader_view_ids = Vec::new();
2341            for view in &views {
2342                let mut variant = view.variant.clone();
2343                if variant.is_none() {
2344                    Err(anyhow!("missing variant"))?;
2345                }
2346                for build_item in &item_builders {
2347                    let task =
2348                        cx.update(|cx| build_item(pane.clone(), project.clone(), &mut variant, cx));
2349                    if let Some(task) = task {
2350                        item_tasks.push(task);
2351                        leader_view_ids.push(view.id);
2352                        break;
2353                    } else {
2354                        assert!(variant.is_some());
2355                    }
2356                }
2357            }
2358
2359            item_tasks_by_pane.insert(pane, (item_tasks, leader_view_ids));
2360        }
2361
2362        for (pane, (item_tasks, leader_view_ids)) in item_tasks_by_pane {
2363            let items = futures::future::try_join_all(item_tasks).await?;
2364            this.update(cx, |this, cx| {
2365                let state = this
2366                    .follower_states_by_leader
2367                    .get_mut(&leader_id)?
2368                    .get_mut(&pane)?;
2369
2370                for (id, item) in leader_view_ids.into_iter().zip(items) {
2371                    item.set_leader_replica_id(Some(replica_id), cx);
2372                    match state.items_by_leader_view_id.entry(id) {
2373                        hash_map::Entry::Occupied(e) => {
2374                            let e = e.into_mut();
2375                            if let FollowerItem::Loading(updates) = e {
2376                                for update in updates.drain(..) {
2377                                    item.apply_update_proto(update, cx)
2378                                        .context("failed to apply view update")
2379                                        .log_err();
2380                                }
2381                            }
2382                            *e = FollowerItem::Loaded(item);
2383                        }
2384                        hash_map::Entry::Vacant(e) => {
2385                            e.insert(FollowerItem::Loaded(item));
2386                        }
2387                    }
2388                }
2389
2390                Some(())
2391            });
2392        }
2393        this.update(cx, |this, cx| this.leader_updated(leader_id, cx));
2394
2395        Ok(())
2396    }
2397
2398    fn update_followers(
2399        &self,
2400        update: proto::update_followers::Variant,
2401        cx: &AppContext,
2402    ) -> Option<()> {
2403        let project_id = self.project.read(cx).remote_id()?;
2404        if !self.leader_state.followers.is_empty() {
2405            self.client
2406                .send(proto::UpdateFollowers {
2407                    project_id,
2408                    follower_ids: self.leader_state.followers.iter().map(|f| f.0).collect(),
2409                    variant: Some(update),
2410                })
2411                .log_err();
2412        }
2413        None
2414    }
2415
2416    pub fn leader_for_pane(&self, pane: &ViewHandle<Pane>) -> Option<PeerId> {
2417        self.follower_states_by_leader
2418            .iter()
2419            .find_map(|(leader_id, state)| {
2420                if state.contains_key(pane) {
2421                    Some(*leader_id)
2422                } else {
2423                    None
2424                }
2425            })
2426    }
2427
2428    fn update_leader_state(
2429        &mut self,
2430        leader_id: PeerId,
2431        cx: &mut ViewContext<Self>,
2432        mut update_fn: impl FnMut(&mut FollowerState, &mut ViewContext<Self>),
2433    ) {
2434        for (_, state) in self
2435            .follower_states_by_leader
2436            .get_mut(&leader_id)
2437            .into_iter()
2438            .flatten()
2439        {
2440            update_fn(state, cx);
2441        }
2442        self.leader_updated(leader_id, cx);
2443    }
2444
2445    fn leader_updated(&mut self, leader_id: PeerId, cx: &mut ViewContext<Self>) -> Option<()> {
2446        let mut items_to_add = Vec::new();
2447        for (pane, state) in self.follower_states_by_leader.get(&leader_id)? {
2448            if let Some(FollowerItem::Loaded(item)) = state
2449                .active_view_id
2450                .and_then(|id| state.items_by_leader_view_id.get(&id))
2451            {
2452                items_to_add.push((pane.clone(), item.boxed_clone()));
2453            }
2454        }
2455
2456        for (pane, item) in items_to_add {
2457            Pane::add_item(self, &pane, item.boxed_clone(), false, false, None, cx);
2458            if pane == self.active_pane {
2459                pane.update(cx, |pane, cx| pane.focus_active_item(cx));
2460            }
2461            cx.notify();
2462        }
2463        None
2464    }
2465
2466    pub fn on_window_activation_changed(&mut self, active: bool, cx: &mut ViewContext<Self>) {
2467        if !active {
2468            for pane in &self.panes {
2469                pane.update(cx, |pane, cx| {
2470                    if let Some(item) = pane.active_item() {
2471                        item.workspace_deactivated(cx);
2472                    }
2473                    if matches!(
2474                        cx.global::<Settings>().autosave,
2475                        Autosave::OnWindowChange | Autosave::OnFocusChange
2476                    ) {
2477                        for item in pane.items() {
2478                            Pane::autosave_item(item.as_ref(), self.project.clone(), cx)
2479                                .detach_and_log_err(cx);
2480                        }
2481                    }
2482                });
2483            }
2484        }
2485    }
2486}
2487
2488impl Entity for Workspace {
2489    type Event = Event;
2490}
2491
2492impl View for Workspace {
2493    fn ui_name() -> &'static str {
2494        "Workspace"
2495    }
2496
2497    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
2498        let theme = cx.global::<Settings>().theme.clone();
2499        Stack::new()
2500            .with_child(
2501                Flex::column()
2502                    .with_child(self.render_titlebar(&theme, cx))
2503                    .with_child(
2504                        Stack::new()
2505                            .with_child({
2506                                Flex::row()
2507                                    .with_children(
2508                                        if self.left_sidebar.read(cx).active_item().is_some() {
2509                                            Some(
2510                                                ChildView::new(&self.left_sidebar)
2511                                                    .flex(0.8, false)
2512                                                    .boxed(),
2513                                            )
2514                                        } else {
2515                                            None
2516                                        },
2517                                    )
2518                                    .with_child(
2519                                        FlexItem::new(self.center.render(
2520                                            &theme,
2521                                            &self.follower_states_by_leader,
2522                                            self.project.read(cx).collaborators(),
2523                                        ))
2524                                        .flex(1., true)
2525                                        .boxed(),
2526                                    )
2527                                    .with_children(
2528                                        if self.right_sidebar.read(cx).active_item().is_some() {
2529                                            Some(
2530                                                ChildView::new(&self.right_sidebar)
2531                                                    .flex(0.8, false)
2532                                                    .boxed(),
2533                                            )
2534                                        } else {
2535                                            None
2536                                        },
2537                                    )
2538                                    .boxed()
2539                            })
2540                            .with_children(self.modal.as_ref().map(|m| {
2541                                ChildView::new(m)
2542                                    .contained()
2543                                    .with_style(theme.workspace.modal)
2544                                    .aligned()
2545                                    .top()
2546                                    .boxed()
2547                            }))
2548                            .with_children(self.render_notifications(&theme.workspace))
2549                            .flex(1.0, true)
2550                            .boxed(),
2551                    )
2552                    .with_child(ChildView::new(&self.status_bar).boxed())
2553                    .contained()
2554                    .with_background_color(theme.workspace.background)
2555                    .boxed(),
2556            )
2557            .with_children(DragAndDrop::render(cx))
2558            .with_children(self.render_disconnected_overlay(cx))
2559            .named("workspace")
2560    }
2561
2562    fn on_focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
2563        if cx.is_self_focused() {
2564            cx.focus(&self.active_pane);
2565        }
2566    }
2567}
2568
2569pub trait WorkspaceHandle {
2570    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
2571}
2572
2573impl WorkspaceHandle for ViewHandle<Workspace> {
2574    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
2575        self.read(cx)
2576            .worktrees(cx)
2577            .flat_map(|worktree| {
2578                let worktree_id = worktree.read(cx).id();
2579                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
2580                    worktree_id,
2581                    path: f.path.clone(),
2582                })
2583            })
2584            .collect::<Vec<_>>()
2585    }
2586}
2587
2588pub struct AvatarRibbon {
2589    color: Color,
2590}
2591
2592impl AvatarRibbon {
2593    pub fn new(color: Color) -> AvatarRibbon {
2594        AvatarRibbon { color }
2595    }
2596}
2597
2598impl Element for AvatarRibbon {
2599    type LayoutState = ();
2600
2601    type PaintState = ();
2602
2603    fn layout(
2604        &mut self,
2605        constraint: gpui::SizeConstraint,
2606        _: &mut gpui::LayoutContext,
2607    ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
2608        (constraint.max, ())
2609    }
2610
2611    fn paint(
2612        &mut self,
2613        bounds: gpui::geometry::rect::RectF,
2614        _: gpui::geometry::rect::RectF,
2615        _: &mut Self::LayoutState,
2616        cx: &mut gpui::PaintContext,
2617    ) -> Self::PaintState {
2618        let mut path = PathBuilder::new();
2619        path.reset(bounds.lower_left());
2620        path.curve_to(
2621            bounds.origin() + vec2f(bounds.height(), 0.),
2622            bounds.origin(),
2623        );
2624        path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
2625        path.curve_to(bounds.lower_right(), bounds.upper_right());
2626        path.line_to(bounds.lower_left());
2627        cx.scene.push_path(path.build(self.color, None));
2628    }
2629
2630    fn dispatch_event(
2631        &mut self,
2632        _: &gpui::Event,
2633        _: RectF,
2634        _: RectF,
2635        _: &mut Self::LayoutState,
2636        _: &mut Self::PaintState,
2637        _: &mut gpui::EventContext,
2638    ) -> bool {
2639        false
2640    }
2641
2642    fn rect_for_text_range(
2643        &self,
2644        _: Range<usize>,
2645        _: RectF,
2646        _: RectF,
2647        _: &Self::LayoutState,
2648        _: &Self::PaintState,
2649        _: &gpui::MeasurementContext,
2650    ) -> Option<RectF> {
2651        None
2652    }
2653
2654    fn debug(
2655        &self,
2656        bounds: gpui::geometry::rect::RectF,
2657        _: &Self::LayoutState,
2658        _: &Self::PaintState,
2659        _: &gpui::DebugContext,
2660    ) -> gpui::json::Value {
2661        json::json!({
2662            "type": "AvatarRibbon",
2663            "bounds": bounds.to_json(),
2664            "color": self.color.to_json(),
2665        })
2666    }
2667}
2668
2669impl std::fmt::Debug for OpenPaths {
2670    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2671        f.debug_struct("OpenPaths")
2672            .field("paths", &self.paths)
2673            .finish()
2674    }
2675}
2676
2677fn open(_: &Open, cx: &mut MutableAppContext) {
2678    let mut paths = cx.prompt_for_paths(PathPromptOptions {
2679        files: true,
2680        directories: true,
2681        multiple: true,
2682    });
2683    cx.spawn(|mut cx| async move {
2684        if let Some(paths) = paths.recv().await.flatten() {
2685            cx.update(|cx| cx.dispatch_global_action(OpenPaths { paths }));
2686        }
2687    })
2688    .detach();
2689}
2690
2691pub struct WorkspaceCreated(WeakViewHandle<Workspace>);
2692
2693pub fn activate_workspace_for_project(
2694    cx: &mut MutableAppContext,
2695    predicate: impl Fn(&mut Project, &mut ModelContext<Project>) -> bool,
2696) -> Option<ViewHandle<Workspace>> {
2697    for window_id in cx.window_ids().collect::<Vec<_>>() {
2698        if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
2699            let project = workspace_handle.read(cx).project.clone();
2700            if project.update(cx, &predicate) {
2701                cx.activate_window(window_id);
2702                return Some(workspace_handle);
2703            }
2704        }
2705    }
2706    None
2707}
2708
2709#[allow(clippy::type_complexity)]
2710pub fn open_paths(
2711    abs_paths: &[PathBuf],
2712    app_state: &Arc<AppState>,
2713    cx: &mut MutableAppContext,
2714) -> Task<(
2715    ViewHandle<Workspace>,
2716    Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>,
2717)> {
2718    log::info!("open paths {:?}", abs_paths);
2719
2720    // Open paths in existing workspace if possible
2721    let existing =
2722        activate_workspace_for_project(cx, |project, cx| project.contains_paths(abs_paths, cx));
2723
2724    let app_state = app_state.clone();
2725    let abs_paths = abs_paths.to_vec();
2726    cx.spawn(|mut cx| async move {
2727        let mut new_project = None;
2728        let workspace = if let Some(existing) = existing {
2729            existing
2730        } else {
2731            let contains_directory =
2732                futures::future::join_all(abs_paths.iter().map(|path| app_state.fs.is_file(path)))
2733                    .await
2734                    .contains(&false);
2735
2736            cx.add_window((app_state.build_window_options)(), |cx| {
2737                let project = Project::local(
2738                    false,
2739                    app_state.client.clone(),
2740                    app_state.user_store.clone(),
2741                    app_state.project_store.clone(),
2742                    app_state.languages.clone(),
2743                    app_state.fs.clone(),
2744                    cx,
2745                );
2746                new_project = Some(project.clone());
2747                let mut workspace = Workspace::new(project, cx);
2748                (app_state.initialize_workspace)(&mut workspace, &app_state, cx);
2749                if contains_directory {
2750                    workspace.toggle_sidebar(Side::Left, cx);
2751                }
2752                workspace
2753            })
2754            .1
2755        };
2756
2757        let items = workspace
2758            .update(&mut cx, |workspace, cx| {
2759                workspace.open_paths(abs_paths, true, cx)
2760            })
2761            .await;
2762
2763        if let Some(project) = new_project {
2764            project
2765                .update(&mut cx, |project, cx| project.restore_state(cx))
2766                .await
2767                .log_err();
2768        }
2769
2770        (workspace, items)
2771    })
2772}
2773
2774pub fn join_project(
2775    contact: Arc<Contact>,
2776    project_index: usize,
2777    app_state: &Arc<AppState>,
2778    cx: &mut MutableAppContext,
2779) {
2780    let project_id = contact.projects[project_index].id;
2781
2782    for window_id in cx.window_ids().collect::<Vec<_>>() {
2783        if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
2784            if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
2785                cx.activate_window(window_id);
2786                return;
2787            }
2788        }
2789    }
2790
2791    cx.add_window((app_state.build_window_options)(), |cx| {
2792        WaitingRoom::new(contact, project_index, app_state.clone(), cx)
2793    });
2794}
2795
2796fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
2797    let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
2798        let mut workspace = Workspace::new(
2799            Project::local(
2800                false,
2801                app_state.client.clone(),
2802                app_state.user_store.clone(),
2803                app_state.project_store.clone(),
2804                app_state.languages.clone(),
2805                app_state.fs.clone(),
2806                cx,
2807            ),
2808            cx,
2809        );
2810        (app_state.initialize_workspace)(&mut workspace, app_state, cx);
2811        workspace
2812    });
2813    cx.dispatch_action_at(window_id, workspace.id(), NewFile);
2814}
2815
2816#[cfg(test)]
2817mod tests {
2818    use std::cell::Cell;
2819
2820    use super::*;
2821    use gpui::{executor::Deterministic, ModelHandle, TestAppContext, ViewContext};
2822    use project::{FakeFs, Project, ProjectEntryId};
2823    use serde_json::json;
2824
2825    #[gpui::test]
2826    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
2827        cx.foreground().forbid_parking();
2828        Settings::test_async(cx);
2829
2830        let fs = FakeFs::new(cx.background());
2831        let project = Project::test(fs, [], cx).await;
2832        let (_, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2833
2834        // Adding an item with no ambiguity renders the tab without detail.
2835        let item1 = cx.add_view(&workspace, |_| {
2836            let mut item = TestItem::new();
2837            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
2838            item
2839        });
2840        workspace.update(cx, |workspace, cx| {
2841            workspace.add_item(Box::new(item1.clone()), cx);
2842        });
2843        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), None));
2844
2845        // Adding an item that creates ambiguity increases the level of detail on
2846        // both tabs.
2847        let item2 = cx.add_view(&workspace, |_| {
2848            let mut item = TestItem::new();
2849            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
2850            item
2851        });
2852        workspace.update(cx, |workspace, cx| {
2853            workspace.add_item(Box::new(item2.clone()), cx);
2854        });
2855        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2856        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2857
2858        // Adding an item that creates ambiguity increases the level of detail only
2859        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
2860        // we stop at the highest detail available.
2861        let item3 = cx.add_view(&workspace, |_| {
2862            let mut item = TestItem::new();
2863            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
2864            item
2865        });
2866        workspace.update(cx, |workspace, cx| {
2867            workspace.add_item(Box::new(item3.clone()), cx);
2868        });
2869        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2870        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
2871        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
2872    }
2873
2874    #[gpui::test]
2875    async fn test_tracking_active_path(cx: &mut TestAppContext) {
2876        cx.foreground().forbid_parking();
2877        Settings::test_async(cx);
2878        let fs = FakeFs::new(cx.background());
2879        fs.insert_tree(
2880            "/root1",
2881            json!({
2882                "one.txt": "",
2883                "two.txt": "",
2884            }),
2885        )
2886        .await;
2887        fs.insert_tree(
2888            "/root2",
2889            json!({
2890                "three.txt": "",
2891            }),
2892        )
2893        .await;
2894
2895        let project = Project::test(fs, ["root1".as_ref()], cx).await;
2896        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2897        let worktree_id = project.read_with(cx, |project, cx| {
2898            project.worktrees(cx).next().unwrap().read(cx).id()
2899        });
2900
2901        let item1 = cx.add_view(&workspace, |_| {
2902            let mut item = TestItem::new();
2903            item.project_path = Some((worktree_id, "one.txt").into());
2904            item
2905        });
2906        let item2 = cx.add_view(&workspace, |_| {
2907            let mut item = TestItem::new();
2908            item.project_path = Some((worktree_id, "two.txt").into());
2909            item
2910        });
2911
2912        // Add an item to an empty pane
2913        workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item1), cx));
2914        project.read_with(cx, |project, cx| {
2915            assert_eq!(
2916                project.active_entry(),
2917                project
2918                    .entry_for_path(&(worktree_id, "one.txt").into(), cx)
2919                    .map(|e| e.id)
2920            );
2921        });
2922        assert_eq!(
2923            cx.current_window_title(window_id).as_deref(),
2924            Some("one.txt — root1")
2925        );
2926
2927        // Add a second item to a non-empty pane
2928        workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item2), cx));
2929        assert_eq!(
2930            cx.current_window_title(window_id).as_deref(),
2931            Some("two.txt — root1")
2932        );
2933        project.read_with(cx, |project, cx| {
2934            assert_eq!(
2935                project.active_entry(),
2936                project
2937                    .entry_for_path(&(worktree_id, "two.txt").into(), cx)
2938                    .map(|e| e.id)
2939            );
2940        });
2941
2942        // Close the active item
2943        workspace
2944            .update(cx, |workspace, cx| {
2945                Pane::close_active_item(workspace, &Default::default(), cx).unwrap()
2946            })
2947            .await
2948            .unwrap();
2949        assert_eq!(
2950            cx.current_window_title(window_id).as_deref(),
2951            Some("one.txt — root1")
2952        );
2953        project.read_with(cx, |project, cx| {
2954            assert_eq!(
2955                project.active_entry(),
2956                project
2957                    .entry_for_path(&(worktree_id, "one.txt").into(), cx)
2958                    .map(|e| e.id)
2959            );
2960        });
2961
2962        // Add a project folder
2963        project
2964            .update(cx, |project, cx| {
2965                project.find_or_create_local_worktree("/root2", true, cx)
2966            })
2967            .await
2968            .unwrap();
2969        assert_eq!(
2970            cx.current_window_title(window_id).as_deref(),
2971            Some("one.txt — root1, root2")
2972        );
2973
2974        // Remove a project folder
2975        project.update(cx, |project, cx| {
2976            project.remove_worktree(worktree_id, cx);
2977        });
2978        assert_eq!(
2979            cx.current_window_title(window_id).as_deref(),
2980            Some("one.txt — root2")
2981        );
2982    }
2983
2984    #[gpui::test]
2985    async fn test_close_window(cx: &mut TestAppContext) {
2986        cx.foreground().forbid_parking();
2987        Settings::test_async(cx);
2988        let fs = FakeFs::new(cx.background());
2989        fs.insert_tree("/root", json!({ "one": "" })).await;
2990
2991        let project = Project::test(fs, ["root".as_ref()], cx).await;
2992        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2993
2994        // When there are no dirty items, there's nothing to do.
2995        let item1 = cx.add_view(&workspace, |_| TestItem::new());
2996        workspace.update(cx, |w, cx| w.add_item(Box::new(item1.clone()), cx));
2997        let task = workspace.update(cx, |w, cx| w.prepare_to_close(cx));
2998        assert!(task.await.unwrap());
2999
3000        // When there are dirty untitled items, prompt to save each one. If the user
3001        // cancels any prompt, then abort.
3002        let item2 = cx.add_view(&workspace, |_| {
3003            let mut item = TestItem::new();
3004            item.is_dirty = true;
3005            item
3006        });
3007        let item3 = cx.add_view(&workspace, |_| {
3008            let mut item = TestItem::new();
3009            item.is_dirty = true;
3010            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3011            item
3012        });
3013        workspace.update(cx, |w, cx| {
3014            w.add_item(Box::new(item2.clone()), cx);
3015            w.add_item(Box::new(item3.clone()), cx);
3016        });
3017        let task = workspace.update(cx, |w, cx| w.prepare_to_close(cx));
3018        cx.foreground().run_until_parked();
3019        cx.simulate_prompt_answer(window_id, 2 /* cancel */);
3020        cx.foreground().run_until_parked();
3021        assert!(!cx.has_pending_prompt(window_id));
3022        assert!(!task.await.unwrap());
3023    }
3024
3025    #[gpui::test]
3026    async fn test_close_pane_items(cx: &mut TestAppContext) {
3027        cx.foreground().forbid_parking();
3028        Settings::test_async(cx);
3029        let fs = FakeFs::new(cx.background());
3030
3031        let project = Project::test(fs, None, cx).await;
3032        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
3033
3034        let item1 = cx.add_view(&workspace, |_| {
3035            let mut item = TestItem::new();
3036            item.is_dirty = true;
3037            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3038            item
3039        });
3040        let item2 = cx.add_view(&workspace, |_| {
3041            let mut item = TestItem::new();
3042            item.is_dirty = true;
3043            item.has_conflict = true;
3044            item.project_entry_ids = vec![ProjectEntryId::from_proto(2)];
3045            item
3046        });
3047        let item3 = cx.add_view(&workspace, |_| {
3048            let mut item = TestItem::new();
3049            item.is_dirty = true;
3050            item.has_conflict = true;
3051            item.project_entry_ids = vec![ProjectEntryId::from_proto(3)];
3052            item
3053        });
3054        let item4 = cx.add_view(&workspace, |_| {
3055            let mut item = TestItem::new();
3056            item.is_dirty = true;
3057            item
3058        });
3059        let pane = workspace.update(cx, |workspace, cx| {
3060            workspace.add_item(Box::new(item1.clone()), cx);
3061            workspace.add_item(Box::new(item2.clone()), cx);
3062            workspace.add_item(Box::new(item3.clone()), cx);
3063            workspace.add_item(Box::new(item4.clone()), cx);
3064            workspace.active_pane().clone()
3065        });
3066
3067        let close_items = workspace.update(cx, |workspace, cx| {
3068            pane.update(cx, |pane, cx| {
3069                pane.activate_item(1, true, true, cx);
3070                assert_eq!(pane.active_item().unwrap().id(), item2.id());
3071            });
3072
3073            let item1_id = item1.id();
3074            let item3_id = item3.id();
3075            let item4_id = item4.id();
3076            Pane::close_items(workspace, pane.clone(), cx, move |id| {
3077                [item1_id, item3_id, item4_id].contains(&id)
3078            })
3079        });
3080
3081        cx.foreground().run_until_parked();
3082        pane.read_with(cx, |pane, _| {
3083            assert_eq!(pane.items().count(), 4);
3084            assert_eq!(pane.active_item().unwrap().id(), item1.id());
3085        });
3086
3087        cx.simulate_prompt_answer(window_id, 0);
3088        cx.foreground().run_until_parked();
3089        pane.read_with(cx, |pane, cx| {
3090            assert_eq!(item1.read(cx).save_count, 1);
3091            assert_eq!(item1.read(cx).save_as_count, 0);
3092            assert_eq!(item1.read(cx).reload_count, 0);
3093            assert_eq!(pane.items().count(), 3);
3094            assert_eq!(pane.active_item().unwrap().id(), item3.id());
3095        });
3096
3097        cx.simulate_prompt_answer(window_id, 1);
3098        cx.foreground().run_until_parked();
3099        pane.read_with(cx, |pane, cx| {
3100            assert_eq!(item3.read(cx).save_count, 0);
3101            assert_eq!(item3.read(cx).save_as_count, 0);
3102            assert_eq!(item3.read(cx).reload_count, 1);
3103            assert_eq!(pane.items().count(), 2);
3104            assert_eq!(pane.active_item().unwrap().id(), item4.id());
3105        });
3106
3107        cx.simulate_prompt_answer(window_id, 0);
3108        cx.foreground().run_until_parked();
3109        cx.simulate_new_path_selection(|_| Some(Default::default()));
3110        close_items.await.unwrap();
3111        pane.read_with(cx, |pane, cx| {
3112            assert_eq!(item4.read(cx).save_count, 0);
3113            assert_eq!(item4.read(cx).save_as_count, 1);
3114            assert_eq!(item4.read(cx).reload_count, 0);
3115            assert_eq!(pane.items().count(), 1);
3116            assert_eq!(pane.active_item().unwrap().id(), item2.id());
3117        });
3118    }
3119
3120    #[gpui::test]
3121    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
3122        cx.foreground().forbid_parking();
3123        Settings::test_async(cx);
3124        let fs = FakeFs::new(cx.background());
3125
3126        let project = Project::test(fs, [], cx).await;
3127        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
3128
3129        // Create several workspace items with single project entries, and two
3130        // workspace items with multiple project entries.
3131        let single_entry_items = (0..=4)
3132            .map(|project_entry_id| {
3133                let mut item = TestItem::new();
3134                item.is_dirty = true;
3135                item.project_entry_ids = vec![ProjectEntryId::from_proto(project_entry_id)];
3136                item.is_singleton = true;
3137                item
3138            })
3139            .collect::<Vec<_>>();
3140        let item_2_3 = {
3141            let mut item = TestItem::new();
3142            item.is_dirty = true;
3143            item.is_singleton = false;
3144            item.project_entry_ids =
3145                vec![ProjectEntryId::from_proto(2), ProjectEntryId::from_proto(3)];
3146            item
3147        };
3148        let item_3_4 = {
3149            let mut item = TestItem::new();
3150            item.is_dirty = true;
3151            item.is_singleton = false;
3152            item.project_entry_ids =
3153                vec![ProjectEntryId::from_proto(3), ProjectEntryId::from_proto(4)];
3154            item
3155        };
3156
3157        // Create two panes that contain the following project entries:
3158        //   left pane:
3159        //     multi-entry items:   (2, 3)
3160        //     single-entry items:  0, 1, 2, 3, 4
3161        //   right pane:
3162        //     single-entry items:  1
3163        //     multi-entry items:   (3, 4)
3164        let left_pane = workspace.update(cx, |workspace, cx| {
3165            let left_pane = workspace.active_pane().clone();
3166            workspace.add_item(Box::new(cx.add_view(|_| item_2_3.clone())), cx);
3167            for item in &single_entry_items {
3168                workspace.add_item(Box::new(cx.add_view(|_| item.clone())), cx);
3169            }
3170            left_pane.update(cx, |pane, cx| {
3171                pane.activate_item(2, true, true, cx);
3172            });
3173
3174            workspace
3175                .split_pane(left_pane.clone(), SplitDirection::Right, cx)
3176                .unwrap();
3177
3178            left_pane
3179        });
3180
3181        //Need to cause an effect flush in order to respect new focus
3182        workspace.update(cx, |workspace, cx| {
3183            workspace.add_item(Box::new(cx.add_view(|_| item_3_4.clone())), cx);
3184            cx.focus(left_pane.clone());
3185        });
3186
3187        // When closing all of the items in the left pane, we should be prompted twice:
3188        // once for project entry 0, and once for project entry 2. After those two
3189        // prompts, the task should complete.
3190
3191        let close = workspace.update(cx, |workspace, cx| {
3192            Pane::close_items(workspace, left_pane.clone(), cx, |_| true)
3193        });
3194
3195        cx.foreground().run_until_parked();
3196        left_pane.read_with(cx, |pane, cx| {
3197            assert_eq!(
3198                pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
3199                &[ProjectEntryId::from_proto(0)]
3200            );
3201        });
3202        cx.simulate_prompt_answer(window_id, 0);
3203
3204        cx.foreground().run_until_parked();
3205        left_pane.read_with(cx, |pane, cx| {
3206            assert_eq!(
3207                pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
3208                &[ProjectEntryId::from_proto(2)]
3209            );
3210        });
3211        cx.simulate_prompt_answer(window_id, 0);
3212
3213        cx.foreground().run_until_parked();
3214        close.await.unwrap();
3215        left_pane.read_with(cx, |pane, _| {
3216            assert_eq!(pane.items().count(), 0);
3217        });
3218    }
3219
3220    #[gpui::test]
3221    async fn test_autosave(deterministic: Arc<Deterministic>, cx: &mut gpui::TestAppContext) {
3222        deterministic.forbid_parking();
3223
3224        Settings::test_async(cx);
3225        let fs = FakeFs::new(cx.background());
3226
3227        let project = Project::test(fs, [], cx).await;
3228        let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
3229
3230        let item = cx.add_view(&workspace, |_| {
3231            let mut item = TestItem::new();
3232            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3233            item
3234        });
3235        let item_id = item.id();
3236        workspace.update(cx, |workspace, cx| {
3237            workspace.add_item(Box::new(item.clone()), cx);
3238        });
3239
3240        // Autosave on window change.
3241        item.update(cx, |item, cx| {
3242            cx.update_global(|settings: &mut Settings, _| {
3243                settings.autosave = Autosave::OnWindowChange;
3244            });
3245            item.is_dirty = true;
3246        });
3247
3248        // Deactivating the window saves the file.
3249        cx.simulate_window_activation(None);
3250        deterministic.run_until_parked();
3251        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
3252
3253        // Autosave on focus change.
3254        item.update(cx, |item, cx| {
3255            cx.focus_self();
3256            cx.update_global(|settings: &mut Settings, _| {
3257                settings.autosave = Autosave::OnFocusChange;
3258            });
3259            item.is_dirty = true;
3260        });
3261
3262        // Blurring the item saves the file.
3263        item.update(cx, |_, cx| cx.blur());
3264        deterministic.run_until_parked();
3265        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
3266
3267        // Deactivating the window still saves the file.
3268        cx.simulate_window_activation(Some(window_id));
3269        item.update(cx, |item, cx| {
3270            cx.focus_self();
3271            item.is_dirty = true;
3272        });
3273        cx.simulate_window_activation(None);
3274
3275        deterministic.run_until_parked();
3276        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
3277
3278        // Autosave after delay.
3279        item.update(cx, |item, cx| {
3280            cx.update_global(|settings: &mut Settings, _| {
3281                settings.autosave = Autosave::AfterDelay { milliseconds: 500 };
3282            });
3283            item.is_dirty = true;
3284            cx.emit(TestItemEvent::Edit);
3285        });
3286
3287        // Delay hasn't fully expired, so the file is still dirty and unsaved.
3288        deterministic.advance_clock(Duration::from_millis(250));
3289        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
3290
3291        // After delay expires, the file is saved.
3292        deterministic.advance_clock(Duration::from_millis(250));
3293        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
3294
3295        // Autosave on focus change, ensuring closing the tab counts as such.
3296        item.update(cx, |item, cx| {
3297            cx.update_global(|settings: &mut Settings, _| {
3298                settings.autosave = Autosave::OnFocusChange;
3299            });
3300            item.is_dirty = true;
3301        });
3302
3303        workspace
3304            .update(cx, |workspace, cx| {
3305                let pane = workspace.active_pane().clone();
3306                Pane::close_items(workspace, pane, cx, move |id| id == item_id)
3307            })
3308            .await
3309            .unwrap();
3310        assert!(!cx.has_pending_prompt(window_id));
3311        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3312
3313        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
3314        workspace.update(cx, |workspace, cx| {
3315            workspace.add_item(Box::new(item.clone()), cx);
3316        });
3317        item.update(cx, |item, cx| {
3318            item.project_entry_ids = Default::default();
3319            item.is_dirty = true;
3320            cx.blur();
3321        });
3322        deterministic.run_until_parked();
3323        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3324
3325        // Ensure autosave is prevented for deleted files also when closing the buffer.
3326        let _close_items = workspace.update(cx, |workspace, cx| {
3327            let pane = workspace.active_pane().clone();
3328            Pane::close_items(workspace, pane, cx, move |id| id == item_id)
3329        });
3330        deterministic.run_until_parked();
3331        assert!(cx.has_pending_prompt(window_id));
3332        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3333    }
3334
3335    #[gpui::test]
3336    async fn test_pane_navigation(
3337        deterministic: Arc<Deterministic>,
3338        cx: &mut gpui::TestAppContext,
3339    ) {
3340        deterministic.forbid_parking();
3341        Settings::test_async(cx);
3342        let fs = FakeFs::new(cx.background());
3343
3344        let project = Project::test(fs, [], cx).await;
3345        let (_, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
3346
3347        let item = cx.add_view(&workspace, |_| {
3348            let mut item = TestItem::new();
3349            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3350            item
3351        });
3352        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
3353        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
3354        let toolbar_notify_count = Rc::new(RefCell::new(0));
3355
3356        workspace.update(cx, |workspace, cx| {
3357            workspace.add_item(Box::new(item.clone()), cx);
3358            let toolbar_notification_count = toolbar_notify_count.clone();
3359            cx.observe(&toolbar, move |_, _, _| {
3360                *toolbar_notification_count.borrow_mut() += 1
3361            })
3362            .detach();
3363        });
3364
3365        pane.read_with(cx, |pane, _| {
3366            assert!(!pane.can_navigate_backward());
3367            assert!(!pane.can_navigate_forward());
3368        });
3369
3370        item.update(cx, |item, cx| {
3371            item.set_state("one".to_string(), cx);
3372        });
3373
3374        // Toolbar must be notified to re-render the navigation buttons
3375        assert_eq!(*toolbar_notify_count.borrow(), 1);
3376
3377        pane.read_with(cx, |pane, _| {
3378            assert!(pane.can_navigate_backward());
3379            assert!(!pane.can_navigate_forward());
3380        });
3381
3382        workspace
3383            .update(cx, |workspace, cx| {
3384                Pane::go_back(workspace, Some(pane.clone()), cx)
3385            })
3386            .await;
3387
3388        assert_eq!(*toolbar_notify_count.borrow(), 3);
3389        pane.read_with(cx, |pane, _| {
3390            assert!(!pane.can_navigate_backward());
3391            assert!(pane.can_navigate_forward());
3392        });
3393    }
3394
3395    pub struct TestItem {
3396        state: String,
3397        pub label: String,
3398        save_count: usize,
3399        save_as_count: usize,
3400        reload_count: usize,
3401        is_dirty: bool,
3402        is_singleton: bool,
3403        has_conflict: bool,
3404        project_entry_ids: Vec<ProjectEntryId>,
3405        project_path: Option<ProjectPath>,
3406        nav_history: Option<ItemNavHistory>,
3407        tab_descriptions: Option<Vec<&'static str>>,
3408        tab_detail: Cell<Option<usize>>,
3409    }
3410
3411    pub enum TestItemEvent {
3412        Edit,
3413    }
3414
3415    impl Clone for TestItem {
3416        fn clone(&self) -> Self {
3417            Self {
3418                state: self.state.clone(),
3419                label: self.label.clone(),
3420                save_count: self.save_count,
3421                save_as_count: self.save_as_count,
3422                reload_count: self.reload_count,
3423                is_dirty: self.is_dirty,
3424                is_singleton: self.is_singleton,
3425                has_conflict: self.has_conflict,
3426                project_entry_ids: self.project_entry_ids.clone(),
3427                project_path: self.project_path.clone(),
3428                nav_history: None,
3429                tab_descriptions: None,
3430                tab_detail: Default::default(),
3431            }
3432        }
3433    }
3434
3435    impl TestItem {
3436        pub fn new() -> Self {
3437            Self {
3438                state: String::new(),
3439                label: String::new(),
3440                save_count: 0,
3441                save_as_count: 0,
3442                reload_count: 0,
3443                is_dirty: false,
3444                has_conflict: false,
3445                project_entry_ids: Vec::new(),
3446                project_path: None,
3447                is_singleton: true,
3448                nav_history: None,
3449                tab_descriptions: None,
3450                tab_detail: Default::default(),
3451            }
3452        }
3453
3454        pub fn with_label(mut self, state: &str) -> Self {
3455            self.label = state.to_string();
3456            self
3457        }
3458
3459        fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
3460            self.push_to_nav_history(cx);
3461            self.state = state;
3462        }
3463
3464        fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
3465            if let Some(history) = &mut self.nav_history {
3466                history.push(Some(Box::new(self.state.clone())), cx);
3467            }
3468        }
3469    }
3470
3471    impl Entity for TestItem {
3472        type Event = TestItemEvent;
3473    }
3474
3475    impl View for TestItem {
3476        fn ui_name() -> &'static str {
3477            "TestItem"
3478        }
3479
3480        fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3481            Empty::new().boxed()
3482        }
3483    }
3484
3485    impl Item for TestItem {
3486        fn tab_description<'a>(&'a self, detail: usize, _: &'a AppContext) -> Option<Cow<'a, str>> {
3487            self.tab_descriptions.as_ref().and_then(|descriptions| {
3488                let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
3489                Some(description.into())
3490            })
3491        }
3492
3493        fn tab_content(&self, detail: Option<usize>, _: &theme::Tab, _: &AppContext) -> ElementBox {
3494            self.tab_detail.set(detail);
3495            Empty::new().boxed()
3496        }
3497
3498        fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
3499            self.project_path.clone()
3500        }
3501
3502        fn project_entry_ids(&self, _: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
3503            self.project_entry_ids.iter().copied().collect()
3504        }
3505
3506        fn is_singleton(&self, _: &AppContext) -> bool {
3507            self.is_singleton
3508        }
3509
3510        fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
3511            self.nav_history = Some(history);
3512        }
3513
3514        fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
3515            let state = *state.downcast::<String>().unwrap_or_default();
3516            if state != self.state {
3517                self.state = state;
3518                true
3519            } else {
3520                false
3521            }
3522        }
3523
3524        fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
3525            self.push_to_nav_history(cx);
3526        }
3527
3528        fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
3529        where
3530            Self: Sized,
3531        {
3532            Some(self.clone())
3533        }
3534
3535        fn is_dirty(&self, _: &AppContext) -> bool {
3536            self.is_dirty
3537        }
3538
3539        fn has_conflict(&self, _: &AppContext) -> bool {
3540            self.has_conflict
3541        }
3542
3543        fn can_save(&self, _: &AppContext) -> bool {
3544            !self.project_entry_ids.is_empty()
3545        }
3546
3547        fn save(
3548            &mut self,
3549            _: ModelHandle<Project>,
3550            _: &mut ViewContext<Self>,
3551        ) -> Task<anyhow::Result<()>> {
3552            self.save_count += 1;
3553            self.is_dirty = false;
3554            Task::ready(Ok(()))
3555        }
3556
3557        fn save_as(
3558            &mut self,
3559            _: ModelHandle<Project>,
3560            _: std::path::PathBuf,
3561            _: &mut ViewContext<Self>,
3562        ) -> Task<anyhow::Result<()>> {
3563            self.save_as_count += 1;
3564            self.is_dirty = false;
3565            Task::ready(Ok(()))
3566        }
3567
3568        fn reload(
3569            &mut self,
3570            _: ModelHandle<Project>,
3571            _: &mut ViewContext<Self>,
3572        ) -> Task<anyhow::Result<()>> {
3573            self.reload_count += 1;
3574            self.is_dirty = false;
3575            Task::ready(Ok(()))
3576        }
3577
3578        fn should_update_tab_on_event(_: &Self::Event) -> bool {
3579            true
3580        }
3581
3582        fn is_edit_event(event: &Self::Event) -> bool {
3583            matches!(event, TestItemEvent::Edit)
3584        }
3585    }
3586}