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