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