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, warn};
  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        if &pane == self.dock_pane() {
1788            warn!("Can't split dock pane.");
1789            return None;
1790        }
1791
1792        pane.read(cx).active_item().map(|item| {
1793            let new_pane = self.add_pane(cx);
1794            if let Some(clone) = item.clone_on_split(cx.as_mut()) {
1795                Pane::add_item(self, &new_pane, clone, true, true, None, cx);
1796            }
1797            self.center.split(&pane, &new_pane, direction).unwrap();
1798            cx.notify();
1799            new_pane
1800        })
1801    }
1802
1803    fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1804        if self.center.remove(&pane).unwrap() {
1805            self.panes.retain(|p| p != &pane);
1806            cx.focus(self.panes.last().unwrap().clone());
1807            self.unfollow(&pane, cx);
1808            self.last_leaders_by_pane.remove(&pane.downgrade());
1809            for removed_item in pane.read(cx).items() {
1810                self.panes_by_item.remove(&removed_item.id());
1811            }
1812            if self.last_active_center_pane == Some(pane) {
1813                self.last_active_center_pane = None;
1814            }
1815
1816            cx.notify();
1817        } else {
1818            self.active_item_path_changed(cx);
1819        }
1820    }
1821
1822    pub fn panes(&self) -> &[ViewHandle<Pane>] {
1823        &self.panes
1824    }
1825
1826    fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1827        self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1828    }
1829
1830    pub fn active_pane(&self) -> &ViewHandle<Pane> {
1831        &self.active_pane
1832    }
1833
1834    pub fn dock_pane(&self) -> &ViewHandle<Pane> {
1835        self.dock.pane()
1836    }
1837
1838    fn project_remote_id_changed(&mut self, remote_id: Option<u64>, cx: &mut ViewContext<Self>) {
1839        if let Some(remote_id) = remote_id {
1840            self.remote_entity_subscription =
1841                Some(self.client.add_view_for_remote_entity(remote_id, cx));
1842        } else {
1843            self.remote_entity_subscription.take();
1844        }
1845    }
1846
1847    fn collaborator_left(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
1848        self.leader_state.followers.remove(&peer_id);
1849        if let Some(states_by_pane) = self.follower_states_by_leader.remove(&peer_id) {
1850            for state in states_by_pane.into_values() {
1851                for item in state.items_by_leader_view_id.into_values() {
1852                    if let FollowerItem::Loaded(item) = item {
1853                        item.set_leader_replica_id(None, cx);
1854                    }
1855                }
1856            }
1857        }
1858        cx.notify();
1859    }
1860
1861    pub fn toggle_follow(
1862        &mut self,
1863        ToggleFollow(leader_id): &ToggleFollow,
1864        cx: &mut ViewContext<Self>,
1865    ) -> Option<Task<Result<()>>> {
1866        let leader_id = *leader_id;
1867        let pane = self.active_pane().clone();
1868
1869        if let Some(prev_leader_id) = self.unfollow(&pane, cx) {
1870            if leader_id == prev_leader_id {
1871                return None;
1872            }
1873        }
1874
1875        self.last_leaders_by_pane
1876            .insert(pane.downgrade(), leader_id);
1877        self.follower_states_by_leader
1878            .entry(leader_id)
1879            .or_default()
1880            .insert(pane.clone(), Default::default());
1881        cx.notify();
1882
1883        let project_id = self.project.read(cx).remote_id()?;
1884        let request = self.client.request(proto::Follow {
1885            project_id,
1886            leader_id: leader_id.0,
1887        });
1888        Some(cx.spawn_weak(|this, mut cx| async move {
1889            let response = request.await?;
1890            if let Some(this) = this.upgrade(&cx) {
1891                this.update(&mut cx, |this, _| {
1892                    let state = this
1893                        .follower_states_by_leader
1894                        .get_mut(&leader_id)
1895                        .and_then(|states_by_pane| states_by_pane.get_mut(&pane))
1896                        .ok_or_else(|| anyhow!("following interrupted"))?;
1897                    state.active_view_id = response.active_view_id;
1898                    Ok::<_, anyhow::Error>(())
1899                })?;
1900                Self::add_views_from_leader(this, leader_id, vec![pane], response.views, &mut cx)
1901                    .await?;
1902            }
1903            Ok(())
1904        }))
1905    }
1906
1907    pub fn follow_next_collaborator(
1908        &mut self,
1909        _: &FollowNextCollaborator,
1910        cx: &mut ViewContext<Self>,
1911    ) -> Option<Task<Result<()>>> {
1912        let collaborators = self.project.read(cx).collaborators();
1913        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
1914            let mut collaborators = collaborators.keys().copied();
1915            for peer_id in collaborators.by_ref() {
1916                if peer_id == leader_id {
1917                    break;
1918                }
1919            }
1920            collaborators.next()
1921        } else if let Some(last_leader_id) =
1922            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
1923        {
1924            if collaborators.contains_key(last_leader_id) {
1925                Some(*last_leader_id)
1926            } else {
1927                None
1928            }
1929        } else {
1930            None
1931        };
1932
1933        next_leader_id
1934            .or_else(|| collaborators.keys().copied().next())
1935            .and_then(|leader_id| self.toggle_follow(&ToggleFollow(leader_id), cx))
1936    }
1937
1938    pub fn unfollow(
1939        &mut self,
1940        pane: &ViewHandle<Pane>,
1941        cx: &mut ViewContext<Self>,
1942    ) -> Option<PeerId> {
1943        for (leader_id, states_by_pane) in &mut self.follower_states_by_leader {
1944            let leader_id = *leader_id;
1945            if let Some(state) = states_by_pane.remove(pane) {
1946                for (_, item) in state.items_by_leader_view_id {
1947                    if let FollowerItem::Loaded(item) = item {
1948                        item.set_leader_replica_id(None, cx);
1949                    }
1950                }
1951
1952                if states_by_pane.is_empty() {
1953                    self.follower_states_by_leader.remove(&leader_id);
1954                    if let Some(project_id) = self.project.read(cx).remote_id() {
1955                        self.client
1956                            .send(proto::Unfollow {
1957                                project_id,
1958                                leader_id: leader_id.0,
1959                            })
1960                            .log_err();
1961                    }
1962                }
1963
1964                cx.notify();
1965                return Some(leader_id);
1966            }
1967        }
1968        None
1969    }
1970
1971    fn render_connection_status(&self, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1972        let theme = &cx.global::<Settings>().theme;
1973        match &*self.client.status().borrow() {
1974            client::Status::ConnectionError
1975            | client::Status::ConnectionLost
1976            | client::Status::Reauthenticating { .. }
1977            | client::Status::Reconnecting { .. }
1978            | client::Status::ReconnectionError { .. } => Some(
1979                Container::new(
1980                    Align::new(
1981                        ConstrainedBox::new(
1982                            Svg::new("icons/cloud_slash_12.svg")
1983                                .with_color(theme.workspace.titlebar.offline_icon.color)
1984                                .boxed(),
1985                        )
1986                        .with_width(theme.workspace.titlebar.offline_icon.width)
1987                        .boxed(),
1988                    )
1989                    .boxed(),
1990                )
1991                .with_style(theme.workspace.titlebar.offline_icon.container)
1992                .boxed(),
1993            ),
1994            client::Status::UpgradeRequired => Some(
1995                Label::new(
1996                    "Please update Zed to collaborate".to_string(),
1997                    theme.workspace.titlebar.outdated_warning.text.clone(),
1998                )
1999                .contained()
2000                .with_style(theme.workspace.titlebar.outdated_warning.container)
2001                .aligned()
2002                .boxed(),
2003            ),
2004            _ => None,
2005        }
2006    }
2007
2008    fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
2009        let project = &self.project.read(cx);
2010        let replica_id = project.replica_id();
2011        let mut worktree_root_names = String::new();
2012        for (i, name) in project.worktree_root_names(cx).enumerate() {
2013            if i > 0 {
2014                worktree_root_names.push_str(", ");
2015            }
2016            worktree_root_names.push_str(name);
2017        }
2018
2019        // TODO: There should be a better system in place for this
2020        // (https://github.com/zed-industries/zed/issues/1290)
2021        let is_fullscreen = cx.window_is_fullscreen(cx.window_id());
2022        let container_theme = if is_fullscreen {
2023            let mut container_theme = theme.workspace.titlebar.container;
2024            container_theme.padding.left = container_theme.padding.right;
2025            container_theme
2026        } else {
2027            theme.workspace.titlebar.container
2028        };
2029
2030        enum TitleBar {}
2031        ConstrainedBox::new(
2032            MouseEventHandler::<TitleBar>::new(0, cx, |_, cx| {
2033                Container::new(
2034                    Stack::new()
2035                        .with_child(
2036                            Label::new(worktree_root_names, theme.workspace.titlebar.title.clone())
2037                                .aligned()
2038                                .left()
2039                                .boxed(),
2040                        )
2041                        .with_child(
2042                            Align::new(
2043                                Flex::row()
2044                                    .with_children(self.render_collaborators(theme, cx))
2045                                    .with_children(self.render_current_user(
2046                                        self.user_store.read(cx).current_user().as_ref(),
2047                                        replica_id,
2048                                        theme,
2049                                        cx,
2050                                    ))
2051                                    .with_children(self.render_connection_status(cx))
2052                                    .boxed(),
2053                            )
2054                            .right()
2055                            .boxed(),
2056                        )
2057                        .boxed(),
2058                )
2059                .with_style(container_theme)
2060                .boxed()
2061            })
2062            .on_click(MouseButton::Left, |event, cx| {
2063                if event.click_count == 2 {
2064                    cx.zoom_window(cx.window_id());
2065                }
2066            })
2067            .boxed(),
2068        )
2069        .with_height(theme.workspace.titlebar.height)
2070        .named("titlebar")
2071    }
2072
2073    fn active_item_path_changed(&mut self, cx: &mut ViewContext<Self>) {
2074        let active_entry = self.active_project_path(cx);
2075        self.project
2076            .update(cx, |project, cx| project.set_active_path(active_entry, cx));
2077        self.update_window_title(cx);
2078    }
2079
2080    fn update_window_title(&mut self, cx: &mut ViewContext<Self>) {
2081        let mut title = String::new();
2082        let project = self.project().read(cx);
2083        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
2084            let filename = path
2085                .path
2086                .file_name()
2087                .map(|s| s.to_string_lossy())
2088                .or_else(|| {
2089                    Some(Cow::Borrowed(
2090                        project
2091                            .worktree_for_id(path.worktree_id, cx)?
2092                            .read(cx)
2093                            .root_name(),
2094                    ))
2095                });
2096            if let Some(filename) = filename {
2097                title.push_str(filename.as_ref());
2098                title.push_str("");
2099            }
2100        }
2101        for (i, name) in project.worktree_root_names(cx).enumerate() {
2102            if i > 0 {
2103                title.push_str(", ");
2104            }
2105            title.push_str(name);
2106        }
2107        if title.is_empty() {
2108            title = "empty project".to_string();
2109        }
2110        cx.set_window_title(&title);
2111    }
2112
2113    fn update_window_edited(&mut self, cx: &mut ViewContext<Self>) {
2114        let is_edited = !self.project.read(cx).is_read_only()
2115            && self
2116                .items(cx)
2117                .any(|item| item.has_conflict(cx) || item.is_dirty(cx));
2118        if is_edited != self.window_edited {
2119            self.window_edited = is_edited;
2120            cx.set_window_edited(self.window_edited)
2121        }
2122    }
2123
2124    fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
2125        let mut collaborators = self
2126            .project
2127            .read(cx)
2128            .collaborators()
2129            .values()
2130            .cloned()
2131            .collect::<Vec<_>>();
2132        collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
2133        collaborators
2134            .into_iter()
2135            .filter_map(|collaborator| {
2136                Some(self.render_avatar(
2137                    collaborator.user.avatar.clone()?,
2138                    collaborator.replica_id,
2139                    Some((collaborator.peer_id, &collaborator.user.github_login)),
2140                    theme,
2141                    cx,
2142                ))
2143            })
2144            .collect()
2145    }
2146
2147    fn render_current_user(
2148        &self,
2149        user: Option<&Arc<User>>,
2150        replica_id: ReplicaId,
2151        theme: &Theme,
2152        cx: &mut RenderContext<Self>,
2153    ) -> Option<ElementBox> {
2154        let status = *self.client.status().borrow();
2155        if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
2156            Some(self.render_avatar(avatar, replica_id, None, theme, cx))
2157        } else if matches!(status, client::Status::UpgradeRequired) {
2158            None
2159        } else {
2160            Some(
2161                MouseEventHandler::<Authenticate>::new(0, cx, |state, _| {
2162                    let style = theme
2163                        .workspace
2164                        .titlebar
2165                        .sign_in_prompt
2166                        .style_for(state, false);
2167                    Label::new("Sign in".to_string(), style.text.clone())
2168                        .contained()
2169                        .with_style(style.container)
2170                        .boxed()
2171                })
2172                .on_click(MouseButton::Left, |_, cx| cx.dispatch_action(Authenticate))
2173                .with_cursor_style(CursorStyle::PointingHand)
2174                .aligned()
2175                .boxed(),
2176            )
2177        }
2178    }
2179
2180    fn render_avatar(
2181        &self,
2182        avatar: Arc<ImageData>,
2183        replica_id: ReplicaId,
2184        peer: Option<(PeerId, &str)>,
2185        theme: &Theme,
2186        cx: &mut RenderContext<Self>,
2187    ) -> ElementBox {
2188        let replica_color = theme.editor.replica_selection_style(replica_id).cursor;
2189        let is_followed = peer.map_or(false, |(peer_id, _)| {
2190            self.follower_states_by_leader.contains_key(&peer_id)
2191        });
2192        let mut avatar_style = theme.workspace.titlebar.avatar;
2193        if is_followed {
2194            avatar_style.border = Border::all(1.0, replica_color);
2195        }
2196        let content = Stack::new()
2197            .with_child(
2198                Image::new(avatar)
2199                    .with_style(avatar_style)
2200                    .constrained()
2201                    .with_width(theme.workspace.titlebar.avatar_width)
2202                    .aligned()
2203                    .boxed(),
2204            )
2205            .with_child(
2206                AvatarRibbon::new(replica_color)
2207                    .constrained()
2208                    .with_width(theme.workspace.titlebar.avatar_ribbon.width)
2209                    .with_height(theme.workspace.titlebar.avatar_ribbon.height)
2210                    .aligned()
2211                    .bottom()
2212                    .boxed(),
2213            )
2214            .constrained()
2215            .with_width(theme.workspace.titlebar.avatar_width)
2216            .contained()
2217            .with_margin_left(theme.workspace.titlebar.avatar_margin)
2218            .boxed();
2219
2220        if let Some((peer_id, peer_github_login)) = peer {
2221            MouseEventHandler::<ToggleFollow>::new(replica_id.into(), cx, move |_, _| content)
2222                .with_cursor_style(CursorStyle::PointingHand)
2223                .on_click(MouseButton::Left, move |_, cx| {
2224                    cx.dispatch_action(ToggleFollow(peer_id))
2225                })
2226                .with_tooltip::<ToggleFollow, _>(
2227                    peer_id.0 as usize,
2228                    if is_followed {
2229                        format!("Unfollow {}", peer_github_login)
2230                    } else {
2231                        format!("Follow {}", peer_github_login)
2232                    },
2233                    Some(Box::new(FollowNextCollaborator)),
2234                    theme.tooltip.clone(),
2235                    cx,
2236                )
2237                .boxed()
2238        } else {
2239            content
2240        }
2241    }
2242
2243    fn render_disconnected_overlay(&self, cx: &mut RenderContext<Workspace>) -> Option<ElementBox> {
2244        if self.project.read(cx).is_read_only() {
2245            enum DisconnectedOverlay {}
2246            Some(
2247                MouseEventHandler::<DisconnectedOverlay>::new(0, cx, |_, cx| {
2248                    let theme = &cx.global::<Settings>().theme;
2249                    Label::new(
2250                        "Your connection to the remote project has been lost.".to_string(),
2251                        theme.workspace.disconnected_overlay.text.clone(),
2252                    )
2253                    .aligned()
2254                    .contained()
2255                    .with_style(theme.workspace.disconnected_overlay.container)
2256                    .boxed()
2257                })
2258                .with_cursor_style(CursorStyle::Arrow)
2259                .capture_all()
2260                .boxed(),
2261            )
2262        } else {
2263            None
2264        }
2265    }
2266
2267    fn render_notifications(&self, theme: &theme::Workspace) -> Option<ElementBox> {
2268        if self.notifications.is_empty() {
2269            None
2270        } else {
2271            Some(
2272                Flex::column()
2273                    .with_children(self.notifications.iter().map(|(_, _, notification)| {
2274                        ChildView::new(notification.as_ref())
2275                            .contained()
2276                            .with_style(theme.notification)
2277                            .boxed()
2278                    }))
2279                    .constrained()
2280                    .with_width(theme.notifications.width)
2281                    .contained()
2282                    .with_style(theme.notifications.container)
2283                    .aligned()
2284                    .bottom()
2285                    .right()
2286                    .boxed(),
2287            )
2288        }
2289    }
2290
2291    // RPC handlers
2292
2293    async fn handle_follow(
2294        this: ViewHandle<Self>,
2295        envelope: TypedEnvelope<proto::Follow>,
2296        _: Arc<Client>,
2297        mut cx: AsyncAppContext,
2298    ) -> Result<proto::FollowResponse> {
2299        this.update(&mut cx, |this, cx| {
2300            this.leader_state
2301                .followers
2302                .insert(envelope.original_sender_id()?);
2303
2304            let active_view_id = this
2305                .active_item(cx)
2306                .and_then(|i| i.to_followable_item_handle(cx))
2307                .map(|i| i.id() as u64);
2308            Ok(proto::FollowResponse {
2309                active_view_id,
2310                views: this
2311                    .panes()
2312                    .iter()
2313                    .flat_map(|pane| {
2314                        let leader_id = this.leader_for_pane(pane).map(|id| id.0);
2315                        pane.read(cx).items().filter_map({
2316                            let cx = &cx;
2317                            move |item| {
2318                                let id = item.id() as u64;
2319                                let item = item.to_followable_item_handle(cx)?;
2320                                let variant = item.to_state_proto(cx)?;
2321                                Some(proto::View {
2322                                    id,
2323                                    leader_id,
2324                                    variant: Some(variant),
2325                                })
2326                            }
2327                        })
2328                    })
2329                    .collect(),
2330            })
2331        })
2332    }
2333
2334    async fn handle_unfollow(
2335        this: ViewHandle<Self>,
2336        envelope: TypedEnvelope<proto::Unfollow>,
2337        _: Arc<Client>,
2338        mut cx: AsyncAppContext,
2339    ) -> Result<()> {
2340        this.update(&mut cx, |this, _| {
2341            this.leader_state
2342                .followers
2343                .remove(&envelope.original_sender_id()?);
2344            Ok(())
2345        })
2346    }
2347
2348    async fn handle_update_followers(
2349        this: ViewHandle<Self>,
2350        envelope: TypedEnvelope<proto::UpdateFollowers>,
2351        _: Arc<Client>,
2352        mut cx: AsyncAppContext,
2353    ) -> Result<()> {
2354        let leader_id = envelope.original_sender_id()?;
2355        match envelope
2356            .payload
2357            .variant
2358            .ok_or_else(|| anyhow!("invalid update"))?
2359        {
2360            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
2361                this.update(&mut cx, |this, cx| {
2362                    this.update_leader_state(leader_id, cx, |state, _| {
2363                        state.active_view_id = update_active_view.id;
2364                    });
2365                    Ok::<_, anyhow::Error>(())
2366                })
2367            }
2368            proto::update_followers::Variant::UpdateView(update_view) => {
2369                this.update(&mut cx, |this, cx| {
2370                    let variant = update_view
2371                        .variant
2372                        .ok_or_else(|| anyhow!("missing update view variant"))?;
2373                    this.update_leader_state(leader_id, cx, |state, cx| {
2374                        let variant = variant.clone();
2375                        match state
2376                            .items_by_leader_view_id
2377                            .entry(update_view.id)
2378                            .or_insert(FollowerItem::Loading(Vec::new()))
2379                        {
2380                            FollowerItem::Loaded(item) => {
2381                                item.apply_update_proto(variant, cx).log_err();
2382                            }
2383                            FollowerItem::Loading(updates) => updates.push(variant),
2384                        }
2385                    });
2386                    Ok(())
2387                })
2388            }
2389            proto::update_followers::Variant::CreateView(view) => {
2390                let panes = this.read_with(&cx, |this, _| {
2391                    this.follower_states_by_leader
2392                        .get(&leader_id)
2393                        .into_iter()
2394                        .flat_map(|states_by_pane| states_by_pane.keys())
2395                        .cloned()
2396                        .collect()
2397                });
2398                Self::add_views_from_leader(this.clone(), leader_id, panes, vec![view], &mut cx)
2399                    .await?;
2400                Ok(())
2401            }
2402        }
2403        .log_err();
2404
2405        Ok(())
2406    }
2407
2408    async fn add_views_from_leader(
2409        this: ViewHandle<Self>,
2410        leader_id: PeerId,
2411        panes: Vec<ViewHandle<Pane>>,
2412        views: Vec<proto::View>,
2413        cx: &mut AsyncAppContext,
2414    ) -> Result<()> {
2415        let project = this.read_with(cx, |this, _| this.project.clone());
2416        let replica_id = project
2417            .read_with(cx, |project, _| {
2418                project
2419                    .collaborators()
2420                    .get(&leader_id)
2421                    .map(|c| c.replica_id)
2422            })
2423            .ok_or_else(|| anyhow!("no such collaborator {}", leader_id))?;
2424
2425        let item_builders = cx.update(|cx| {
2426            cx.default_global::<FollowableItemBuilders>()
2427                .values()
2428                .map(|b| b.0)
2429                .collect::<Vec<_>>()
2430        });
2431
2432        let mut item_tasks_by_pane = HashMap::default();
2433        for pane in panes {
2434            let mut item_tasks = Vec::new();
2435            let mut leader_view_ids = Vec::new();
2436            for view in &views {
2437                let mut variant = view.variant.clone();
2438                if variant.is_none() {
2439                    Err(anyhow!("missing variant"))?;
2440                }
2441                for build_item in &item_builders {
2442                    let task =
2443                        cx.update(|cx| build_item(pane.clone(), project.clone(), &mut variant, cx));
2444                    if let Some(task) = task {
2445                        item_tasks.push(task);
2446                        leader_view_ids.push(view.id);
2447                        break;
2448                    } else {
2449                        assert!(variant.is_some());
2450                    }
2451                }
2452            }
2453
2454            item_tasks_by_pane.insert(pane, (item_tasks, leader_view_ids));
2455        }
2456
2457        for (pane, (item_tasks, leader_view_ids)) in item_tasks_by_pane {
2458            let items = futures::future::try_join_all(item_tasks).await?;
2459            this.update(cx, |this, cx| {
2460                let state = this
2461                    .follower_states_by_leader
2462                    .get_mut(&leader_id)?
2463                    .get_mut(&pane)?;
2464
2465                for (id, item) in leader_view_ids.into_iter().zip(items) {
2466                    item.set_leader_replica_id(Some(replica_id), cx);
2467                    match state.items_by_leader_view_id.entry(id) {
2468                        hash_map::Entry::Occupied(e) => {
2469                            let e = e.into_mut();
2470                            if let FollowerItem::Loading(updates) = e {
2471                                for update in updates.drain(..) {
2472                                    item.apply_update_proto(update, cx)
2473                                        .context("failed to apply view update")
2474                                        .log_err();
2475                                }
2476                            }
2477                            *e = FollowerItem::Loaded(item);
2478                        }
2479                        hash_map::Entry::Vacant(e) => {
2480                            e.insert(FollowerItem::Loaded(item));
2481                        }
2482                    }
2483                }
2484
2485                Some(())
2486            });
2487        }
2488        this.update(cx, |this, cx| this.leader_updated(leader_id, cx));
2489
2490        Ok(())
2491    }
2492
2493    fn update_followers(
2494        &self,
2495        update: proto::update_followers::Variant,
2496        cx: &AppContext,
2497    ) -> Option<()> {
2498        let project_id = self.project.read(cx).remote_id()?;
2499        if !self.leader_state.followers.is_empty() {
2500            self.client
2501                .send(proto::UpdateFollowers {
2502                    project_id,
2503                    follower_ids: self.leader_state.followers.iter().map(|f| f.0).collect(),
2504                    variant: Some(update),
2505                })
2506                .log_err();
2507        }
2508        None
2509    }
2510
2511    pub fn leader_for_pane(&self, pane: &ViewHandle<Pane>) -> Option<PeerId> {
2512        self.follower_states_by_leader
2513            .iter()
2514            .find_map(|(leader_id, state)| {
2515                if state.contains_key(pane) {
2516                    Some(*leader_id)
2517                } else {
2518                    None
2519                }
2520            })
2521    }
2522
2523    fn update_leader_state(
2524        &mut self,
2525        leader_id: PeerId,
2526        cx: &mut ViewContext<Self>,
2527        mut update_fn: impl FnMut(&mut FollowerState, &mut ViewContext<Self>),
2528    ) {
2529        for (_, state) in self
2530            .follower_states_by_leader
2531            .get_mut(&leader_id)
2532            .into_iter()
2533            .flatten()
2534        {
2535            update_fn(state, cx);
2536        }
2537        self.leader_updated(leader_id, cx);
2538    }
2539
2540    fn leader_updated(&mut self, leader_id: PeerId, cx: &mut ViewContext<Self>) -> Option<()> {
2541        let mut items_to_add = Vec::new();
2542        for (pane, state) in self.follower_states_by_leader.get(&leader_id)? {
2543            if let Some(FollowerItem::Loaded(item)) = state
2544                .active_view_id
2545                .and_then(|id| state.items_by_leader_view_id.get(&id))
2546            {
2547                items_to_add.push((pane.clone(), item.boxed_clone()));
2548            }
2549        }
2550
2551        for (pane, item) in items_to_add {
2552            Pane::add_item(self, &pane, item.boxed_clone(), false, false, None, cx);
2553            if pane == self.active_pane {
2554                pane.update(cx, |pane, cx| pane.focus_active_item(cx));
2555            }
2556            cx.notify();
2557        }
2558        None
2559    }
2560
2561    pub fn on_window_activation_changed(&mut self, active: bool, cx: &mut ViewContext<Self>) {
2562        if !active {
2563            for pane in &self.panes {
2564                pane.update(cx, |pane, cx| {
2565                    if let Some(item) = pane.active_item() {
2566                        item.workspace_deactivated(cx);
2567                    }
2568                    if matches!(
2569                        cx.global::<Settings>().autosave,
2570                        Autosave::OnWindowChange | Autosave::OnFocusChange
2571                    ) {
2572                        for item in pane.items() {
2573                            Pane::autosave_item(item.as_ref(), self.project.clone(), cx)
2574                                .detach_and_log_err(cx);
2575                        }
2576                    }
2577                });
2578            }
2579        }
2580    }
2581}
2582
2583impl Entity for Workspace {
2584    type Event = Event;
2585}
2586
2587impl View for Workspace {
2588    fn ui_name() -> &'static str {
2589        "Workspace"
2590    }
2591
2592    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
2593        let theme = cx.global::<Settings>().theme.clone();
2594        Stack::new()
2595            .with_child(
2596                Flex::column()
2597                    .with_child(self.render_titlebar(&theme, cx))
2598                    .with_child(
2599                        Stack::new()
2600                            .with_child({
2601                                Flex::row()
2602                                    .with_children(
2603                                        if self.left_sidebar.read(cx).active_item().is_some() {
2604                                            Some(
2605                                                ChildView::new(&self.left_sidebar)
2606                                                    .flex(0.8, false)
2607                                                    .boxed(),
2608                                            )
2609                                        } else {
2610                                            None
2611                                        },
2612                                    )
2613                                    .with_child(
2614                                        FlexItem::new(
2615                                            Flex::column()
2616                                                .with_child(
2617                                                    FlexItem::new(self.center.render(
2618                                                        &theme,
2619                                                        &self.follower_states_by_leader,
2620                                                        self.project.read(cx).collaborators(),
2621                                                    ))
2622                                                    .flex(1., true)
2623                                                    .boxed(),
2624                                                )
2625                                                .with_children(self.dock.render(
2626                                                    &theme,
2627                                                    DockAnchor::Bottom,
2628                                                    cx,
2629                                                ))
2630                                                .boxed(),
2631                                        )
2632                                        .flex(1., true)
2633                                        .boxed(),
2634                                    )
2635                                    .with_children(self.dock.render(&theme, DockAnchor::Right, cx))
2636                                    .with_children(
2637                                        if self.right_sidebar.read(cx).active_item().is_some() {
2638                                            Some(
2639                                                ChildView::new(&self.right_sidebar)
2640                                                    .flex(0.8, false)
2641                                                    .boxed(),
2642                                            )
2643                                        } else {
2644                                            None
2645                                        },
2646                                    )
2647                                    .boxed()
2648                            })
2649                            .with_child(
2650                                Overlay::new(
2651                                    Stack::new()
2652                                        .with_children(self.dock.render(
2653                                            &theme,
2654                                            DockAnchor::Expanded,
2655                                            cx,
2656                                        ))
2657                                        .with_children(self.modal.as_ref().map(|m| {
2658                                            ChildView::new(m)
2659                                                .contained()
2660                                                .with_style(theme.workspace.modal)
2661                                                .aligned()
2662                                                .top()
2663                                                .boxed()
2664                                        }))
2665                                        .with_children(self.render_notifications(&theme.workspace))
2666                                        .boxed(),
2667                                )
2668                                .boxed(),
2669                            )
2670                            .flex(1.0, true)
2671                            .boxed(),
2672                    )
2673                    .with_child(ChildView::new(&self.status_bar).boxed())
2674                    .contained()
2675                    .with_background_color(theme.workspace.background)
2676                    .boxed(),
2677            )
2678            .with_children(DragAndDrop::render(cx))
2679            .with_children(self.render_disconnected_overlay(cx))
2680            .named("workspace")
2681    }
2682
2683    fn on_focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
2684        if cx.is_self_focused() {
2685            cx.focus(&self.active_pane);
2686        }
2687    }
2688
2689    fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
2690        let mut keymap = Self::default_keymap_context();
2691        if self.active_pane() == self.dock_pane() {
2692            keymap.set.insert("Dock".into());
2693        }
2694        keymap
2695    }
2696}
2697
2698pub trait WorkspaceHandle {
2699    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
2700}
2701
2702impl WorkspaceHandle for ViewHandle<Workspace> {
2703    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
2704        self.read(cx)
2705            .worktrees(cx)
2706            .flat_map(|worktree| {
2707                let worktree_id = worktree.read(cx).id();
2708                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
2709                    worktree_id,
2710                    path: f.path.clone(),
2711                })
2712            })
2713            .collect::<Vec<_>>()
2714    }
2715}
2716
2717pub struct AvatarRibbon {
2718    color: Color,
2719}
2720
2721impl AvatarRibbon {
2722    pub fn new(color: Color) -> AvatarRibbon {
2723        AvatarRibbon { color }
2724    }
2725}
2726
2727impl Element for AvatarRibbon {
2728    type LayoutState = ();
2729
2730    type PaintState = ();
2731
2732    fn layout(
2733        &mut self,
2734        constraint: gpui::SizeConstraint,
2735        _: &mut gpui::LayoutContext,
2736    ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
2737        (constraint.max, ())
2738    }
2739
2740    fn paint(
2741        &mut self,
2742        bounds: gpui::geometry::rect::RectF,
2743        _: gpui::geometry::rect::RectF,
2744        _: &mut Self::LayoutState,
2745        cx: &mut gpui::PaintContext,
2746    ) -> Self::PaintState {
2747        let mut path = PathBuilder::new();
2748        path.reset(bounds.lower_left());
2749        path.curve_to(
2750            bounds.origin() + vec2f(bounds.height(), 0.),
2751            bounds.origin(),
2752        );
2753        path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
2754        path.curve_to(bounds.lower_right(), bounds.upper_right());
2755        path.line_to(bounds.lower_left());
2756        cx.scene.push_path(path.build(self.color, None));
2757    }
2758
2759    fn dispatch_event(
2760        &mut self,
2761        _: &gpui::Event,
2762        _: RectF,
2763        _: RectF,
2764        _: &mut Self::LayoutState,
2765        _: &mut Self::PaintState,
2766        _: &mut gpui::EventContext,
2767    ) -> bool {
2768        false
2769    }
2770
2771    fn rect_for_text_range(
2772        &self,
2773        _: Range<usize>,
2774        _: RectF,
2775        _: RectF,
2776        _: &Self::LayoutState,
2777        _: &Self::PaintState,
2778        _: &gpui::MeasurementContext,
2779    ) -> Option<RectF> {
2780        None
2781    }
2782
2783    fn debug(
2784        &self,
2785        bounds: gpui::geometry::rect::RectF,
2786        _: &Self::LayoutState,
2787        _: &Self::PaintState,
2788        _: &gpui::DebugContext,
2789    ) -> gpui::json::Value {
2790        json::json!({
2791            "type": "AvatarRibbon",
2792            "bounds": bounds.to_json(),
2793            "color": self.color.to_json(),
2794        })
2795    }
2796}
2797
2798impl std::fmt::Debug for OpenPaths {
2799    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2800        f.debug_struct("OpenPaths")
2801            .field("paths", &self.paths)
2802            .finish()
2803    }
2804}
2805
2806fn open(_: &Open, cx: &mut MutableAppContext) {
2807    let mut paths = cx.prompt_for_paths(PathPromptOptions {
2808        files: true,
2809        directories: true,
2810        multiple: true,
2811    });
2812    cx.spawn(|mut cx| async move {
2813        if let Some(paths) = paths.recv().await.flatten() {
2814            cx.update(|cx| cx.dispatch_global_action(OpenPaths { paths }));
2815        }
2816    })
2817    .detach();
2818}
2819
2820pub struct WorkspaceCreated(WeakViewHandle<Workspace>);
2821
2822pub fn activate_workspace_for_project(
2823    cx: &mut MutableAppContext,
2824    predicate: impl Fn(&mut Project, &mut ModelContext<Project>) -> bool,
2825) -> Option<ViewHandle<Workspace>> {
2826    for window_id in cx.window_ids().collect::<Vec<_>>() {
2827        if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
2828            let project = workspace_handle.read(cx).project.clone();
2829            if project.update(cx, &predicate) {
2830                cx.activate_window(window_id);
2831                return Some(workspace_handle);
2832            }
2833        }
2834    }
2835    None
2836}
2837
2838#[allow(clippy::type_complexity)]
2839pub fn open_paths(
2840    abs_paths: &[PathBuf],
2841    app_state: &Arc<AppState>,
2842    cx: &mut MutableAppContext,
2843) -> Task<(
2844    ViewHandle<Workspace>,
2845    Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>,
2846)> {
2847    log::info!("open paths {:?}", abs_paths);
2848
2849    // Open paths in existing workspace if possible
2850    let existing =
2851        activate_workspace_for_project(cx, |project, cx| project.contains_paths(abs_paths, cx));
2852
2853    let app_state = app_state.clone();
2854    let abs_paths = abs_paths.to_vec();
2855    cx.spawn(|mut cx| async move {
2856        let mut new_project = None;
2857        let workspace = if let Some(existing) = existing {
2858            existing
2859        } else {
2860            let contains_directory =
2861                futures::future::join_all(abs_paths.iter().map(|path| app_state.fs.is_file(path)))
2862                    .await
2863                    .contains(&false);
2864
2865            cx.add_window((app_state.build_window_options)(), |cx| {
2866                let project = Project::local(
2867                    false,
2868                    app_state.client.clone(),
2869                    app_state.user_store.clone(),
2870                    app_state.project_store.clone(),
2871                    app_state.languages.clone(),
2872                    app_state.fs.clone(),
2873                    cx,
2874                );
2875                new_project = Some(project.clone());
2876                let mut workspace = Workspace::new(project, app_state.default_item_factory, cx);
2877                (app_state.initialize_workspace)(&mut workspace, &app_state, cx);
2878                if contains_directory {
2879                    workspace.toggle_sidebar(SidebarSide::Left, cx);
2880                }
2881                workspace
2882            })
2883            .1
2884        };
2885
2886        let items = workspace
2887            .update(&mut cx, |workspace, cx| {
2888                workspace.open_paths(abs_paths, true, cx)
2889            })
2890            .await;
2891
2892        if let Some(project) = new_project {
2893            project
2894                .update(&mut cx, |project, cx| project.restore_state(cx))
2895                .await
2896                .log_err();
2897        }
2898
2899        (workspace, items)
2900    })
2901}
2902
2903pub fn join_project(
2904    contact: Arc<Contact>,
2905    project_index: usize,
2906    app_state: &Arc<AppState>,
2907    cx: &mut MutableAppContext,
2908) {
2909    let project_id = contact.projects[project_index].id;
2910
2911    for window_id in cx.window_ids().collect::<Vec<_>>() {
2912        if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
2913            if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
2914                cx.activate_window(window_id);
2915                return;
2916            }
2917        }
2918    }
2919
2920    cx.add_window((app_state.build_window_options)(), |cx| {
2921        WaitingRoom::new(contact, project_index, app_state.clone(), cx)
2922    });
2923}
2924
2925fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
2926    let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
2927        let mut workspace = Workspace::new(
2928            Project::local(
2929                false,
2930                app_state.client.clone(),
2931                app_state.user_store.clone(),
2932                app_state.project_store.clone(),
2933                app_state.languages.clone(),
2934                app_state.fs.clone(),
2935                cx,
2936            ),
2937            app_state.default_item_factory,
2938            cx,
2939        );
2940        (app_state.initialize_workspace)(&mut workspace, app_state, cx);
2941        workspace
2942    });
2943    cx.dispatch_action_at(window_id, workspace.id(), NewFile);
2944}
2945
2946#[cfg(test)]
2947mod tests {
2948    use std::cell::Cell;
2949
2950    use crate::sidebar::SidebarItem;
2951
2952    use super::*;
2953    use gpui::{executor::Deterministic, ModelHandle, TestAppContext, ViewContext};
2954    use project::{FakeFs, Project, ProjectEntryId};
2955    use serde_json::json;
2956
2957    pub fn default_item_factory(
2958        _workspace: &mut Workspace,
2959        _cx: &mut ViewContext<Workspace>,
2960    ) -> Box<dyn ItemHandle> {
2961        unimplemented!();
2962    }
2963
2964    #[gpui::test]
2965    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
2966        cx.foreground().forbid_parking();
2967        Settings::test_async(cx);
2968
2969        let fs = FakeFs::new(cx.background());
2970        let project = Project::test(fs, [], cx).await;
2971        let (_, workspace) =
2972            cx.add_window(|cx| Workspace::new(project.clone(), default_item_factory, cx));
2973
2974        // Adding an item with no ambiguity renders the tab without detail.
2975        let item1 = cx.add_view(&workspace, |_| {
2976            let mut item = TestItem::new();
2977            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
2978            item
2979        });
2980        workspace.update(cx, |workspace, cx| {
2981            workspace.add_item(Box::new(item1.clone()), cx);
2982        });
2983        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), None));
2984
2985        // Adding an item that creates ambiguity increases the level of detail on
2986        // both tabs.
2987        let item2 = cx.add_view(&workspace, |_| {
2988            let mut item = TestItem::new();
2989            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
2990            item
2991        });
2992        workspace.update(cx, |workspace, cx| {
2993            workspace.add_item(Box::new(item2.clone()), cx);
2994        });
2995        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2996        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2997
2998        // Adding an item that creates ambiguity increases the level of detail only
2999        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
3000        // we stop at the highest detail available.
3001        let item3 = cx.add_view(&workspace, |_| {
3002            let mut item = TestItem::new();
3003            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
3004            item
3005        });
3006        workspace.update(cx, |workspace, cx| {
3007            workspace.add_item(Box::new(item3.clone()), cx);
3008        });
3009        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
3010        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
3011        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
3012    }
3013
3014    #[gpui::test]
3015    async fn test_tracking_active_path(cx: &mut TestAppContext) {
3016        cx.foreground().forbid_parking();
3017        Settings::test_async(cx);
3018        let fs = FakeFs::new(cx.background());
3019        fs.insert_tree(
3020            "/root1",
3021            json!({
3022                "one.txt": "",
3023                "two.txt": "",
3024            }),
3025        )
3026        .await;
3027        fs.insert_tree(
3028            "/root2",
3029            json!({
3030                "three.txt": "",
3031            }),
3032        )
3033        .await;
3034
3035        let project = Project::test(fs, ["root1".as_ref()], cx).await;
3036        let (window_id, workspace) =
3037            cx.add_window(|cx| Workspace::new(project.clone(), default_item_factory, cx));
3038        let worktree_id = project.read_with(cx, |project, cx| {
3039            project.worktrees(cx).next().unwrap().read(cx).id()
3040        });
3041
3042        let item1 = cx.add_view(&workspace, |_| {
3043            let mut item = TestItem::new();
3044            item.project_path = Some((worktree_id, "one.txt").into());
3045            item
3046        });
3047        let item2 = cx.add_view(&workspace, |_| {
3048            let mut item = TestItem::new();
3049            item.project_path = Some((worktree_id, "two.txt").into());
3050            item
3051        });
3052
3053        // Add an item to an empty pane
3054        workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item1), cx));
3055        project.read_with(cx, |project, cx| {
3056            assert_eq!(
3057                project.active_entry(),
3058                project
3059                    .entry_for_path(&(worktree_id, "one.txt").into(), cx)
3060                    .map(|e| e.id)
3061            );
3062        });
3063        assert_eq!(
3064            cx.current_window_title(window_id).as_deref(),
3065            Some("one.txt — root1")
3066        );
3067
3068        // Add a second item to a non-empty pane
3069        workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item2), cx));
3070        assert_eq!(
3071            cx.current_window_title(window_id).as_deref(),
3072            Some("two.txt — root1")
3073        );
3074        project.read_with(cx, |project, cx| {
3075            assert_eq!(
3076                project.active_entry(),
3077                project
3078                    .entry_for_path(&(worktree_id, "two.txt").into(), cx)
3079                    .map(|e| e.id)
3080            );
3081        });
3082
3083        // Close the active item
3084        workspace
3085            .update(cx, |workspace, cx| {
3086                Pane::close_active_item(workspace, &Default::default(), cx).unwrap()
3087            })
3088            .await
3089            .unwrap();
3090        assert_eq!(
3091            cx.current_window_title(window_id).as_deref(),
3092            Some("one.txt — root1")
3093        );
3094        project.read_with(cx, |project, cx| {
3095            assert_eq!(
3096                project.active_entry(),
3097                project
3098                    .entry_for_path(&(worktree_id, "one.txt").into(), cx)
3099                    .map(|e| e.id)
3100            );
3101        });
3102
3103        // Add a project folder
3104        project
3105            .update(cx, |project, cx| {
3106                project.find_or_create_local_worktree("/root2", true, cx)
3107            })
3108            .await
3109            .unwrap();
3110        assert_eq!(
3111            cx.current_window_title(window_id).as_deref(),
3112            Some("one.txt — root1, root2")
3113        );
3114
3115        // Remove a project folder
3116        project.update(cx, |project, cx| {
3117            project.remove_worktree(worktree_id, cx);
3118        });
3119        assert_eq!(
3120            cx.current_window_title(window_id).as_deref(),
3121            Some("one.txt — root2")
3122        );
3123    }
3124
3125    #[gpui::test]
3126    async fn test_close_window(cx: &mut TestAppContext) {
3127        cx.foreground().forbid_parking();
3128        Settings::test_async(cx);
3129        let fs = FakeFs::new(cx.background());
3130        fs.insert_tree("/root", json!({ "one": "" })).await;
3131
3132        let project = Project::test(fs, ["root".as_ref()], cx).await;
3133        let (window_id, workspace) =
3134            cx.add_window(|cx| Workspace::new(project.clone(), default_item_factory, cx));
3135
3136        // When there are no dirty items, there's nothing to do.
3137        let item1 = cx.add_view(&workspace, |_| TestItem::new());
3138        workspace.update(cx, |w, cx| w.add_item(Box::new(item1.clone()), cx));
3139        let task = workspace.update(cx, |w, cx| w.prepare_to_close(cx));
3140        assert!(task.await.unwrap());
3141
3142        // When there are dirty untitled items, prompt to save each one. If the user
3143        // cancels any prompt, then abort.
3144        let item2 = cx.add_view(&workspace, |_| {
3145            let mut item = TestItem::new();
3146            item.is_dirty = true;
3147            item
3148        });
3149        let item3 = cx.add_view(&workspace, |_| {
3150            let mut item = TestItem::new();
3151            item.is_dirty = true;
3152            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3153            item
3154        });
3155        workspace.update(cx, |w, cx| {
3156            w.add_item(Box::new(item2.clone()), cx);
3157            w.add_item(Box::new(item3.clone()), cx);
3158        });
3159        let task = workspace.update(cx, |w, cx| w.prepare_to_close(cx));
3160        cx.foreground().run_until_parked();
3161        cx.simulate_prompt_answer(window_id, 2 /* cancel */);
3162        cx.foreground().run_until_parked();
3163        assert!(!cx.has_pending_prompt(window_id));
3164        assert!(!task.await.unwrap());
3165    }
3166
3167    #[gpui::test]
3168    async fn test_close_pane_items(cx: &mut TestAppContext) {
3169        cx.foreground().forbid_parking();
3170        Settings::test_async(cx);
3171        let fs = FakeFs::new(cx.background());
3172
3173        let project = Project::test(fs, None, cx).await;
3174        let (window_id, workspace) =
3175            cx.add_window(|cx| Workspace::new(project, default_item_factory, cx));
3176
3177        let item1 = cx.add_view(&workspace, |_| {
3178            let mut item = TestItem::new();
3179            item.is_dirty = true;
3180            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3181            item
3182        });
3183        let item2 = cx.add_view(&workspace, |_| {
3184            let mut item = TestItem::new();
3185            item.is_dirty = true;
3186            item.has_conflict = true;
3187            item.project_entry_ids = vec![ProjectEntryId::from_proto(2)];
3188            item
3189        });
3190        let item3 = cx.add_view(&workspace, |_| {
3191            let mut item = TestItem::new();
3192            item.is_dirty = true;
3193            item.has_conflict = true;
3194            item.project_entry_ids = vec![ProjectEntryId::from_proto(3)];
3195            item
3196        });
3197        let item4 = cx.add_view(&workspace, |_| {
3198            let mut item = TestItem::new();
3199            item.is_dirty = true;
3200            item
3201        });
3202        let pane = workspace.update(cx, |workspace, cx| {
3203            workspace.add_item(Box::new(item1.clone()), cx);
3204            workspace.add_item(Box::new(item2.clone()), cx);
3205            workspace.add_item(Box::new(item3.clone()), cx);
3206            workspace.add_item(Box::new(item4.clone()), cx);
3207            workspace.active_pane().clone()
3208        });
3209
3210        let close_items = workspace.update(cx, |workspace, cx| {
3211            pane.update(cx, |pane, cx| {
3212                pane.activate_item(1, true, true, cx);
3213                assert_eq!(pane.active_item().unwrap().id(), item2.id());
3214            });
3215
3216            let item1_id = item1.id();
3217            let item3_id = item3.id();
3218            let item4_id = item4.id();
3219            Pane::close_items(workspace, pane.clone(), cx, move |id| {
3220                [item1_id, item3_id, item4_id].contains(&id)
3221            })
3222        });
3223
3224        cx.foreground().run_until_parked();
3225        pane.read_with(cx, |pane, _| {
3226            assert_eq!(pane.items().count(), 4);
3227            assert_eq!(pane.active_item().unwrap().id(), item1.id());
3228        });
3229
3230        cx.simulate_prompt_answer(window_id, 0);
3231        cx.foreground().run_until_parked();
3232        pane.read_with(cx, |pane, cx| {
3233            assert_eq!(item1.read(cx).save_count, 1);
3234            assert_eq!(item1.read(cx).save_as_count, 0);
3235            assert_eq!(item1.read(cx).reload_count, 0);
3236            assert_eq!(pane.items().count(), 3);
3237            assert_eq!(pane.active_item().unwrap().id(), item3.id());
3238        });
3239
3240        cx.simulate_prompt_answer(window_id, 1);
3241        cx.foreground().run_until_parked();
3242        pane.read_with(cx, |pane, cx| {
3243            assert_eq!(item3.read(cx).save_count, 0);
3244            assert_eq!(item3.read(cx).save_as_count, 0);
3245            assert_eq!(item3.read(cx).reload_count, 1);
3246            assert_eq!(pane.items().count(), 2);
3247            assert_eq!(pane.active_item().unwrap().id(), item4.id());
3248        });
3249
3250        cx.simulate_prompt_answer(window_id, 0);
3251        cx.foreground().run_until_parked();
3252        cx.simulate_new_path_selection(|_| Some(Default::default()));
3253        close_items.await.unwrap();
3254        pane.read_with(cx, |pane, cx| {
3255            assert_eq!(item4.read(cx).save_count, 0);
3256            assert_eq!(item4.read(cx).save_as_count, 1);
3257            assert_eq!(item4.read(cx).reload_count, 0);
3258            assert_eq!(pane.items().count(), 1);
3259            assert_eq!(pane.active_item().unwrap().id(), item2.id());
3260        });
3261    }
3262
3263    #[gpui::test]
3264    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
3265        cx.foreground().forbid_parking();
3266        Settings::test_async(cx);
3267        let fs = FakeFs::new(cx.background());
3268
3269        let project = Project::test(fs, [], cx).await;
3270        let (window_id, workspace) =
3271            cx.add_window(|cx| Workspace::new(project, default_item_factory, cx));
3272
3273        // Create several workspace items with single project entries, and two
3274        // workspace items with multiple project entries.
3275        let single_entry_items = (0..=4)
3276            .map(|project_entry_id| {
3277                let mut item = TestItem::new();
3278                item.is_dirty = true;
3279                item.project_entry_ids = vec![ProjectEntryId::from_proto(project_entry_id)];
3280                item.is_singleton = true;
3281                item
3282            })
3283            .collect::<Vec<_>>();
3284        let item_2_3 = {
3285            let mut item = TestItem::new();
3286            item.is_dirty = true;
3287            item.is_singleton = false;
3288            item.project_entry_ids =
3289                vec![ProjectEntryId::from_proto(2), ProjectEntryId::from_proto(3)];
3290            item
3291        };
3292        let item_3_4 = {
3293            let mut item = TestItem::new();
3294            item.is_dirty = true;
3295            item.is_singleton = false;
3296            item.project_entry_ids =
3297                vec![ProjectEntryId::from_proto(3), ProjectEntryId::from_proto(4)];
3298            item
3299        };
3300
3301        // Create two panes that contain the following project entries:
3302        //   left pane:
3303        //     multi-entry items:   (2, 3)
3304        //     single-entry items:  0, 1, 2, 3, 4
3305        //   right pane:
3306        //     single-entry items:  1
3307        //     multi-entry items:   (3, 4)
3308        let left_pane = workspace.update(cx, |workspace, cx| {
3309            let left_pane = workspace.active_pane().clone();
3310            workspace.add_item(Box::new(cx.add_view(|_| item_2_3.clone())), cx);
3311            for item in &single_entry_items {
3312                workspace.add_item(Box::new(cx.add_view(|_| item.clone())), cx);
3313            }
3314            left_pane.update(cx, |pane, cx| {
3315                pane.activate_item(2, true, true, cx);
3316            });
3317
3318            workspace
3319                .split_pane(left_pane.clone(), SplitDirection::Right, cx)
3320                .unwrap();
3321
3322            left_pane
3323        });
3324
3325        //Need to cause an effect flush in order to respect new focus
3326        workspace.update(cx, |workspace, cx| {
3327            workspace.add_item(Box::new(cx.add_view(|_| item_3_4.clone())), cx);
3328            cx.focus(left_pane.clone());
3329        });
3330
3331        // When closing all of the items in the left pane, we should be prompted twice:
3332        // once for project entry 0, and once for project entry 2. After those two
3333        // prompts, the task should complete.
3334
3335        let close = workspace.update(cx, |workspace, cx| {
3336            Pane::close_items(workspace, left_pane.clone(), cx, |_| true)
3337        });
3338
3339        cx.foreground().run_until_parked();
3340        left_pane.read_with(cx, |pane, cx| {
3341            assert_eq!(
3342                pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
3343                &[ProjectEntryId::from_proto(0)]
3344            );
3345        });
3346        cx.simulate_prompt_answer(window_id, 0);
3347
3348        cx.foreground().run_until_parked();
3349        left_pane.read_with(cx, |pane, cx| {
3350            assert_eq!(
3351                pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
3352                &[ProjectEntryId::from_proto(2)]
3353            );
3354        });
3355        cx.simulate_prompt_answer(window_id, 0);
3356
3357        cx.foreground().run_until_parked();
3358        close.await.unwrap();
3359        left_pane.read_with(cx, |pane, _| {
3360            assert_eq!(pane.items().count(), 0);
3361        });
3362    }
3363
3364    #[gpui::test]
3365    async fn test_autosave(deterministic: Arc<Deterministic>, cx: &mut gpui::TestAppContext) {
3366        deterministic.forbid_parking();
3367
3368        Settings::test_async(cx);
3369        let fs = FakeFs::new(cx.background());
3370
3371        let project = Project::test(fs, [], cx).await;
3372        let (window_id, workspace) =
3373            cx.add_window(|cx| Workspace::new(project, default_item_factory, cx));
3374
3375        let item = cx.add_view(&workspace, |_| {
3376            let mut item = TestItem::new();
3377            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3378            item
3379        });
3380        let item_id = item.id();
3381        workspace.update(cx, |workspace, cx| {
3382            workspace.add_item(Box::new(item.clone()), cx);
3383        });
3384
3385        // Autosave on window change.
3386        item.update(cx, |item, cx| {
3387            cx.update_global(|settings: &mut Settings, _| {
3388                settings.autosave = Autosave::OnWindowChange;
3389            });
3390            item.is_dirty = true;
3391        });
3392
3393        // Deactivating the window saves the file.
3394        cx.simulate_window_activation(None);
3395        deterministic.run_until_parked();
3396        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
3397
3398        // Autosave on focus change.
3399        item.update(cx, |item, cx| {
3400            cx.focus_self();
3401            cx.update_global(|settings: &mut Settings, _| {
3402                settings.autosave = Autosave::OnFocusChange;
3403            });
3404            item.is_dirty = true;
3405        });
3406
3407        // Blurring the item saves the file.
3408        item.update(cx, |_, cx| cx.blur());
3409        deterministic.run_until_parked();
3410        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
3411
3412        // Deactivating the window still saves the file.
3413        cx.simulate_window_activation(Some(window_id));
3414        item.update(cx, |item, cx| {
3415            cx.focus_self();
3416            item.is_dirty = true;
3417        });
3418        cx.simulate_window_activation(None);
3419
3420        deterministic.run_until_parked();
3421        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
3422
3423        // Autosave after delay.
3424        item.update(cx, |item, cx| {
3425            cx.update_global(|settings: &mut Settings, _| {
3426                settings.autosave = Autosave::AfterDelay { milliseconds: 500 };
3427            });
3428            item.is_dirty = true;
3429            cx.emit(TestItemEvent::Edit);
3430        });
3431
3432        // Delay hasn't fully expired, so the file is still dirty and unsaved.
3433        deterministic.advance_clock(Duration::from_millis(250));
3434        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
3435
3436        // After delay expires, the file is saved.
3437        deterministic.advance_clock(Duration::from_millis(250));
3438        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
3439
3440        // Autosave on focus change, ensuring closing the tab counts as such.
3441        item.update(cx, |item, cx| {
3442            cx.update_global(|settings: &mut Settings, _| {
3443                settings.autosave = Autosave::OnFocusChange;
3444            });
3445            item.is_dirty = true;
3446        });
3447
3448        workspace
3449            .update(cx, |workspace, cx| {
3450                let pane = workspace.active_pane().clone();
3451                Pane::close_items(workspace, pane, cx, move |id| id == item_id)
3452            })
3453            .await
3454            .unwrap();
3455        assert!(!cx.has_pending_prompt(window_id));
3456        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3457
3458        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
3459        workspace.update(cx, |workspace, cx| {
3460            workspace.add_item(Box::new(item.clone()), cx);
3461        });
3462        item.update(cx, |item, cx| {
3463            item.project_entry_ids = Default::default();
3464            item.is_dirty = true;
3465            cx.blur();
3466        });
3467        deterministic.run_until_parked();
3468        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3469
3470        // Ensure autosave is prevented for deleted files also when closing the buffer.
3471        let _close_items = workspace.update(cx, |workspace, cx| {
3472            let pane = workspace.active_pane().clone();
3473            Pane::close_items(workspace, pane, cx, move |id| id == item_id)
3474        });
3475        deterministic.run_until_parked();
3476        assert!(cx.has_pending_prompt(window_id));
3477        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3478    }
3479
3480    #[gpui::test]
3481    async fn test_pane_navigation(
3482        deterministic: Arc<Deterministic>,
3483        cx: &mut gpui::TestAppContext,
3484    ) {
3485        deterministic.forbid_parking();
3486        Settings::test_async(cx);
3487        let fs = FakeFs::new(cx.background());
3488
3489        let project = Project::test(fs, [], cx).await;
3490        let (_, workspace) = cx.add_window(|cx| Workspace::new(project, default_item_factory, cx));
3491
3492        let item = cx.add_view(&workspace, |_| {
3493            let mut item = TestItem::new();
3494            item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3495            item
3496        });
3497        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
3498        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
3499        let toolbar_notify_count = Rc::new(RefCell::new(0));
3500
3501        workspace.update(cx, |workspace, cx| {
3502            workspace.add_item(Box::new(item.clone()), cx);
3503            let toolbar_notification_count = toolbar_notify_count.clone();
3504            cx.observe(&toolbar, move |_, _, _| {
3505                *toolbar_notification_count.borrow_mut() += 1
3506            })
3507            .detach();
3508        });
3509
3510        pane.read_with(cx, |pane, _| {
3511            assert!(!pane.can_navigate_backward());
3512            assert!(!pane.can_navigate_forward());
3513        });
3514
3515        item.update(cx, |item, cx| {
3516            item.set_state("one".to_string(), cx);
3517        });
3518
3519        // Toolbar must be notified to re-render the navigation buttons
3520        assert_eq!(*toolbar_notify_count.borrow(), 1);
3521
3522        pane.read_with(cx, |pane, _| {
3523            assert!(pane.can_navigate_backward());
3524            assert!(!pane.can_navigate_forward());
3525        });
3526
3527        workspace
3528            .update(cx, |workspace, cx| {
3529                Pane::go_back(workspace, Some(pane.clone()), cx)
3530            })
3531            .await;
3532
3533        assert_eq!(*toolbar_notify_count.borrow(), 3);
3534        pane.read_with(cx, |pane, _| {
3535            assert!(!pane.can_navigate_backward());
3536            assert!(pane.can_navigate_forward());
3537        });
3538    }
3539
3540    pub struct TestItem {
3541        state: String,
3542        pub label: String,
3543        save_count: usize,
3544        save_as_count: usize,
3545        reload_count: usize,
3546        is_dirty: bool,
3547        is_singleton: bool,
3548        has_conflict: bool,
3549        project_entry_ids: Vec<ProjectEntryId>,
3550        project_path: Option<ProjectPath>,
3551        nav_history: Option<ItemNavHistory>,
3552        tab_descriptions: Option<Vec<&'static str>>,
3553        tab_detail: Cell<Option<usize>>,
3554    }
3555
3556    pub enum TestItemEvent {
3557        Edit,
3558    }
3559
3560    impl Clone for TestItem {
3561        fn clone(&self) -> Self {
3562            Self {
3563                state: self.state.clone(),
3564                label: self.label.clone(),
3565                save_count: self.save_count,
3566                save_as_count: self.save_as_count,
3567                reload_count: self.reload_count,
3568                is_dirty: self.is_dirty,
3569                is_singleton: self.is_singleton,
3570                has_conflict: self.has_conflict,
3571                project_entry_ids: self.project_entry_ids.clone(),
3572                project_path: self.project_path.clone(),
3573                nav_history: None,
3574                tab_descriptions: None,
3575                tab_detail: Default::default(),
3576            }
3577        }
3578    }
3579
3580    impl TestItem {
3581        pub fn new() -> Self {
3582            Self {
3583                state: String::new(),
3584                label: String::new(),
3585                save_count: 0,
3586                save_as_count: 0,
3587                reload_count: 0,
3588                is_dirty: false,
3589                has_conflict: false,
3590                project_entry_ids: Vec::new(),
3591                project_path: None,
3592                is_singleton: true,
3593                nav_history: None,
3594                tab_descriptions: None,
3595                tab_detail: Default::default(),
3596            }
3597        }
3598
3599        pub fn with_label(mut self, state: &str) -> Self {
3600            self.label = state.to_string();
3601            self
3602        }
3603
3604        pub fn with_singleton(mut self, singleton: bool) -> Self {
3605            self.is_singleton = singleton;
3606            self
3607        }
3608
3609        pub fn with_project_entry_ids(mut self, project_entry_ids: &[u64]) -> Self {
3610            self.project_entry_ids.extend(
3611                project_entry_ids
3612                    .iter()
3613                    .copied()
3614                    .map(ProjectEntryId::from_proto),
3615            );
3616            self
3617        }
3618
3619        fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
3620            self.push_to_nav_history(cx);
3621            self.state = state;
3622        }
3623
3624        fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
3625            if let Some(history) = &mut self.nav_history {
3626                history.push(Some(Box::new(self.state.clone())), cx);
3627            }
3628        }
3629    }
3630
3631    impl Entity for TestItem {
3632        type Event = TestItemEvent;
3633    }
3634
3635    impl View for TestItem {
3636        fn ui_name() -> &'static str {
3637            "TestItem"
3638        }
3639
3640        fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3641            Empty::new().boxed()
3642        }
3643    }
3644
3645    impl Item for TestItem {
3646        fn tab_description<'a>(&'a self, detail: usize, _: &'a AppContext) -> Option<Cow<'a, str>> {
3647            self.tab_descriptions.as_ref().and_then(|descriptions| {
3648                let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
3649                Some(description.into())
3650            })
3651        }
3652
3653        fn tab_content(&self, detail: Option<usize>, _: &theme::Tab, _: &AppContext) -> ElementBox {
3654            self.tab_detail.set(detail);
3655            Empty::new().boxed()
3656        }
3657
3658        fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
3659            self.project_path.clone()
3660        }
3661
3662        fn project_entry_ids(&self, _: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
3663            self.project_entry_ids.iter().copied().collect()
3664        }
3665
3666        fn is_singleton(&self, _: &AppContext) -> bool {
3667            self.is_singleton
3668        }
3669
3670        fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
3671            self.nav_history = Some(history);
3672        }
3673
3674        fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
3675            let state = *state.downcast::<String>().unwrap_or_default();
3676            if state != self.state {
3677                self.state = state;
3678                true
3679            } else {
3680                false
3681            }
3682        }
3683
3684        fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
3685            self.push_to_nav_history(cx);
3686        }
3687
3688        fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
3689        where
3690            Self: Sized,
3691        {
3692            Some(self.clone())
3693        }
3694
3695        fn is_dirty(&self, _: &AppContext) -> bool {
3696            self.is_dirty
3697        }
3698
3699        fn has_conflict(&self, _: &AppContext) -> bool {
3700            self.has_conflict
3701        }
3702
3703        fn can_save(&self, _: &AppContext) -> bool {
3704            !self.project_entry_ids.is_empty()
3705        }
3706
3707        fn save(
3708            &mut self,
3709            _: ModelHandle<Project>,
3710            _: &mut ViewContext<Self>,
3711        ) -> Task<anyhow::Result<()>> {
3712            self.save_count += 1;
3713            self.is_dirty = false;
3714            Task::ready(Ok(()))
3715        }
3716
3717        fn save_as(
3718            &mut self,
3719            _: ModelHandle<Project>,
3720            _: std::path::PathBuf,
3721            _: &mut ViewContext<Self>,
3722        ) -> Task<anyhow::Result<()>> {
3723            self.save_as_count += 1;
3724            self.is_dirty = false;
3725            Task::ready(Ok(()))
3726        }
3727
3728        fn reload(
3729            &mut self,
3730            _: ModelHandle<Project>,
3731            _: &mut ViewContext<Self>,
3732        ) -> Task<anyhow::Result<()>> {
3733            self.reload_count += 1;
3734            self.is_dirty = false;
3735            Task::ready(Ok(()))
3736        }
3737
3738        fn to_item_events(_: &Self::Event) -> Vec<ItemEvent> {
3739            vec![ItemEvent::UpdateTab, ItemEvent::Edit]
3740        }
3741    }
3742
3743    impl SidebarItem for TestItem {}
3744}