workspace.rs

   1pub mod pane;
   2pub mod pane_group;
   3pub mod settings;
   4pub mod sidebar;
   5mod status_bar;
   6
   7use anyhow::{anyhow, Result};
   8use client::{Authenticate, ChannelList, Client, User, UserStore};
   9use clock::ReplicaId;
  10use collections::HashSet;
  11use gpui::{
  12    action,
  13    color::Color,
  14    elements::*,
  15    geometry::{vector::vec2f, PathBuilder},
  16    json::{self, to_string_pretty, ToJson},
  17    keymap::Binding,
  18    platform::{CursorStyle, WindowOptions},
  19    AnyViewHandle, AppContext, ClipboardItem, Entity, ModelContext, ModelHandle, MutableAppContext,
  20    PathPromptOptions, PromptLevel, RenderContext, Task, View, ViewContext, ViewHandle,
  21    WeakModelHandle,
  22};
  23use language::LanguageRegistry;
  24use log::error;
  25pub use pane::*;
  26pub use pane_group::*;
  27use parking_lot::Mutex;
  28use postage::{prelude::Stream, watch};
  29use project::{fs, Fs, Project, ProjectPath, Worktree};
  30pub use settings::Settings;
  31use sidebar::{Side, Sidebar, SidebarItemId, ToggleSidebarItem, ToggleSidebarItemFocus};
  32use status_bar::StatusBar;
  33pub use status_bar::StatusItemView;
  34use std::{
  35    future::Future,
  36    hash::{Hash, Hasher},
  37    path::{Path, PathBuf},
  38    sync::Arc,
  39};
  40use theme::{Theme, ThemeRegistry};
  41
  42action!(Open, Arc<AppState>);
  43action!(OpenNew, Arc<AppState>);
  44action!(OpenPaths, OpenParams);
  45action!(ToggleShare);
  46action!(JoinProject, JoinProjectParams);
  47action!(Save);
  48action!(DebugElements);
  49
  50pub fn init(cx: &mut MutableAppContext) {
  51    cx.add_global_action(open);
  52    cx.add_global_action(move |action: &OpenPaths, cx: &mut MutableAppContext| {
  53        open_paths(&action.0.paths, &action.0.app_state, cx).detach();
  54    });
  55    cx.add_global_action(move |action: &OpenNew, cx: &mut MutableAppContext| {
  56        open_new(&action.0, cx)
  57    });
  58    cx.add_global_action(move |action: &JoinProject, cx: &mut MutableAppContext| {
  59        join_project(action.0.project_id, &action.0.app_state, cx).detach();
  60    });
  61
  62    cx.add_action(Workspace::toggle_share);
  63    cx.add_action(Workspace::save_active_item);
  64    cx.add_action(Workspace::debug_elements);
  65    cx.add_action(Workspace::toggle_sidebar_item);
  66    cx.add_action(Workspace::toggle_sidebar_item_focus);
  67    cx.add_bindings(vec![
  68        Binding::new("cmd-s", Save, None),
  69        Binding::new("cmd-alt-i", DebugElements, None),
  70        Binding::new(
  71            "cmd-shift-!",
  72            ToggleSidebarItem(SidebarItemId {
  73                side: Side::Left,
  74                item_index: 0,
  75            }),
  76            None,
  77        ),
  78        Binding::new(
  79            "cmd-1",
  80            ToggleSidebarItemFocus(SidebarItemId {
  81                side: Side::Left,
  82                item_index: 0,
  83            }),
  84            None,
  85        ),
  86    ]);
  87    pane::init(cx);
  88}
  89
  90pub struct AppState {
  91    pub settings_tx: Arc<Mutex<watch::Sender<Settings>>>,
  92    pub settings: watch::Receiver<Settings>,
  93    pub languages: Arc<LanguageRegistry>,
  94    pub themes: Arc<ThemeRegistry>,
  95    pub client: Arc<client::Client>,
  96    pub user_store: ModelHandle<client::UserStore>,
  97    pub fs: Arc<dyn fs::Fs>,
  98    pub channel_list: ModelHandle<client::ChannelList>,
  99    pub path_openers: Arc<[Box<dyn EntryOpener>]>,
 100    pub build_window_options: &'static dyn Fn() -> WindowOptions<'static>,
 101    pub build_workspace: &'static dyn Fn(
 102        ModelHandle<Project>,
 103        &Arc<AppState>,
 104        &mut ViewContext<Workspace>,
 105    ) -> Workspace,
 106}
 107
 108#[derive(Clone)]
 109pub struct OpenParams {
 110    pub paths: Vec<PathBuf>,
 111    pub app_state: Arc<AppState>,
 112}
 113
 114#[derive(Clone)]
 115pub struct JoinProjectParams {
 116    pub project_id: u64,
 117    pub app_state: Arc<AppState>,
 118}
 119
 120pub trait EntryOpener {
 121    fn open(
 122        &self,
 123        worktree: &mut Worktree,
 124        path: ProjectPath,
 125        cx: &mut ModelContext<Worktree>,
 126    ) -> Option<Task<Result<Box<dyn ItemHandle>>>>;
 127}
 128
 129pub trait Item: Entity + Sized {
 130    type View: ItemView;
 131
 132    fn build_view(
 133        handle: ModelHandle<Self>,
 134        settings: watch::Receiver<Settings>,
 135        cx: &mut ViewContext<Self::View>,
 136    ) -> Self::View;
 137
 138    fn project_path(&self) -> Option<ProjectPath>;
 139}
 140
 141pub trait ItemView: View {
 142    type ItemHandle: ItemHandle;
 143
 144    fn item_handle(&self, cx: &AppContext) -> Self::ItemHandle;
 145    fn title(&self, cx: &AppContext) -> String;
 146    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 147    fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
 148    where
 149        Self: Sized,
 150    {
 151        None
 152    }
 153    fn is_dirty(&self, _: &AppContext) -> bool {
 154        false
 155    }
 156    fn has_conflict(&self, _: &AppContext) -> bool {
 157        false
 158    }
 159    fn can_save(&self, cx: &AppContext) -> bool;
 160    fn save(&mut self, cx: &mut ViewContext<Self>) -> Result<Task<Result<()>>>;
 161    fn can_save_as(&self, cx: &AppContext) -> bool;
 162    fn save_as(
 163        &mut self,
 164        worktree: ModelHandle<Worktree>,
 165        path: &Path,
 166        cx: &mut ViewContext<Self>,
 167    ) -> Task<anyhow::Result<()>>;
 168    fn should_activate_item_on_event(_: &Self::Event) -> bool {
 169        false
 170    }
 171    fn should_close_item_on_event(_: &Self::Event) -> bool {
 172        false
 173    }
 174    fn should_update_tab_on_event(_: &Self::Event) -> bool {
 175        false
 176    }
 177}
 178
 179pub trait ItemHandle: Send + Sync {
 180    fn id(&self) -> usize;
 181    fn add_view(
 182        &self,
 183        window_id: usize,
 184        settings: watch::Receiver<Settings>,
 185        cx: &mut MutableAppContext,
 186    ) -> Box<dyn ItemViewHandle>;
 187    fn boxed_clone(&self) -> Box<dyn ItemHandle>;
 188    fn downgrade(&self) -> Box<dyn WeakItemHandle>;
 189    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 190}
 191
 192pub trait WeakItemHandle {
 193    fn id(&self) -> usize;
 194    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>>;
 195}
 196
 197pub trait ItemViewHandle {
 198    fn item_handle(&self, cx: &AppContext) -> Box<dyn ItemHandle>;
 199    fn title(&self, cx: &AppContext) -> String;
 200    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 201    fn boxed_clone(&self) -> Box<dyn ItemViewHandle>;
 202    fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemViewHandle>>;
 203    fn added_to_pane(&self, cx: &mut ViewContext<Pane>);
 204    fn id(&self) -> usize;
 205    fn to_any(&self) -> AnyViewHandle;
 206    fn is_dirty(&self, cx: &AppContext) -> bool;
 207    fn has_conflict(&self, cx: &AppContext) -> bool;
 208    fn can_save(&self, cx: &AppContext) -> bool;
 209    fn can_save_as(&self, cx: &AppContext) -> bool;
 210    fn save(&self, cx: &mut MutableAppContext) -> Result<Task<Result<()>>>;
 211    fn save_as(
 212        &self,
 213        worktree: ModelHandle<Worktree>,
 214        path: &Path,
 215        cx: &mut MutableAppContext,
 216    ) -> Task<anyhow::Result<()>>;
 217}
 218
 219impl<T: Item> ItemHandle for ModelHandle<T> {
 220    fn id(&self) -> usize {
 221        self.id()
 222    }
 223
 224    fn add_view(
 225        &self,
 226        window_id: usize,
 227        settings: watch::Receiver<Settings>,
 228        cx: &mut MutableAppContext,
 229    ) -> Box<dyn ItemViewHandle> {
 230        Box::new(cx.add_view(window_id, |cx| T::build_view(self.clone(), settings, cx)))
 231    }
 232
 233    fn boxed_clone(&self) -> Box<dyn ItemHandle> {
 234        Box::new(self.clone())
 235    }
 236
 237    fn downgrade(&self) -> Box<dyn WeakItemHandle> {
 238        Box::new(self.downgrade())
 239    }
 240
 241    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
 242        self.read(cx).project_path()
 243    }
 244}
 245
 246impl ItemHandle for Box<dyn ItemHandle> {
 247    fn id(&self) -> usize {
 248        ItemHandle::id(self.as_ref())
 249    }
 250
 251    fn add_view(
 252        &self,
 253        window_id: usize,
 254        settings: watch::Receiver<Settings>,
 255        cx: &mut MutableAppContext,
 256    ) -> Box<dyn ItemViewHandle> {
 257        ItemHandle::add_view(self.as_ref(), window_id, settings, cx)
 258    }
 259
 260    fn boxed_clone(&self) -> Box<dyn ItemHandle> {
 261        self.as_ref().boxed_clone()
 262    }
 263
 264    fn downgrade(&self) -> Box<dyn WeakItemHandle> {
 265        self.as_ref().downgrade()
 266    }
 267
 268    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
 269        self.as_ref().project_path(cx)
 270    }
 271}
 272
 273impl<T: Item> WeakItemHandle for WeakModelHandle<T> {
 274    fn id(&self) -> usize {
 275        WeakModelHandle::id(self)
 276    }
 277
 278    fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
 279        WeakModelHandle::<T>::upgrade(*self, cx).map(|i| Box::new(i) as Box<dyn ItemHandle>)
 280    }
 281}
 282
 283impl Hash for Box<dyn WeakItemHandle> {
 284    fn hash<H: Hasher>(&self, state: &mut H) {
 285        self.id().hash(state);
 286    }
 287}
 288
 289impl PartialEq for Box<dyn WeakItemHandle> {
 290    fn eq(&self, other: &Self) -> bool {
 291        self.id() == other.id()
 292    }
 293}
 294
 295impl Eq for Box<dyn WeakItemHandle> {}
 296
 297impl<T: ItemView> ItemViewHandle for ViewHandle<T> {
 298    fn item_handle(&self, cx: &AppContext) -> Box<dyn ItemHandle> {
 299        Box::new(self.read(cx).item_handle(cx))
 300    }
 301
 302    fn title(&self, cx: &AppContext) -> String {
 303        self.read(cx).title(cx)
 304    }
 305
 306    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
 307        self.read(cx).project_path(cx)
 308    }
 309
 310    fn boxed_clone(&self) -> Box<dyn ItemViewHandle> {
 311        Box::new(self.clone())
 312    }
 313
 314    fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemViewHandle>> {
 315        self.update(cx, |item, cx| {
 316            cx.add_option_view(|cx| item.clone_on_split(cx))
 317        })
 318        .map(|handle| Box::new(handle) as Box<dyn ItemViewHandle>)
 319    }
 320
 321    fn added_to_pane(&self, cx: &mut ViewContext<Pane>) {
 322        cx.subscribe(self, |pane, item, event, cx| {
 323            if T::should_close_item_on_event(event) {
 324                pane.close_item(item.id(), cx);
 325                return;
 326            }
 327            if T::should_activate_item_on_event(event) {
 328                if let Some(ix) = pane.item_index(&item) {
 329                    pane.activate_item(ix, cx);
 330                    pane.activate(cx);
 331                }
 332            }
 333            if T::should_update_tab_on_event(event) {
 334                cx.notify()
 335            }
 336        })
 337        .detach();
 338    }
 339
 340    fn save(&self, cx: &mut MutableAppContext) -> Result<Task<Result<()>>> {
 341        self.update(cx, |item, cx| item.save(cx))
 342    }
 343
 344    fn save_as(
 345        &self,
 346        worktree: ModelHandle<Worktree>,
 347        path: &Path,
 348        cx: &mut MutableAppContext,
 349    ) -> Task<anyhow::Result<()>> {
 350        self.update(cx, |item, cx| item.save_as(worktree, path, cx))
 351    }
 352
 353    fn is_dirty(&self, cx: &AppContext) -> bool {
 354        self.read(cx).is_dirty(cx)
 355    }
 356
 357    fn has_conflict(&self, cx: &AppContext) -> bool {
 358        self.read(cx).has_conflict(cx)
 359    }
 360
 361    fn id(&self) -> usize {
 362        self.id()
 363    }
 364
 365    fn to_any(&self) -> AnyViewHandle {
 366        self.into()
 367    }
 368
 369    fn can_save(&self, cx: &AppContext) -> bool {
 370        self.read(cx).can_save(cx)
 371    }
 372
 373    fn can_save_as(&self, cx: &AppContext) -> bool {
 374        self.read(cx).can_save_as(cx)
 375    }
 376}
 377
 378impl Clone for Box<dyn ItemViewHandle> {
 379    fn clone(&self) -> Box<dyn ItemViewHandle> {
 380        self.boxed_clone()
 381    }
 382}
 383
 384impl Clone for Box<dyn ItemHandle> {
 385    fn clone(&self) -> Box<dyn ItemHandle> {
 386        self.boxed_clone()
 387    }
 388}
 389
 390#[derive(Clone)]
 391pub struct WorkspaceParams {
 392    pub project: ModelHandle<Project>,
 393    pub client: Arc<Client>,
 394    pub fs: Arc<dyn Fs>,
 395    pub languages: Arc<LanguageRegistry>,
 396    pub settings: watch::Receiver<Settings>,
 397    pub user_store: ModelHandle<UserStore>,
 398    pub channel_list: ModelHandle<ChannelList>,
 399    pub path_openers: Arc<[Box<dyn EntryOpener>]>,
 400}
 401
 402impl WorkspaceParams {
 403    #[cfg(any(test, feature = "test-support"))]
 404    pub fn test(cx: &mut MutableAppContext) -> Self {
 405        let fs = Arc::new(project::FakeFs::new());
 406        let languages = Arc::new(LanguageRegistry::new());
 407        let http_client = client::test::FakeHttpClient::new(|_| async move {
 408            Ok(client::http::ServerResponse::new(404))
 409        });
 410        let client = Client::new(http_client.clone());
 411        let theme =
 412            gpui::fonts::with_font_cache(cx.font_cache().clone(), || theme::Theme::default());
 413        let settings = Settings::new("Courier", cx.font_cache(), Arc::new(theme)).unwrap();
 414        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 415        let project = Project::local(
 416            client.clone(),
 417            user_store.clone(),
 418            languages.clone(),
 419            fs.clone(),
 420            cx,
 421        );
 422        Self {
 423            project,
 424            channel_list: cx
 425                .add_model(|cx| ChannelList::new(user_store.clone(), client.clone(), cx)),
 426            client,
 427            fs,
 428            languages,
 429            settings: watch::channel_with(settings).1,
 430            user_store,
 431            path_openers: Arc::from([]),
 432        }
 433    }
 434
 435    #[cfg(any(test, feature = "test-support"))]
 436    pub fn local(app_state: &Arc<AppState>, cx: &mut MutableAppContext) -> Self {
 437        Self {
 438            project: Project::local(
 439                app_state.client.clone(),
 440                app_state.user_store.clone(),
 441                app_state.languages.clone(),
 442                app_state.fs.clone(),
 443                cx,
 444            ),
 445            client: app_state.client.clone(),
 446            fs: app_state.fs.clone(),
 447            languages: app_state.languages.clone(),
 448            settings: app_state.settings.clone(),
 449            user_store: app_state.user_store.clone(),
 450            channel_list: app_state.channel_list.clone(),
 451            path_openers: app_state.path_openers.clone(),
 452        }
 453    }
 454}
 455
 456pub struct Workspace {
 457    pub settings: watch::Receiver<Settings>,
 458    client: Arc<Client>,
 459    user_store: ModelHandle<client::UserStore>,
 460    fs: Arc<dyn Fs>,
 461    modal: Option<AnyViewHandle>,
 462    center: PaneGroup,
 463    left_sidebar: Sidebar,
 464    right_sidebar: Sidebar,
 465    panes: Vec<ViewHandle<Pane>>,
 466    active_pane: ViewHandle<Pane>,
 467    status_bar: ViewHandle<StatusBar>,
 468    project: ModelHandle<Project>,
 469    path_openers: Arc<[Box<dyn EntryOpener>]>,
 470    items: HashSet<Box<dyn WeakItemHandle>>,
 471    _observe_current_user: Task<()>,
 472}
 473
 474impl Workspace {
 475    pub fn new(params: &WorkspaceParams, cx: &mut ViewContext<Self>) -> Self {
 476        cx.observe(&params.project, |_, _, cx| cx.notify()).detach();
 477
 478        let pane = cx.add_view(|_| Pane::new(params.settings.clone()));
 479        let pane_id = pane.id();
 480        cx.observe(&pane, move |me, _, cx| {
 481            let active_entry = me.active_project_path(cx);
 482            me.project
 483                .update(cx, |project, cx| project.set_active_path(active_entry, cx));
 484        })
 485        .detach();
 486        cx.subscribe(&pane, move |me, _, event, cx| {
 487            me.handle_pane_event(pane_id, event, cx)
 488        })
 489        .detach();
 490        cx.focus(&pane);
 491
 492        let status_bar = cx.add_view(|cx| StatusBar::new(&pane, params.settings.clone(), cx));
 493        let mut current_user = params.user_store.read(cx).watch_current_user().clone();
 494        let mut connection_status = params.client.status().clone();
 495        let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
 496            current_user.recv().await;
 497            connection_status.recv().await;
 498            let mut stream =
 499                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 500
 501            while stream.recv().await.is_some() {
 502                cx.update(|cx| {
 503                    if let Some(this) = this.upgrade(&cx) {
 504                        this.update(cx, |_, cx| cx.notify());
 505                    }
 506                })
 507            }
 508        });
 509
 510        Workspace {
 511            modal: None,
 512            center: PaneGroup::new(pane.id()),
 513            panes: vec![pane.clone()],
 514            active_pane: pane.clone(),
 515            status_bar,
 516            settings: params.settings.clone(),
 517            client: params.client.clone(),
 518            user_store: params.user_store.clone(),
 519            fs: params.fs.clone(),
 520            left_sidebar: Sidebar::new(Side::Left),
 521            right_sidebar: Sidebar::new(Side::Right),
 522            project: params.project.clone(),
 523            path_openers: params.path_openers.clone(),
 524            items: Default::default(),
 525            _observe_current_user,
 526        }
 527    }
 528
 529    pub fn left_sidebar_mut(&mut self) -> &mut Sidebar {
 530        &mut self.left_sidebar
 531    }
 532
 533    pub fn right_sidebar_mut(&mut self) -> &mut Sidebar {
 534        &mut self.right_sidebar
 535    }
 536
 537    pub fn status_bar(&self) -> &ViewHandle<StatusBar> {
 538        &self.status_bar
 539    }
 540
 541    pub fn project(&self) -> &ModelHandle<Project> {
 542        &self.project
 543    }
 544
 545    pub fn worktrees<'a>(&self, cx: &'a AppContext) -> &'a [ModelHandle<Worktree>] {
 546        &self.project.read(cx).worktrees()
 547    }
 548
 549    pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
 550        paths.iter().all(|path| self.contains_path(&path, cx))
 551    }
 552
 553    pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
 554        for worktree in self.worktrees(cx) {
 555            let worktree = worktree.read(cx).as_local();
 556            if worktree.map_or(false, |w| w.contains_abs_path(path)) {
 557                return true;
 558            }
 559        }
 560        false
 561    }
 562
 563    pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
 564        let futures = self
 565            .worktrees(cx)
 566            .iter()
 567            .filter_map(|worktree| worktree.read(cx).as_local())
 568            .map(|worktree| worktree.scan_complete())
 569            .collect::<Vec<_>>();
 570        async move {
 571            for future in futures {
 572                future.await;
 573            }
 574        }
 575    }
 576
 577    pub fn open_paths(
 578        &mut self,
 579        abs_paths: &[PathBuf],
 580        cx: &mut ViewContext<Self>,
 581    ) -> Task<Vec<Option<Result<Box<dyn ItemViewHandle>, Arc<anyhow::Error>>>>> {
 582        let entries = abs_paths
 583            .iter()
 584            .cloned()
 585            .map(|path| self.project_path_for_path(&path, cx))
 586            .collect::<Vec<_>>();
 587
 588        let fs = self.fs.clone();
 589        let tasks = abs_paths
 590            .iter()
 591            .cloned()
 592            .zip(entries.into_iter())
 593            .map(|(abs_path, project_path)| {
 594                cx.spawn(|this, mut cx| {
 595                    let fs = fs.clone();
 596                    async move {
 597                        let project_path = project_path.await.ok()?;
 598                        if fs.is_file(&abs_path).await {
 599                            Some(
 600                                this.update(&mut cx, |this, cx| this.open_path(project_path, cx))
 601                                    .await,
 602                            )
 603                        } else {
 604                            None
 605                        }
 606                    }
 607                })
 608            })
 609            .collect::<Vec<_>>();
 610
 611        cx.foreground().spawn(async move {
 612            let mut items = Vec::new();
 613            for task in tasks {
 614                items.push(task.await);
 615            }
 616            items
 617        })
 618    }
 619
 620    fn worktree_for_abs_path(
 621        &self,
 622        abs_path: &Path,
 623        cx: &mut ViewContext<Self>,
 624    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
 625        let abs_path: Arc<Path> = Arc::from(abs_path);
 626        cx.spawn(|this, mut cx| async move {
 627            let mut entry_id = None;
 628            this.read_with(&cx, |this, cx| {
 629                for tree in this.worktrees(cx) {
 630                    if let Some(relative_path) = tree
 631                        .read(cx)
 632                        .as_local()
 633                        .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
 634                    {
 635                        entry_id = Some((tree.clone(), relative_path.into()));
 636                        break;
 637                    }
 638                }
 639            });
 640
 641            if let Some(entry_id) = entry_id {
 642                Ok(entry_id)
 643            } else {
 644                let worktree = this
 645                    .update(&mut cx, |this, cx| this.add_worktree(&abs_path, cx))
 646                    .await?;
 647                Ok((worktree, PathBuf::new()))
 648            }
 649        })
 650    }
 651
 652    fn project_path_for_path(
 653        &self,
 654        abs_path: &Path,
 655        cx: &mut ViewContext<Self>,
 656    ) -> Task<Result<ProjectPath>> {
 657        let entry = self.worktree_for_abs_path(abs_path, cx);
 658        cx.spawn(|_, cx| async move {
 659            let (worktree, path) = entry.await?;
 660            Ok(ProjectPath {
 661                worktree_id: worktree.read_with(&cx, |t, _| t.id()),
 662                path: path.into(),
 663            })
 664        })
 665    }
 666
 667    pub fn add_worktree(
 668        &self,
 669        path: &Path,
 670        cx: &mut ViewContext<Self>,
 671    ) -> Task<Result<ModelHandle<Worktree>>> {
 672        self.project
 673            .update(cx, |project, cx| project.add_local_worktree(path, cx))
 674    }
 675
 676    pub fn toggle_modal<V, F>(&mut self, cx: &mut ViewContext<Self>, add_view: F)
 677    where
 678        V: 'static + View,
 679        F: FnOnce(&mut ViewContext<Self>, &mut Self) -> ViewHandle<V>,
 680    {
 681        if self.modal.as_ref().map_or(false, |modal| modal.is::<V>()) {
 682            self.modal.take();
 683            cx.focus_self();
 684        } else {
 685            let modal = add_view(cx, self);
 686            cx.focus(&modal);
 687            self.modal = Some(modal.into());
 688        }
 689        cx.notify();
 690    }
 691
 692    pub fn modal(&self) -> Option<&AnyViewHandle> {
 693        self.modal.as_ref()
 694    }
 695
 696    pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
 697        if self.modal.take().is_some() {
 698            cx.focus(&self.active_pane);
 699            cx.notify();
 700        }
 701    }
 702
 703    #[must_use]
 704    pub fn open_path(
 705        &mut self,
 706        path: ProjectPath,
 707        cx: &mut ViewContext<Self>,
 708    ) -> Task<Result<Box<dyn ItemViewHandle>, Arc<anyhow::Error>>> {
 709        if let Some(existing_item) = self.item_for_path(&path, cx) {
 710            return Task::ready(Ok(self.open_item(existing_item, cx)));
 711        }
 712
 713        let worktree = match self.project.read(cx).worktree_for_id(path.worktree_id, cx) {
 714            Some(worktree) => worktree,
 715            None => {
 716                return Task::ready(Err(Arc::new(anyhow!(
 717                    "worktree {} does not exist",
 718                    path.worktree_id
 719                ))));
 720            }
 721        };
 722
 723        let project_path = path.clone();
 724        let path_openers = self.path_openers.clone();
 725        let open_task = worktree.update(cx, |worktree, cx| {
 726            for opener in path_openers.iter() {
 727                if let Some(task) = opener.open(worktree, project_path.clone(), cx) {
 728                    return task;
 729                }
 730            }
 731            Task::ready(Err(anyhow!("no opener found for path {:?}", project_path)))
 732        });
 733
 734        let pane = self.active_pane().clone().downgrade();
 735        cx.spawn(|this, mut cx| async move {
 736            let item = open_task.await?;
 737            this.update(&mut cx, |this, cx| {
 738                let pane = pane
 739                    .upgrade(&cx)
 740                    .ok_or_else(|| anyhow!("could not upgrade pane reference"))?;
 741                Ok(this.open_item_in_pane(item, &pane, cx))
 742            })
 743        })
 744    }
 745
 746    fn item_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
 747        self.items
 748            .iter()
 749            .filter_map(|i| i.upgrade(cx))
 750            .find(|i| i.project_path(cx).as_ref() == Some(path))
 751    }
 752
 753    pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemViewHandle>> {
 754        self.active_pane().read(cx).active_item()
 755    }
 756
 757    fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
 758        self.active_item(cx).and_then(|item| item.project_path(cx))
 759    }
 760
 761    pub fn save_active_item(&mut self, _: &Save, cx: &mut ViewContext<Self>) {
 762        if let Some(item) = self.active_item(cx) {
 763            let handle = cx.handle();
 764            if item.can_save(cx) {
 765                if item.has_conflict(cx.as_ref()) {
 766                    const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
 767
 768                    cx.prompt(
 769                        PromptLevel::Warning,
 770                        CONFLICT_MESSAGE,
 771                        &["Overwrite", "Cancel"],
 772                        move |answer, cx| {
 773                            if answer == 0 {
 774                                cx.spawn(|mut cx| async move {
 775                                    if let Err(error) = cx.update(|cx| item.save(cx)).unwrap().await
 776                                    {
 777                                        error!("failed to save item: {:?}, ", error);
 778                                    }
 779                                })
 780                                .detach();
 781                            }
 782                        },
 783                    );
 784                } else {
 785                    cx.spawn(|_, mut cx| async move {
 786                        if let Err(error) = cx.update(|cx| item.save(cx)).unwrap().await {
 787                            error!("failed to save item: {:?}, ", error);
 788                        }
 789                    })
 790                    .detach();
 791                }
 792            } else if item.can_save_as(cx) {
 793                let worktree = self.worktrees(cx).first();
 794                let start_abs_path = worktree
 795                    .and_then(|w| w.read(cx).as_local())
 796                    .map_or(Path::new(""), |w| w.abs_path())
 797                    .to_path_buf();
 798                cx.prompt_for_new_path(&start_abs_path, move |abs_path, cx| {
 799                    if let Some(abs_path) = abs_path {
 800                        cx.spawn(|mut cx| async move {
 801                            let result = match handle
 802                                .update(&mut cx, |this, cx| {
 803                                    this.worktree_for_abs_path(&abs_path, cx)
 804                                })
 805                                .await
 806                            {
 807                                Ok((worktree, path)) => {
 808                                    handle
 809                                        .update(&mut cx, |_, cx| {
 810                                            item.save_as(worktree, &path, cx.as_mut())
 811                                        })
 812                                        .await
 813                                }
 814                                Err(error) => Err(error),
 815                            };
 816
 817                            if let Err(error) = result {
 818                                error!("failed to save item: {:?}, ", error);
 819                            }
 820                        })
 821                        .detach()
 822                    }
 823                });
 824            }
 825        }
 826    }
 827
 828    pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
 829        let sidebar = match action.0.side {
 830            Side::Left => &mut self.left_sidebar,
 831            Side::Right => &mut self.right_sidebar,
 832        };
 833        sidebar.toggle_item(action.0.item_index);
 834        if let Some(active_item) = sidebar.active_item() {
 835            cx.focus(active_item);
 836        } else {
 837            cx.focus_self();
 838        }
 839        cx.notify();
 840    }
 841
 842    pub fn toggle_sidebar_item_focus(
 843        &mut self,
 844        action: &ToggleSidebarItemFocus,
 845        cx: &mut ViewContext<Self>,
 846    ) {
 847        let sidebar = match action.0.side {
 848            Side::Left => &mut self.left_sidebar,
 849            Side::Right => &mut self.right_sidebar,
 850        };
 851        sidebar.activate_item(action.0.item_index);
 852        if let Some(active_item) = sidebar.active_item() {
 853            if active_item.is_focused(cx) {
 854                cx.focus_self();
 855            } else {
 856                cx.focus(active_item);
 857            }
 858        }
 859        cx.notify();
 860    }
 861
 862    pub fn debug_elements(&mut self, _: &DebugElements, cx: &mut ViewContext<Self>) {
 863        match to_string_pretty(&cx.debug_elements()) {
 864            Ok(json) => {
 865                let kib = json.len() as f32 / 1024.;
 866                cx.as_mut().write_to_clipboard(ClipboardItem::new(json));
 867                log::info!(
 868                    "copied {:.1} KiB of element debug JSON to the clipboard",
 869                    kib
 870                );
 871            }
 872            Err(error) => {
 873                log::error!("error debugging elements: {}", error);
 874            }
 875        };
 876    }
 877
 878    fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
 879        let pane = cx.add_view(|_| Pane::new(self.settings.clone()));
 880        let pane_id = pane.id();
 881        cx.observe(&pane, move |me, _, cx| {
 882            let active_entry = me.active_project_path(cx);
 883            me.project
 884                .update(cx, |project, cx| project.set_active_path(active_entry, cx));
 885        })
 886        .detach();
 887        cx.subscribe(&pane, move |me, _, event, cx| {
 888            me.handle_pane_event(pane_id, event, cx)
 889        })
 890        .detach();
 891        self.panes.push(pane.clone());
 892        self.activate_pane(pane.clone(), cx);
 893        pane
 894    }
 895
 896    pub fn open_item<T>(
 897        &mut self,
 898        item_handle: T,
 899        cx: &mut ViewContext<Self>,
 900    ) -> Box<dyn ItemViewHandle>
 901    where
 902        T: 'static + ItemHandle,
 903    {
 904        self.open_item_in_pane(item_handle, &self.active_pane().clone(), cx)
 905    }
 906
 907    pub fn open_item_in_pane<T>(
 908        &mut self,
 909        item_handle: T,
 910        pane: &ViewHandle<Pane>,
 911        cx: &mut ViewContext<Self>,
 912    ) -> Box<dyn ItemViewHandle>
 913    where
 914        T: 'static + ItemHandle,
 915    {
 916        self.items.insert(item_handle.downgrade());
 917        pane.update(cx, |pane, cx| pane.open_item(item_handle, cx))
 918    }
 919
 920    fn activate_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
 921        self.active_pane = pane;
 922        self.status_bar.update(cx, |status_bar, cx| {
 923            status_bar.set_active_pane(&self.active_pane, cx);
 924        });
 925        cx.focus(&self.active_pane);
 926        cx.notify();
 927    }
 928
 929    fn handle_pane_event(
 930        &mut self,
 931        pane_id: usize,
 932        event: &pane::Event,
 933        cx: &mut ViewContext<Self>,
 934    ) {
 935        if let Some(pane) = self.pane(pane_id) {
 936            match event {
 937                pane::Event::Split(direction) => {
 938                    self.split_pane(pane, *direction, cx);
 939                }
 940                pane::Event::Remove => {
 941                    self.remove_pane(pane, cx);
 942                }
 943                pane::Event::Activate => {
 944                    self.activate_pane(pane, cx);
 945                }
 946            }
 947        } else {
 948            error!("pane {} not found", pane_id);
 949        }
 950    }
 951
 952    pub fn split_pane(
 953        &mut self,
 954        pane: ViewHandle<Pane>,
 955        direction: SplitDirection,
 956        cx: &mut ViewContext<Self>,
 957    ) -> ViewHandle<Pane> {
 958        let new_pane = self.add_pane(cx);
 959        self.activate_pane(new_pane.clone(), cx);
 960        if let Some(item) = pane.read(cx).active_item() {
 961            if let Some(clone) = item.clone_on_split(cx.as_mut()) {
 962                new_pane.update(cx, |new_pane, cx| new_pane.add_item_view(clone, cx));
 963            }
 964        }
 965        self.center
 966            .split(pane.id(), new_pane.id(), direction)
 967            .unwrap();
 968        cx.notify();
 969        new_pane
 970    }
 971
 972    fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
 973        if self.center.remove(pane.id()).unwrap() {
 974            self.panes.retain(|p| p != &pane);
 975            self.activate_pane(self.panes.last().unwrap().clone(), cx);
 976        }
 977    }
 978
 979    pub fn panes(&self) -> &[ViewHandle<Pane>] {
 980        &self.panes
 981    }
 982
 983    fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
 984        self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
 985    }
 986
 987    pub fn active_pane(&self) -> &ViewHandle<Pane> {
 988        &self.active_pane
 989    }
 990
 991    fn toggle_share(&mut self, _: &ToggleShare, cx: &mut ViewContext<Self>) {
 992        self.project.update(cx, |project, cx| {
 993            if project.is_local() {
 994                if project.is_shared() {
 995                    project.unshare(cx).detach();
 996                } else {
 997                    project.share(cx).detach();
 998                }
 999            }
1000        });
1001    }
1002
1003    fn render_connection_status(&self) -> Option<ElementBox> {
1004        let theme = &self.settings.borrow().theme;
1005        match &*self.client.status().borrow() {
1006            client::Status::ConnectionError
1007            | client::Status::ConnectionLost
1008            | client::Status::Reauthenticating
1009            | client::Status::Reconnecting { .. }
1010            | client::Status::ReconnectionError { .. } => Some(
1011                Container::new(
1012                    Align::new(
1013                        ConstrainedBox::new(
1014                            Svg::new("icons/offline-14.svg")
1015                                .with_color(theme.workspace.titlebar.icon_color)
1016                                .boxed(),
1017                        )
1018                        .with_width(theme.workspace.titlebar.offline_icon.width)
1019                        .boxed(),
1020                    )
1021                    .boxed(),
1022                )
1023                .with_style(theme.workspace.titlebar.offline_icon.container)
1024                .boxed(),
1025            ),
1026            client::Status::UpgradeRequired => Some(
1027                Label::new(
1028                    "Please update Zed to collaborate".to_string(),
1029                    theme.workspace.titlebar.outdated_warning.text.clone(),
1030                )
1031                .contained()
1032                .with_style(theme.workspace.titlebar.outdated_warning.container)
1033                .aligned()
1034                .boxed(),
1035            ),
1036            _ => None,
1037        }
1038    }
1039
1040    fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1041        ConstrainedBox::new(
1042            Container::new(
1043                Stack::new()
1044                    .with_child(
1045                        Align::new(
1046                            Label::new("zed".into(), theme.workspace.titlebar.title.clone())
1047                                .boxed(),
1048                        )
1049                        .boxed(),
1050                    )
1051                    .with_child(
1052                        Align::new(
1053                            Flex::row()
1054                                .with_children(self.render_share_icon(cx))
1055                                .with_children(self.render_collaborators(theme, cx))
1056                                .with_child(self.render_avatar(
1057                                    self.user_store.read(cx).current_user().as_ref(),
1058                                    self.project.read(cx).replica_id(),
1059                                    theme,
1060                                    cx,
1061                                ))
1062                                .with_children(self.render_connection_status())
1063                                .boxed(),
1064                        )
1065                        .right()
1066                        .boxed(),
1067                    )
1068                    .boxed(),
1069            )
1070            .with_style(theme.workspace.titlebar.container)
1071            .boxed(),
1072        )
1073        .with_height(theme.workspace.titlebar.height)
1074        .named("titlebar")
1075    }
1076
1077    fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1078        let mut collaborators = self
1079            .project
1080            .read(cx)
1081            .collaborators()
1082            .values()
1083            .cloned()
1084            .collect::<Vec<_>>();
1085        collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1086        collaborators
1087            .into_iter()
1088            .map(|collaborator| {
1089                self.render_avatar(Some(&collaborator.user), collaborator.replica_id, theme, cx)
1090            })
1091            .collect()
1092    }
1093
1094    fn render_avatar(
1095        &self,
1096        user: Option<&Arc<User>>,
1097        replica_id: ReplicaId,
1098        theme: &Theme,
1099        cx: &mut RenderContext<Self>,
1100    ) -> ElementBox {
1101        if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1102            ConstrainedBox::new(
1103                Stack::new()
1104                    .with_child(
1105                        ConstrainedBox::new(
1106                            Image::new(avatar)
1107                                .with_style(theme.workspace.titlebar.avatar)
1108                                .boxed(),
1109                        )
1110                        .with_width(theme.workspace.titlebar.avatar_width)
1111                        .aligned()
1112                        .boxed(),
1113                    )
1114                    .with_child(
1115                        AvatarRibbon::new(theme.editor.replica_selection_style(replica_id).cursor)
1116                            .constrained()
1117                            .with_width(theme.workspace.titlebar.avatar_ribbon.width)
1118                            .with_height(theme.workspace.titlebar.avatar_ribbon.height)
1119                            .aligned()
1120                            .bottom()
1121                            .boxed(),
1122                    )
1123                    .boxed(),
1124            )
1125            .with_width(theme.workspace.right_sidebar.width)
1126            .boxed()
1127        } else {
1128            MouseEventHandler::new::<Authenticate, _, _, _>(0, cx, |state, _| {
1129                let style = if state.hovered {
1130                    &theme.workspace.titlebar.hovered_sign_in_prompt
1131                } else {
1132                    &theme.workspace.titlebar.sign_in_prompt
1133                };
1134                Label::new("Sign in".to_string(), style.text.clone())
1135                    .contained()
1136                    .with_style(style.container)
1137                    .boxed()
1138            })
1139            .on_click(|cx| cx.dispatch_action(Authenticate))
1140            .with_cursor_style(CursorStyle::PointingHand)
1141            .aligned()
1142            .boxed()
1143        }
1144    }
1145
1146    fn render_share_icon(&self, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1147        if self.project().read(cx).is_local() && self.client.user_id().is_some() {
1148            enum Share {}
1149
1150            let color = if self.project().read(cx).is_shared() {
1151                Color::green()
1152            } else {
1153                Color::red()
1154            };
1155            Some(
1156                MouseEventHandler::new::<Share, _, _, _>(0, cx, |_, _| {
1157                    Align::new(
1158                        ConstrainedBox::new(
1159                            Svg::new("icons/broadcast-24.svg").with_color(color).boxed(),
1160                        )
1161                        .with_width(24.)
1162                        .boxed(),
1163                    )
1164                    .boxed()
1165                })
1166                .with_cursor_style(CursorStyle::PointingHand)
1167                .on_click(|cx| cx.dispatch_action(ToggleShare))
1168                .boxed(),
1169            )
1170        } else {
1171            None
1172        }
1173    }
1174}
1175
1176impl Entity for Workspace {
1177    type Event = ();
1178}
1179
1180impl View for Workspace {
1181    fn ui_name() -> &'static str {
1182        "Workspace"
1183    }
1184
1185    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1186        let settings = self.settings.borrow();
1187        let theme = &settings.theme;
1188        Flex::column()
1189            .with_child(self.render_titlebar(&theme, cx))
1190            .with_child(
1191                Stack::new()
1192                    .with_child({
1193                        let mut content = Flex::row();
1194                        content.add_child(self.left_sidebar.render(&settings, cx));
1195                        if let Some(element) = self.left_sidebar.render_active_item(&settings, cx) {
1196                            content.add_child(Flexible::new(0.8, false, element).boxed());
1197                        }
1198                        content.add_child(
1199                            Flex::column()
1200                                .with_child(
1201                                    Flexible::new(1., true, self.center.render(&settings.theme))
1202                                        .boxed(),
1203                                )
1204                                .with_child(ChildView::new(self.status_bar.id()).boxed())
1205                                .flexible(1., true)
1206                                .boxed(),
1207                        );
1208                        if let Some(element) = self.right_sidebar.render_active_item(&settings, cx)
1209                        {
1210                            content.add_child(Flexible::new(0.8, false, element).boxed());
1211                        }
1212                        content.add_child(self.right_sidebar.render(&settings, cx));
1213                        content.boxed()
1214                    })
1215                    .with_children(self.modal.as_ref().map(|m| ChildView::new(m.id()).boxed()))
1216                    .flexible(1.0, true)
1217                    .boxed(),
1218            )
1219            .contained()
1220            .with_background_color(settings.theme.workspace.background)
1221            .named("workspace")
1222    }
1223
1224    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
1225        cx.focus(&self.active_pane);
1226    }
1227}
1228
1229pub trait WorkspaceHandle {
1230    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
1231}
1232
1233impl WorkspaceHandle for ViewHandle<Workspace> {
1234    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
1235        self.read(cx)
1236            .worktrees(cx)
1237            .iter()
1238            .flat_map(|worktree| {
1239                let worktree_id = worktree.read(cx).id();
1240                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
1241                    worktree_id,
1242                    path: f.path.clone(),
1243                })
1244            })
1245            .collect::<Vec<_>>()
1246    }
1247}
1248
1249pub struct AvatarRibbon {
1250    color: Color,
1251}
1252
1253impl AvatarRibbon {
1254    pub fn new(color: Color) -> AvatarRibbon {
1255        AvatarRibbon { color }
1256    }
1257}
1258
1259impl Element for AvatarRibbon {
1260    type LayoutState = ();
1261
1262    type PaintState = ();
1263
1264    fn layout(
1265        &mut self,
1266        constraint: gpui::SizeConstraint,
1267        _: &mut gpui::LayoutContext,
1268    ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
1269        (constraint.max, ())
1270    }
1271
1272    fn paint(
1273        &mut self,
1274        bounds: gpui::geometry::rect::RectF,
1275        _: gpui::geometry::rect::RectF,
1276        _: &mut Self::LayoutState,
1277        cx: &mut gpui::PaintContext,
1278    ) -> Self::PaintState {
1279        let mut path = PathBuilder::new();
1280        path.reset(bounds.lower_left());
1281        path.curve_to(
1282            bounds.origin() + vec2f(bounds.height(), 0.),
1283            bounds.origin(),
1284        );
1285        path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
1286        path.curve_to(bounds.lower_right(), bounds.upper_right());
1287        path.line_to(bounds.lower_left());
1288        cx.scene.push_path(path.build(self.color, None));
1289    }
1290
1291    fn dispatch_event(
1292        &mut self,
1293        _: &gpui::Event,
1294        _: gpui::geometry::rect::RectF,
1295        _: &mut Self::LayoutState,
1296        _: &mut Self::PaintState,
1297        _: &mut gpui::EventContext,
1298    ) -> bool {
1299        false
1300    }
1301
1302    fn debug(
1303        &self,
1304        bounds: gpui::geometry::rect::RectF,
1305        _: &Self::LayoutState,
1306        _: &Self::PaintState,
1307        _: &gpui::DebugContext,
1308    ) -> gpui::json::Value {
1309        json::json!({
1310            "type": "AvatarRibbon",
1311            "bounds": bounds.to_json(),
1312            "color": self.color.to_json(),
1313        })
1314    }
1315}
1316
1317impl std::fmt::Debug for OpenParams {
1318    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1319        f.debug_struct("OpenParams")
1320            .field("paths", &self.paths)
1321            .finish()
1322    }
1323}
1324
1325fn open(action: &Open, cx: &mut MutableAppContext) {
1326    let app_state = action.0.clone();
1327    cx.prompt_for_paths(
1328        PathPromptOptions {
1329            files: true,
1330            directories: true,
1331            multiple: true,
1332        },
1333        move |paths, cx| {
1334            if let Some(paths) = paths {
1335                cx.dispatch_global_action(OpenPaths(OpenParams { paths, app_state }));
1336            }
1337        },
1338    );
1339}
1340
1341pub fn open_paths(
1342    abs_paths: &[PathBuf],
1343    app_state: &Arc<AppState>,
1344    cx: &mut MutableAppContext,
1345) -> Task<ViewHandle<Workspace>> {
1346    log::info!("open paths {:?}", abs_paths);
1347
1348    // Open paths in existing workspace if possible
1349    let mut existing = None;
1350    for window_id in cx.window_ids().collect::<Vec<_>>() {
1351        if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
1352            if workspace.update(cx, |view, cx| {
1353                if view.contains_paths(abs_paths, cx.as_ref()) {
1354                    existing = Some(workspace.clone());
1355                    true
1356                } else {
1357                    false
1358                }
1359            }) {
1360                break;
1361            }
1362        }
1363    }
1364
1365    let workspace = existing.unwrap_or_else(|| {
1366        cx.add_window((app_state.build_window_options)(), |cx| {
1367            let project = Project::local(
1368                app_state.client.clone(),
1369                app_state.user_store.clone(),
1370                app_state.languages.clone(),
1371                app_state.fs.clone(),
1372                cx,
1373            );
1374            (app_state.build_workspace)(project, &app_state, cx)
1375        })
1376        .1
1377    });
1378
1379    let task = workspace.update(cx, |workspace, cx| workspace.open_paths(abs_paths, cx));
1380    cx.spawn(|_| async move {
1381        task.await;
1382        workspace
1383    })
1384}
1385
1386pub fn join_project(
1387    project_id: u64,
1388    app_state: &Arc<AppState>,
1389    cx: &mut MutableAppContext,
1390) -> Task<Result<ViewHandle<Workspace>>> {
1391    for window_id in cx.window_ids().collect::<Vec<_>>() {
1392        if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
1393            if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
1394                return Task::ready(Ok(workspace));
1395            }
1396        }
1397    }
1398
1399    let app_state = app_state.clone();
1400    cx.spawn(|mut cx| async move {
1401        let project = Project::remote(
1402            project_id,
1403            app_state.client.clone(),
1404            app_state.user_store.clone(),
1405            app_state.languages.clone(),
1406            app_state.fs.clone(),
1407            &mut cx,
1408        )
1409        .await?;
1410        let (_, workspace) = cx.update(|cx| {
1411            cx.add_window((app_state.build_window_options)(), |cx| {
1412                (app_state.build_workspace)(project, &app_state, cx)
1413            })
1414        });
1415        Ok(workspace)
1416    })
1417}
1418
1419fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
1420    let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
1421        let project = Project::local(
1422            app_state.client.clone(),
1423            app_state.user_store.clone(),
1424            app_state.languages.clone(),
1425            app_state.fs.clone(),
1426            cx,
1427        );
1428        (app_state.build_workspace)(project, &app_state, cx)
1429    });
1430    cx.dispatch_action(window_id, vec![workspace.id()], &OpenNew(app_state.clone()));
1431}