workspace.rs

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