workspace.rs

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