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