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