workspace.rs

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