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