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