workspace.rs

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