workspace.rs

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