workspace.rs

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