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