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