workspace.rs

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