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