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