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