workspace.rs

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