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