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