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, WeakViewHandle,
  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 PathOpener>]>,
 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 PathOpener {
 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        workspace: &Workspace,
 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        workspace: &Workspace,
 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        workspace: &Workspace,
 228        cx: &mut MutableAppContext,
 229    ) -> Box<dyn ItemViewHandle> {
 230        Box::new(cx.add_view(window_id, |cx| T::build_view(self.clone(), workspace, 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        workspace: &Workspace,
 255        cx: &mut MutableAppContext,
 256    ) -> Box<dyn ItemViewHandle> {
 257        ItemHandle::add_view(self.as_ref(), window_id, workspace, 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 PathOpener>]>,
 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    weak_self: WeakViewHandle<Self>,
 459    client: Arc<Client>,
 460    user_store: ModelHandle<client::UserStore>,
 461    fs: Arc<dyn Fs>,
 462    modal: Option<AnyViewHandle>,
 463    center: PaneGroup,
 464    left_sidebar: Sidebar,
 465    right_sidebar: Sidebar,
 466    panes: Vec<ViewHandle<Pane>>,
 467    active_pane: ViewHandle<Pane>,
 468    status_bar: ViewHandle<StatusBar>,
 469    project: ModelHandle<Project>,
 470    path_openers: Arc<[Box<dyn PathOpener>]>,
 471    items: HashSet<Box<dyn WeakItemHandle>>,
 472    _observe_current_user: Task<()>,
 473}
 474
 475impl Workspace {
 476    pub fn new(params: &WorkspaceParams, cx: &mut ViewContext<Self>) -> Self {
 477        cx.observe(&params.project, |_, _, cx| cx.notify()).detach();
 478
 479        let pane = cx.add_view(|_| Pane::new(params.settings.clone()));
 480        let pane_id = pane.id();
 481        cx.observe(&pane, move |me, _, cx| {
 482            let active_entry = me.active_project_path(cx);
 483            me.project
 484                .update(cx, |project, cx| project.set_active_path(active_entry, cx));
 485        })
 486        .detach();
 487        cx.subscribe(&pane, move |me, _, event, cx| {
 488            me.handle_pane_event(pane_id, event, cx)
 489        })
 490        .detach();
 491        cx.focus(&pane);
 492
 493        let status_bar = cx.add_view(|cx| StatusBar::new(&pane, params.settings.clone(), cx));
 494        let mut current_user = params.user_store.read(cx).watch_current_user().clone();
 495        let mut connection_status = params.client.status().clone();
 496        let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
 497            current_user.recv().await;
 498            connection_status.recv().await;
 499            let mut stream =
 500                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 501
 502            while stream.recv().await.is_some() {
 503                cx.update(|cx| {
 504                    if let Some(this) = this.upgrade(&cx) {
 505                        this.update(cx, |_, cx| cx.notify());
 506                    }
 507                })
 508            }
 509        });
 510
 511        Workspace {
 512            modal: None,
 513            weak_self: cx.weak_handle(),
 514            center: PaneGroup::new(pane.id()),
 515            panes: vec![pane.clone()],
 516            active_pane: pane.clone(),
 517            status_bar,
 518            settings: params.settings.clone(),
 519            client: params.client.clone(),
 520            user_store: params.user_store.clone(),
 521            fs: params.fs.clone(),
 522            left_sidebar: Sidebar::new(Side::Left),
 523            right_sidebar: Sidebar::new(Side::Right),
 524            project: params.project.clone(),
 525            path_openers: params.path_openers.clone(),
 526            items: Default::default(),
 527            _observe_current_user,
 528        }
 529    }
 530
 531    pub fn weak_handle(&self) -> WeakViewHandle<Self> {
 532        self.weak_self.clone()
 533    }
 534
 535    pub fn settings(&self) -> watch::Receiver<Settings> {
 536        self.settings.clone()
 537    }
 538
 539    pub fn left_sidebar_mut(&mut self) -> &mut Sidebar {
 540        &mut self.left_sidebar
 541    }
 542
 543    pub fn right_sidebar_mut(&mut self) -> &mut Sidebar {
 544        &mut self.right_sidebar
 545    }
 546
 547    pub fn status_bar(&self) -> &ViewHandle<StatusBar> {
 548        &self.status_bar
 549    }
 550
 551    pub fn project(&self) -> &ModelHandle<Project> {
 552        &self.project
 553    }
 554
 555    pub fn worktrees<'a>(&self, cx: &'a AppContext) -> &'a [ModelHandle<Worktree>] {
 556        &self.project.read(cx).worktrees()
 557    }
 558
 559    pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
 560        paths.iter().all(|path| self.contains_path(&path, cx))
 561    }
 562
 563    pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
 564        for worktree in self.worktrees(cx) {
 565            let worktree = worktree.read(cx).as_local();
 566            if worktree.map_or(false, |w| w.contains_abs_path(path)) {
 567                return true;
 568            }
 569        }
 570        false
 571    }
 572
 573    pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
 574        let futures = self
 575            .worktrees(cx)
 576            .iter()
 577            .filter_map(|worktree| worktree.read(cx).as_local())
 578            .map(|worktree| worktree.scan_complete())
 579            .collect::<Vec<_>>();
 580        async move {
 581            for future in futures {
 582                future.await;
 583            }
 584        }
 585    }
 586
 587    pub fn open_paths(
 588        &mut self,
 589        abs_paths: &[PathBuf],
 590        cx: &mut ViewContext<Self>,
 591    ) -> Task<Vec<Option<Result<Box<dyn ItemViewHandle>, Arc<anyhow::Error>>>>> {
 592        let entries = abs_paths
 593            .iter()
 594            .cloned()
 595            .map(|path| self.project_path_for_path(&path, cx))
 596            .collect::<Vec<_>>();
 597
 598        let fs = self.fs.clone();
 599        let tasks = abs_paths
 600            .iter()
 601            .cloned()
 602            .zip(entries.into_iter())
 603            .map(|(abs_path, project_path)| {
 604                cx.spawn(|this, mut cx| {
 605                    let fs = fs.clone();
 606                    async move {
 607                        let project_path = project_path.await.ok()?;
 608                        if fs.is_file(&abs_path).await {
 609                            Some(
 610                                this.update(&mut cx, |this, cx| this.open_path(project_path, cx))
 611                                    .await,
 612                            )
 613                        } else {
 614                            None
 615                        }
 616                    }
 617                })
 618            })
 619            .collect::<Vec<_>>();
 620
 621        cx.foreground().spawn(async move {
 622            let mut items = Vec::new();
 623            for task in tasks {
 624                items.push(task.await);
 625            }
 626            items
 627        })
 628    }
 629
 630    fn worktree_for_abs_path(
 631        &self,
 632        abs_path: &Path,
 633        cx: &mut ViewContext<Self>,
 634    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
 635        let abs_path: Arc<Path> = Arc::from(abs_path);
 636        cx.spawn(|this, mut cx| async move {
 637            let mut entry_id = None;
 638            this.read_with(&cx, |this, cx| {
 639                for tree in this.worktrees(cx) {
 640                    if let Some(relative_path) = tree
 641                        .read(cx)
 642                        .as_local()
 643                        .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
 644                    {
 645                        entry_id = Some((tree.clone(), relative_path.into()));
 646                        break;
 647                    }
 648                }
 649            });
 650
 651            if let Some(entry_id) = entry_id {
 652                Ok(entry_id)
 653            } else {
 654                let worktree = this
 655                    .update(&mut cx, |this, cx| this.add_worktree(&abs_path, cx))
 656                    .await?;
 657                Ok((worktree, PathBuf::new()))
 658            }
 659        })
 660    }
 661
 662    fn project_path_for_path(
 663        &self,
 664        abs_path: &Path,
 665        cx: &mut ViewContext<Self>,
 666    ) -> Task<Result<ProjectPath>> {
 667        let entry = self.worktree_for_abs_path(abs_path, cx);
 668        cx.spawn(|_, cx| async move {
 669            let (worktree, path) = entry.await?;
 670            Ok(ProjectPath {
 671                worktree_id: worktree.read_with(&cx, |t, _| t.id()),
 672                path: path.into(),
 673            })
 674        })
 675    }
 676
 677    pub fn add_worktree(
 678        &self,
 679        path: &Path,
 680        cx: &mut ViewContext<Self>,
 681    ) -> Task<Result<ModelHandle<Worktree>>> {
 682        self.project
 683            .update(cx, |project, cx| project.add_local_worktree(path, cx))
 684    }
 685
 686    pub fn toggle_modal<V, F>(&mut self, cx: &mut ViewContext<Self>, add_view: F)
 687    where
 688        V: 'static + View,
 689        F: FnOnce(&mut ViewContext<Self>, &mut Self) -> ViewHandle<V>,
 690    {
 691        if self.modal.as_ref().map_or(false, |modal| modal.is::<V>()) {
 692            self.modal.take();
 693            cx.focus_self();
 694        } else {
 695            let modal = add_view(cx, self);
 696            cx.focus(&modal);
 697            self.modal = Some(modal.into());
 698        }
 699        cx.notify();
 700    }
 701
 702    pub fn modal(&self) -> Option<&AnyViewHandle> {
 703        self.modal.as_ref()
 704    }
 705
 706    pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
 707        if self.modal.take().is_some() {
 708            cx.focus(&self.active_pane);
 709            cx.notify();
 710        }
 711    }
 712
 713    #[must_use]
 714    pub fn open_path(
 715        &mut self,
 716        path: ProjectPath,
 717        cx: &mut ViewContext<Self>,
 718    ) -> Task<Result<Box<dyn ItemViewHandle>, Arc<anyhow::Error>>> {
 719        if let Some(existing_item) = self.item_for_path(&path, cx) {
 720            return Task::ready(Ok(self.open_item(existing_item, cx)));
 721        }
 722
 723        let worktree = match self.project.read(cx).worktree_for_id(path.worktree_id, cx) {
 724            Some(worktree) => worktree,
 725            None => {
 726                return Task::ready(Err(Arc::new(anyhow!(
 727                    "worktree {} does not exist",
 728                    path.worktree_id
 729                ))));
 730            }
 731        };
 732
 733        let project_path = path.clone();
 734        let path_openers = self.path_openers.clone();
 735        let open_task = worktree.update(cx, |worktree, cx| {
 736            for opener in path_openers.iter() {
 737                if let Some(task) = opener.open(worktree, project_path.clone(), cx) {
 738                    return task;
 739                }
 740            }
 741            Task::ready(Err(anyhow!("no opener found for path {:?}", project_path)))
 742        });
 743
 744        let pane = self.active_pane().clone().downgrade();
 745        cx.spawn(|this, mut cx| async move {
 746            let item = open_task.await?;
 747            this.update(&mut cx, |this, cx| {
 748                let pane = pane
 749                    .upgrade(&cx)
 750                    .ok_or_else(|| anyhow!("could not upgrade pane reference"))?;
 751                Ok(this.open_item_in_pane(item, &pane, cx))
 752            })
 753        })
 754    }
 755
 756    fn item_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
 757        self.items
 758            .iter()
 759            .filter_map(|i| i.upgrade(cx))
 760            .find(|i| i.project_path(cx).as_ref() == Some(path))
 761    }
 762
 763    pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemViewHandle>> {
 764        self.active_pane().read(cx).active_item()
 765    }
 766
 767    fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
 768        self.active_item(cx).and_then(|item| item.project_path(cx))
 769    }
 770
 771    pub fn save_active_item(&mut self, _: &Save, cx: &mut ViewContext<Self>) {
 772        if let Some(item) = self.active_item(cx) {
 773            let handle = cx.handle();
 774            if item.can_save(cx) {
 775                if item.has_conflict(cx.as_ref()) {
 776                    const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
 777
 778                    cx.prompt(
 779                        PromptLevel::Warning,
 780                        CONFLICT_MESSAGE,
 781                        &["Overwrite", "Cancel"],
 782                        move |answer, cx| {
 783                            if answer == 0 {
 784                                cx.spawn(|mut cx| async move {
 785                                    if let Err(error) = cx.update(|cx| item.save(cx)).unwrap().await
 786                                    {
 787                                        error!("failed to save item: {:?}, ", error);
 788                                    }
 789                                })
 790                                .detach();
 791                            }
 792                        },
 793                    );
 794                } else {
 795                    cx.spawn(|_, mut cx| async move {
 796                        if let Err(error) = cx.update(|cx| item.save(cx)).unwrap().await {
 797                            error!("failed to save item: {:?}, ", error);
 798                        }
 799                    })
 800                    .detach();
 801                }
 802            } else if item.can_save_as(cx) {
 803                let worktree = self.worktrees(cx).first();
 804                let start_abs_path = worktree
 805                    .and_then(|w| w.read(cx).as_local())
 806                    .map_or(Path::new(""), |w| w.abs_path())
 807                    .to_path_buf();
 808                cx.prompt_for_new_path(&start_abs_path, move |abs_path, cx| {
 809                    if let Some(abs_path) = abs_path {
 810                        cx.spawn(|mut cx| async move {
 811                            let result = match handle
 812                                .update(&mut cx, |this, cx| {
 813                                    this.worktree_for_abs_path(&abs_path, cx)
 814                                })
 815                                .await
 816                            {
 817                                Ok((worktree, path)) => {
 818                                    handle
 819                                        .update(&mut cx, |_, cx| {
 820                                            item.save_as(worktree, &path, cx.as_mut())
 821                                        })
 822                                        .await
 823                                }
 824                                Err(error) => Err(error),
 825                            };
 826
 827                            if let Err(error) = result {
 828                                error!("failed to save item: {:?}, ", error);
 829                            }
 830                        })
 831                        .detach()
 832                    }
 833                });
 834            }
 835        }
 836    }
 837
 838    pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
 839        let sidebar = match action.0.side {
 840            Side::Left => &mut self.left_sidebar,
 841            Side::Right => &mut self.right_sidebar,
 842        };
 843        sidebar.toggle_item(action.0.item_index);
 844        if let Some(active_item) = sidebar.active_item() {
 845            cx.focus(active_item);
 846        } else {
 847            cx.focus_self();
 848        }
 849        cx.notify();
 850    }
 851
 852    pub fn toggle_sidebar_item_focus(
 853        &mut self,
 854        action: &ToggleSidebarItemFocus,
 855        cx: &mut ViewContext<Self>,
 856    ) {
 857        let sidebar = match action.0.side {
 858            Side::Left => &mut self.left_sidebar,
 859            Side::Right => &mut self.right_sidebar,
 860        };
 861        sidebar.activate_item(action.0.item_index);
 862        if let Some(active_item) = sidebar.active_item() {
 863            if active_item.is_focused(cx) {
 864                cx.focus_self();
 865            } else {
 866                cx.focus(active_item);
 867            }
 868        }
 869        cx.notify();
 870    }
 871
 872    pub fn debug_elements(&mut self, _: &DebugElements, cx: &mut ViewContext<Self>) {
 873        match to_string_pretty(&cx.debug_elements()) {
 874            Ok(json) => {
 875                let kib = json.len() as f32 / 1024.;
 876                cx.as_mut().write_to_clipboard(ClipboardItem::new(json));
 877                log::info!(
 878                    "copied {:.1} KiB of element debug JSON to the clipboard",
 879                    kib
 880                );
 881            }
 882            Err(error) => {
 883                log::error!("error debugging elements: {}", error);
 884            }
 885        };
 886    }
 887
 888    fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
 889        let pane = cx.add_view(|_| Pane::new(self.settings.clone()));
 890        let pane_id = pane.id();
 891        cx.observe(&pane, move |me, _, cx| {
 892            let active_entry = me.active_project_path(cx);
 893            me.project
 894                .update(cx, |project, cx| project.set_active_path(active_entry, cx));
 895        })
 896        .detach();
 897        cx.subscribe(&pane, move |me, _, event, cx| {
 898            me.handle_pane_event(pane_id, event, cx)
 899        })
 900        .detach();
 901        self.panes.push(pane.clone());
 902        self.activate_pane(pane.clone(), cx);
 903        pane
 904    }
 905
 906    pub fn open_item<T>(
 907        &mut self,
 908        item_handle: T,
 909        cx: &mut ViewContext<Self>,
 910    ) -> Box<dyn ItemViewHandle>
 911    where
 912        T: 'static + ItemHandle,
 913    {
 914        self.open_item_in_pane(item_handle, &self.active_pane().clone(), cx)
 915    }
 916
 917    pub fn open_item_in_pane<T>(
 918        &mut self,
 919        item_handle: T,
 920        pane: &ViewHandle<Pane>,
 921        cx: &mut ViewContext<Self>,
 922    ) -> Box<dyn ItemViewHandle>
 923    where
 924        T: 'static + ItemHandle,
 925    {
 926        self.items.insert(item_handle.downgrade());
 927        pane.update(cx, |pane, cx| pane.open_item(item_handle, self, cx))
 928    }
 929
 930    fn activate_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
 931        self.active_pane = pane;
 932        self.status_bar.update(cx, |status_bar, cx| {
 933            status_bar.set_active_pane(&self.active_pane, cx);
 934        });
 935        cx.focus(&self.active_pane);
 936        cx.notify();
 937    }
 938
 939    fn handle_pane_event(
 940        &mut self,
 941        pane_id: usize,
 942        event: &pane::Event,
 943        cx: &mut ViewContext<Self>,
 944    ) {
 945        if let Some(pane) = self.pane(pane_id) {
 946            match event {
 947                pane::Event::Split(direction) => {
 948                    self.split_pane(pane, *direction, cx);
 949                }
 950                pane::Event::Remove => {
 951                    self.remove_pane(pane, cx);
 952                }
 953                pane::Event::Activate => {
 954                    self.activate_pane(pane, cx);
 955                }
 956            }
 957        } else {
 958            error!("pane {} not found", pane_id);
 959        }
 960    }
 961
 962    pub fn split_pane(
 963        &mut self,
 964        pane: ViewHandle<Pane>,
 965        direction: SplitDirection,
 966        cx: &mut ViewContext<Self>,
 967    ) -> ViewHandle<Pane> {
 968        let new_pane = self.add_pane(cx);
 969        self.activate_pane(new_pane.clone(), cx);
 970        if let Some(item) = pane.read(cx).active_item() {
 971            if let Some(clone) = item.clone_on_split(cx.as_mut()) {
 972                new_pane.update(cx, |new_pane, cx| new_pane.add_item_view(clone, cx));
 973            }
 974        }
 975        self.center
 976            .split(pane.id(), new_pane.id(), direction)
 977            .unwrap();
 978        cx.notify();
 979        new_pane
 980    }
 981
 982    fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
 983        if self.center.remove(pane.id()).unwrap() {
 984            self.panes.retain(|p| p != &pane);
 985            self.activate_pane(self.panes.last().unwrap().clone(), cx);
 986        }
 987    }
 988
 989    pub fn panes(&self) -> &[ViewHandle<Pane>] {
 990        &self.panes
 991    }
 992
 993    fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
 994        self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
 995    }
 996
 997    pub fn active_pane(&self) -> &ViewHandle<Pane> {
 998        &self.active_pane
 999    }
