workspace.rs

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