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