1000
1001    fn toggle_share(&mut self, _: &ToggleShare, cx: &mut ViewContext<Self>) {
1002        self.project.update(cx, |project, cx| {
1003            if project.is_local() {
1004                if project.is_shared() {
1005                    project.unshare(cx).detach();
1006                } else {
1007                    project.share(cx).detach();
1008                }
1009            }
1010        });
1011    }
1012
1013    fn render_connection_status(&self) -> Option<ElementBox> {
1014        let theme = &self.settings.borrow().theme;
1015        match &*self.client.status().borrow() {
1016            client::Status::ConnectionError
1017            | client::Status::ConnectionLost
1018            | client::Status::Reauthenticating
1019            | client::Status::Reconnecting { .. }
1020            | client::Status::ReconnectionError { .. } => Some(
1021                Container::new(
1022                    Align::new(
1023                        ConstrainedBox::new(
1024                            Svg::new("icons/offline-14.svg")
1025                                .with_color(theme.workspace.titlebar.icon_color)
1026                                .boxed(),
1027                        )
1028                        .with_width(theme.workspace.titlebar.offline_icon.width)
1029                        .boxed(),
1030                    )
1031                    .boxed(),
1032                )
1033                .with_style(theme.workspace.titlebar.offline_icon.container)
1034                .boxed(),
1035            ),
1036            client::Status::UpgradeRequired => Some(
1037                Label::new(
1038                    "Please update Zed to collaborate".to_string(),
1039                    theme.workspace.titlebar.outdated_warning.text.clone(),
1040                )
1041                .contained()
1042                .with_style(theme.workspace.titlebar.outdated_warning.container)
1043                .aligned()
1044                .boxed(),
1045            ),
1046            _ => None,
1047        }
1048    }
1049
1050    fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1051        ConstrainedBox::new(
1052            Container::new(
1053                Stack::new()
1054                    .with_child(
1055                        Align::new(
1056                            Label::new("zed".into(), theme.workspace.titlebar.title.clone())
1057                                .boxed(),
1058                        )
1059                        .boxed(),
1060                    )
1061                    .with_child(
1062                        Align::new(
1063                            Flex::row()
1064                                .with_children(self.render_share_icon(cx))
1065                                .with_children(self.render_collaborators(theme, cx))
1066                                .with_child(self.render_avatar(
1067                                    self.user_store.read(cx).current_user().as_ref(),
1068                                    self.project.read(cx).replica_id(),
1069                                    theme,
1070                                    cx,
1071                                ))
1072                                .with_children(self.render_connection_status())
1073                                .boxed(),
1074                        )
1075                        .right()
1076                        .boxed(),
1077                    )
1078                    .boxed(),
1079            )
1080            .with_style(theme.workspace.titlebar.container)
1081            .boxed(),
1082        )
1083        .with_height(theme.workspace.titlebar.height)
1084        .named("titlebar")
1085    }
1086
1087    fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1088        let mut collaborators = self
1089            .project
1090            .read(cx)
1091            .collaborators()
1092            .values()
1093            .cloned()
1094            .collect::<Vec<_>>();
1095        collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1096        collaborators
1097            .into_iter()
1098            .map(|collaborator| {
1099                self.render_avatar(Some(&collaborator.user), collaborator.replica_id, theme, cx)
1100            })
1101            .collect()
1102    }
1103
1104    fn render_avatar(
1105        &self,
1106        user: Option<&Arc<User>>,
1107        replica_id: ReplicaId,
1108        theme: &Theme,
1109        cx: &mut RenderContext<Self>,
1110    ) -> ElementBox {
1111        if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1112            ConstrainedBox::new(
1113                Stack::new()
1114                    .with_child(
1115                        ConstrainedBox::new(
1116                            Image::new(avatar)
1117                                .with_style(theme.workspace.titlebar.avatar)
1118                                .boxed(),
1119                        )
1120                        .with_width(theme.workspace.titlebar.avatar_width)
1121                        .aligned()
1122                        .boxed(),
1123                    )
1124                    .with_child(
1125                        AvatarRibbon::new(theme.editor.replica_selection_style(replica_id).cursor)
1126                            .constrained()
1127                            .with_width(theme.workspace.titlebar.avatar_ribbon.width)
1128                            .with_height(theme.workspace.titlebar.avatar_ribbon.height)
1129                            .aligned()
1130                            .bottom()
1131                            .boxed(),
1132                    )
1133                    .boxed(),
1134            )
1135            .with_width(theme.workspace.right_sidebar.width)
1136            .boxed()
1137        } else {
1138            MouseEventHandler::new::<Authenticate, _, _, _>(0, cx, |state, _| {
1139                let style = if state.hovered {
1140                    &theme.workspace.titlebar.hovered_sign_in_prompt
1141                } else {
1142                    &theme.workspace.titlebar.sign_in_prompt
1143                };
1144                Label::new("Sign in".to_string(), style.text.clone())
1145                    .contained()
1146                    .with_style(style.container)
1147                    .boxed()
1148            })
1149            .on_click(|cx| cx.dispatch_action(Authenticate))
1150            .with_cursor_style(CursorStyle::PointingHand)
1151            .aligned()
1152            .boxed()
1153        }
1154    }
1155
1156    fn render_share_icon(&self, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1157        if self.project().read(cx).is_local() && self.client.user_id().is_some() {
1158            enum Share {}
1159
1160            let color = if self.project().read(cx).is_shared() {
1161                Color::green()
1162            } else {
1163                Color::red()
1164            };
1165            Some(
1166                MouseEventHandler::new::<Share, _, _, _>(0, cx, |_, _| {
1167                    Align::new(
1168                        ConstrainedBox::new(
1169                            Svg::new("icons/broadcast-24.svg").with_color(color).boxed(),
1170                        )
1171                        .with_width(24.)
1172                        .boxed(),
1173                    )
1174                    .boxed()
1175                })
1176                .with_cursor_style(CursorStyle::PointingHand)
1177                .on_click(|cx| cx.dispatch_action(ToggleShare))
1178                .boxed(),
1179            )
1180        } else {
1181            None
1182        }
1183    }
1184}
1185
1186impl Entity for Workspace {
1187    type Event = ();
1188}
1189
1190impl View for Workspace {
1191    fn ui_name() -> &'static str {
1192        "Workspace"
1193    }
1194
1195    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1196        let settings = self.settings.borrow();
1197        let theme = &settings.theme;
1198        Flex::column()
1199            .with_child(self.render_titlebar(&theme, cx))
1200            .with_child(
1201                Stack::new()
1202                    .with_child({
1203                        let mut content = Flex::row();
1204                        content.add_child(self.left_sidebar.render(&settings, cx));
1205                        if let Some(element) = self.left_sidebar.render_active_item(&settings, cx) {
1206                            content.add_child(Flexible::new(0.8, false, element).boxed());
1207                        }
1208                        content.add_child(
1209                            Flex::column()
1210                                .with_child(
1211                                    Flexible::new(1., true, self.center.render(&settings.theme))
1212                                        .boxed(),
1213                                )
1214                                .with_child(ChildView::new(self.status_bar.id()).boxed())
1215                                .flexible(1., true)
1216                                .boxed(),
1217                        );
1218                        if let Some(element) = self.right_sidebar.render_active_item(&settings, cx)
1219                        {
1220                            content.add_child(Flexible::new(0.8, false, element).boxed());
1221                        }
1222                        content.add_child(self.right_sidebar.render(&settings, cx));
1223                        content.boxed()
1224                    })
1225                    .with_children(self.modal.as_ref().map(|m| ChildView::new(m.id()).boxed()))
1226                    .flexible(1.0, true)
1227                    .boxed(),
1228            )
1229            .contained()
1230            .with_background_color(settings.theme.workspace.background)
1231            .named("workspace")
1232    }
1233
1234    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
1235        cx.focus(&self.active_pane);
1236    }
1237}
1238
1239pub trait WorkspaceHandle {
1240    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
1241}
1242
1243impl WorkspaceHandle for ViewHandle<Workspace> {
1244    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
1245        self.read(cx)
1246            .worktrees(cx)
1247            .iter()
1248            .flat_map(|worktree| {
1249                let worktree_id = worktree.read(cx).id();
1250                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
1251                    worktree_id,
1252                    path: f.path.clone(),
1253                })
1254            })
1255            .collect::<Vec<_>>()
1256    }
1257}
1258
1259pub struct AvatarRibbon {
1260    color: Color,
1261}
1262
1263impl AvatarRibbon {
1264    pub fn new(color: Color) -> AvatarRibbon {
1265        AvatarRibbon { color }
1266    }
1267}
1268
1269impl Element for AvatarRibbon {
1270    type LayoutState = ();
1271
1272    type PaintState = ();
1273
1274    fn layout(
1275        &mut self,
1276        constraint: gpui::SizeConstraint,
1277        _: &mut gpui::LayoutContext,
1278    ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
1279        (constraint.max, ())
1280    }
1281
1282    fn paint(
1283        &mut self,
1284        bounds: gpui::geometry::rect::RectF,
1285        _: gpui::geometry::rect::RectF,
1286        _: &mut Self::LayoutState,
1287        cx: &mut gpui::PaintContext,
1288    ) -> Self::PaintState {
1289        let mut path = PathBuilder::new();
1290        path.reset(bounds.lower_left());
1291        path.curve_to(
1292            bounds.origin() + vec2f(bounds.height(), 0.),
1293            bounds.origin(),
1294        );
1295        path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
1296        path.curve_to(bounds.lower_right(), bounds.upper_right());
1297        path.line_to(bounds.lower_left());
1298        cx.scene.push_path(path.build(self.color, None));
1299    }
1300
1301    fn dispatch_event(
1302        &mut self,
1303        _: &gpui::Event,
1304        _: gpui::geometry::rect::RectF,
1305        _: &mut Self::LayoutState,
1306        _: &mut Self::PaintState,
1307        _: &mut gpui::EventContext,
1308    ) -> bool {
1309        false
1310    }
1311
1312    fn debug(
1313        &self,
1314        bounds: gpui::geometry::rect::RectF,
1315        _: &Self::LayoutState,
1316        _: &Self::PaintState,
1317        _: &gpui::DebugContext,
1318    ) -> gpui::json::Value {
1319        json::json!({
1320            "type": "AvatarRibbon",
1321            "bounds": bounds.to_json(),
1322            "color": self.color.to_json(),
1323        })
1324    }
1325}
1326
1327impl std::fmt::Debug for OpenParams {
1328    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1329        f.debug_struct("OpenParams")
1330            .field("paths", &self.paths)
1331            .finish()
1332    }
1333}
1334
1335fn open(action: &Open, cx: &mut MutableAppContext) {
1336    let app_state = action.0.clone();
1337    cx.prompt_for_paths(
1338        PathPromptOptions {
1339            files: true,
1340            directories: true,
1341            multiple: true,
1342        },
1343        move |paths, cx| {
1344            if let Some(paths) = paths {
1345                cx.dispatch_global_action(OpenPaths(OpenParams { paths, app_state }));
1346            }
1347        },
1348    );
1349}
1350
1351pub fn open_paths(
1352    abs_paths: &[PathBuf],
1353    app_state: &Arc<AppState>,
1354    cx: &mut MutableAppContext,
1355) -> Task<ViewHandle<Workspace>> {
1356    log::info!("open paths {:?}", abs_paths);
1357
1358    // Open paths in existing workspace if possible
1359    let mut existing = None;
1360    for window_id in cx.window_ids().collect::<Vec<_>>() {
1361        if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
1362            if workspace.update(cx, |view, cx| {
1363                if view.contains_paths(abs_paths, cx.as_ref()) {
1364                    existing = Some(workspace.clone());
1365                    true
1366                } else {
1367                    false
1368                }
1369            }) {
1370                break;
1371            }
1372        }
1373    }
1374
1375    let workspace = existing.unwrap_or_else(|| {
1376        cx.add_window((app_state.build_window_options)(), |cx| {
1377            let project = Project::local(
1378                app_state.client.clone(),
1379                app_state.user_store.clone(),
1380                app_state.languages.clone(),
1381                app_state.fs.clone(),
1382                cx,
1383            );
1384            (app_state.build_workspace)(project, &app_state, cx)
1385        })
1386        .1
1387    });
1388
1389    let task = workspace.update(cx, |workspace, cx| workspace.open_paths(abs_paths, cx));
1390    cx.spawn(|_| async move {
1391        task.await;
1392        workspace
1393    })
1394}
1395
1396pub fn join_project(
1397    project_id: u64,
1398    app_state: &Arc<AppState>,
1399    cx: &mut MutableAppContext,
1400) -> Task<Result<ViewHandle<Workspace>>> {
1401    for window_id in cx.window_ids().collect::<Vec<_>>() {
1402        if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
1403            if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
1404                return Task::ready(Ok(workspace));
1405            }
1406        }
1407    }
1408
1409    let app_state = app_state.clone();
1410    cx.spawn(|mut cx| async move {
1411        let project = Project::remote(
1412            project_id,
1413            app_state.client.clone(),
1414            app_state.user_store.clone(),
1415            app_state.languages.clone(),
1416            app_state.fs.clone(),
1417            &mut cx,
1418        )
1419        .await?;
1420        let (_, workspace) = cx.update(|cx| {
1421            cx.add_window((app_state.build_window_options)(), |cx| {
1422                (app_state.build_workspace)(project, &app_state, cx)
1423            })
1424        });
1425        Ok(workspace)
1426    })
1427}
1428
1429fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
1430    let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
1431        let project = Project::local(
1432            app_state.client.clone(),
1433            app_state.user_store.clone(),
1434            app_state.languages.clone(),
1435            app_state.fs.clone(),
1436            cx,
1437        );
1438        (app_state.build_workspace)(project, &app_state, cx)
1439    });
1440    cx.dispatch_action(window_id, vec![workspace.id()], &OpenNew(app_state.clone()));
1441}