workspace.rs

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