workspace.rs

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