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