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