workspace.rs

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