workspace.rs

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