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