workspace.rs

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