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(&self, cx: &AppContext) -> Box<dyn ItemHandle>;
 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(&self, cx: &AppContext) -> Box<dyn ItemHandle>;
 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(&self, cx: &AppContext) -> Box<dyn ItemHandle> {
 365        self.read(cx).item(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                self.items.insert(clone.item(cx).downgrade());
1063                new_pane.update(cx, |new_pane, cx| new_pane.add_item_view(clone, cx));
1064            }
1065        }
1066        self.center.split(&pane, &new_pane, direction).unwrap();
1067        cx.notify();
1068        new_pane
1069    }
1070
1071    fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1072        if self.center.remove(&pane).unwrap() {
1073            self.panes.retain(|p| p != &pane);
1074            self.activate_pane(self.panes.last().unwrap().clone(), cx);
1075        }
1076    }
1077
1078    pub fn panes(&self) -> &[ViewHandle<Pane>] {
1079        &self.panes
1080    }
1081
1082    fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1083        self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1084    }
1085
1086    pub fn active_pane(&self) -> &ViewHandle<Pane> {
1087        &self.active_pane
1088    }
1089
1090    fn toggle_share(&mut self, _: &ToggleShare, cx: &mut ViewContext<Self>) {
1091        self.project.update(cx, |project, cx| {
1092            if project.is_local() {
1093                if project.is_shared() {
1094                    project.unshare(cx).detach();
1095                } else {
1096                    project.share(cx).detach();
1097                }
1098            }
1099        });
1100    }
1101
1102    fn render_connection_status(&self) -> Option<ElementBox> {
1103        let theme = &self.settings.borrow().theme;
1104        match &*self.client.status().borrow() {
1105            client::Status::ConnectionError
1106            | client::Status::ConnectionLost
1107            | client::Status::Reauthenticating
1108            | client::Status::Reconnecting { .. }
1109            | client::Status::ReconnectionError { .. } => Some(
1110                Container::new(
1111                    Align::new(
1112                        ConstrainedBox::new(
1113                            Svg::new("icons/offline-14.svg")
1114                                .with_color(theme.workspace.titlebar.offline_icon.color)
1115                                .boxed(),
1116                        )
1117                        .with_width(theme.workspace.titlebar.offline_icon.width)
1118                        .boxed(),
1119                    )
1120                    .boxed(),
1121                )
1122                .with_style(theme.workspace.titlebar.offline_icon.container)
1123                .boxed(),
1124            ),
1125            client::Status::UpgradeRequired => Some(
1126                Label::new(
1127                    "Please update Zed to collaborate".to_string(),
1128                    theme.workspace.titlebar.outdated_warning.text.clone(),
1129                )
1130                .contained()
1131                .with_style(theme.workspace.titlebar.outdated_warning.container)
1132                .aligned()
1133                .boxed(),
1134            ),
1135            _ => None,
1136        }
1137    }
1138
1139    fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1140        ConstrainedBox::new(
1141            Container::new(
1142                Stack::new()
1143                    .with_child(
1144                        Align::new(
1145                            Label::new("zed".into(), theme.workspace.titlebar.title.clone())
1146                                .boxed(),
1147                        )
1148                        .boxed(),
1149                    )
1150                    .with_child(
1151                        Align::new(
1152                            Flex::row()
1153                                .with_children(self.render_share_icon(theme, cx))
1154                                .with_children(self.render_collaborators(theme, cx))
1155                                .with_child(self.render_current_user(
1156                                    self.user_store.read(cx).current_user().as_ref(),
1157                                    self.project.read(cx).replica_id(),
1158                                    theme,
1159                                    cx,
1160                                ))
1161                                .with_children(self.render_connection_status())
1162                                .boxed(),
1163                        )
1164                        .right()
1165                        .boxed(),
1166                    )
1167                    .boxed(),
1168            )
1169            .with_style(theme.workspace.titlebar.container)
1170            .boxed(),
1171        )
1172        .with_height(theme.workspace.titlebar.height)
1173        .named("titlebar")
1174    }
1175
1176    fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1177        let mut collaborators = self
1178            .project
1179            .read(cx)
1180            .collaborators()
1181            .values()
1182            .cloned()
1183            .collect::<Vec<_>>();
1184        collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1185        collaborators
1186            .into_iter()
1187            .filter_map(|collaborator| {
1188                Some(self.render_avatar(
1189                    collaborator.user.avatar.clone()?,
1190                    collaborator.replica_id,
1191                    theme,
1192                ))
1193            })
1194            .collect()
1195    }
1196
1197    fn render_current_user(
1198        &self,
1199        user: Option<&Arc<User>>,
1200        replica_id: ReplicaId,
1201        theme: &Theme,
1202        cx: &mut RenderContext<Self>,
1203    ) -> ElementBox {
1204        if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1205            self.render_avatar(avatar, replica_id, theme)
1206        } else {
1207            MouseEventHandler::new::<Authenticate, _, _>(0, cx, |state, _| {
1208                let style = if state.hovered {
1209                    &theme.workspace.titlebar.hovered_sign_in_prompt
1210                } else {
1211                    &theme.workspace.titlebar.sign_in_prompt
1212                };
1213                Label::new("Sign in".to_string(), style.text.clone())
1214                    .contained()
1215                    .with_style(style.container)
1216                    .boxed()
1217            })
1218            .on_click(|cx| cx.dispatch_action(Authenticate))
1219            .with_cursor_style(CursorStyle::PointingHand)
1220            .aligned()
1221            .boxed()
1222        }
1223    }
1224
1225    fn render_avatar(
1226        &self,
1227        avatar: Arc<ImageData>,
1228        replica_id: ReplicaId,
1229        theme: &Theme,
1230    ) -> ElementBox {
1231        ConstrainedBox::new(
1232            Stack::new()
1233                .with_child(
1234                    ConstrainedBox::new(
1235                        Image::new(avatar)
1236                            .with_style(theme.workspace.titlebar.avatar)
1237                            .boxed(),
1238                    )
1239                    .with_width(theme.workspace.titlebar.avatar_width)
1240                    .aligned()
1241                    .boxed(),
1242                )
1243                .with_child(
1244                    AvatarRibbon::new(theme.editor.replica_selection_style(replica_id).cursor)
1245                        .constrained()
1246                        .with_width(theme.workspace.titlebar.avatar_ribbon.width)
1247                        .with_height(theme.workspace.titlebar.avatar_ribbon.height)
1248                        .aligned()
1249                        .bottom()
1250                        .boxed(),
1251                )
1252                .boxed(),
1253        )
1254        .with_width(theme.workspace.right_sidebar.width)
1255        .boxed()
1256    }
1257
1258    fn render_share_icon(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1259        if self.project().read(cx).is_local() && self.client.user_id().is_some() {
1260            enum Share {}
1261
1262            let color = if self.project().read(cx).is_shared() {
1263                theme.workspace.titlebar.share_icon_active_color
1264            } else {
1265                theme.workspace.titlebar.share_icon_color
1266            };
1267            Some(
1268                MouseEventHandler::new::<Share, _, _>(0, cx, |_, _| {
1269                    Align::new(
1270                        ConstrainedBox::new(
1271                            Svg::new("icons/broadcast-24.svg").with_color(color).boxed(),
1272                        )
1273                        .with_width(24.)
1274                        .boxed(),
1275                    )
1276                    .boxed()
1277                })
1278                .with_cursor_style(CursorStyle::PointingHand)
1279                .on_click(|cx| cx.dispatch_action(ToggleShare))
1280                .boxed(),
1281            )
1282        } else {
1283            None
1284        }
1285    }
1286}
1287
1288impl Entity for Workspace {
1289    type Event = ();
1290}
1291
1292impl View for Workspace {
1293    fn ui_name() -> &'static str {
1294        "Workspace"
1295    }
1296
1297    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1298        let settings = self.settings.borrow();
1299        let theme = &settings.theme;
1300        Flex::column()
1301            .with_child(self.render_titlebar(&theme, cx))
1302            .with_child(
1303                Stack::new()
1304                    .with_child({
1305                        let mut content = Flex::row();
1306                        content.add_child(self.left_sidebar.render(&settings, cx));
1307                        if let Some(element) = self.left_sidebar.render_active_item(&settings, cx) {
1308                            content.add_child(Flexible::new(0.8, false, element).boxed());
1309                        }
1310                        content.add_child(
1311                            Flex::column()
1312                                .with_child(
1313                                    Flexible::new(1., true, self.center.render(&settings.theme))
1314                                        .boxed(),
1315                                )
1316                                .with_child(ChildView::new(&self.status_bar).boxed())
1317                                .flexible(1., true)
1318                                .boxed(),
1319                        );
1320                        if let Some(element) = self.right_sidebar.render_active_item(&settings, cx)
1321                        {
1322                            content.add_child(Flexible::new(0.8, false, element).boxed());
1323                        }
1324                        content.add_child(self.right_sidebar.render(&settings, cx));
1325                        content.boxed()
1326                    })
1327                    .with_children(self.modal.as_ref().map(|m| ChildView::new(m).boxed()))
1328                    .flexible(1.0, true)
1329                    .boxed(),
1330            )
1331            .contained()
1332            .with_background_color(settings.theme.workspace.background)
1333            .named("workspace")
1334    }
1335
1336    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
1337        cx.focus(&self.active_pane);
1338    }
1339}
1340
1341pub trait WorkspaceHandle {
1342    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
1343}
1344
1345impl WorkspaceHandle for ViewHandle<Workspace> {
1346    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
1347        self.read(cx)
1348            .worktrees(cx)
1349            .flat_map(|worktree| {
1350                let worktree_id = worktree.read(cx).id();
1351                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
1352                    worktree_id,
1353                    path: f.path.clone(),
1354                })
1355            })
1356            .collect::<Vec<_>>()
1357    }
1358}
1359
1360pub struct AvatarRibbon {
1361    color: Color,
1362}
1363
1364impl AvatarRibbon {
1365    pub fn new(color: Color) -> AvatarRibbon {
1366        AvatarRibbon { color }
1367    }
1368}
1369
1370impl Element for AvatarRibbon {
1371    type LayoutState = ();
1372
1373    type PaintState = ();
1374
1375    fn layout(
1376        &mut self,
1377        constraint: gpui::SizeConstraint,
1378        _: &mut gpui::LayoutContext,
1379    ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
1380        (constraint.max, ())
1381    }
1382
1383    fn paint(
1384        &mut self,
1385        bounds: gpui::geometry::rect::RectF,
1386        _: gpui::geometry::rect::RectF,
1387        _: &mut Self::LayoutState,
1388        cx: &mut gpui::PaintContext,
1389    ) -> Self::PaintState {
1390        let mut path = PathBuilder::new();
1391        path.reset(bounds.lower_left());
1392        path.curve_to(
1393            bounds.origin() + vec2f(bounds.height(), 0.),
1394            bounds.origin(),
1395        );
1396        path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
1397        path.curve_to(bounds.lower_right(), bounds.upper_right());
1398        path.line_to(bounds.lower_left());
1399        cx.scene.push_path(path.build(self.color, None));
1400    }
1401
1402    fn dispatch_event(
1403        &mut self,
1404        _: &gpui::Event,
1405        _: gpui::geometry::rect::RectF,
1406        _: &mut Self::LayoutState,
1407        _: &mut Self::PaintState,
1408        _: &mut gpui::EventContext,
1409    ) -> bool {
1410        false
1411    }
1412
1413    fn debug(
1414        &self,
1415        bounds: gpui::geometry::rect::RectF,
1416        _: &Self::LayoutState,
1417        _: &Self::PaintState,
1418        _: &gpui::DebugContext,
1419    ) -> gpui::json::Value {
1420        json::json!({
1421            "type": "AvatarRibbon",
1422            "bounds": bounds.to_json(),
1423            "color": self.color.to_json(),
1424        })
1425    }
1426}
1427
1428impl std::fmt::Debug for OpenParams {
1429    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1430        f.debug_struct("OpenParams")
1431            .field("paths", &self.paths)
1432            .finish()
1433    }
1434}
1435
1436fn open(action: &Open, cx: &mut MutableAppContext) {
1437    let app_state = action.0.clone();
1438    let mut paths = cx.prompt_for_paths(PathPromptOptions {
1439        files: true,
1440        directories: true,
1441        multiple: true,
1442    });
1443    cx.spawn(|mut cx| async move {
1444        if let Some(paths) = paths.recv().await.flatten() {
1445            cx.update(|cx| cx.dispatch_global_action(OpenPaths(OpenParams { paths, app_state })));
1446        }
1447    })
1448    .detach();
1449}
1450
1451pub fn open_paths(
1452    abs_paths: &[PathBuf],
1453    app_state: &Arc<AppState>,
1454    cx: &mut MutableAppContext,
1455) -> Task<ViewHandle<Workspace>> {
1456    log::info!("open paths {:?}", abs_paths);
1457
1458    // Open paths in existing workspace if possible
1459    let mut existing = None;
1460    for window_id in cx.window_ids().collect::<Vec<_>>() {
1461        if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
1462            if workspace_handle.update(cx, |workspace, cx| {
1463                if workspace.contains_paths(abs_paths, cx.as_ref()) {
1464                    cx.activate_window(window_id);
1465                    existing = Some(workspace_handle.clone());
1466                    true
1467                } else {
1468                    false
1469                }
1470            }) {
1471                break;
1472            }
1473        }
1474    }
1475
1476    let workspace = existing.unwrap_or_else(|| {
1477        cx.add_window((app_state.build_window_options)(), |cx| {
1478            let project = Project::local(
1479                app_state.client.clone(),
1480                app_state.user_store.clone(),
1481                app_state.languages.clone(),
1482                app_state.fs.clone(),
1483                cx,
1484            );
1485            (app_state.build_workspace)(project, &app_state, cx)
1486        })
1487        .1
1488    });
1489
1490    let task = workspace.update(cx, |workspace, cx| workspace.open_paths(abs_paths, cx));
1491    cx.spawn(|_| async move {
1492        task.await;
1493        workspace
1494    })
1495}
1496
1497pub fn join_project(
1498    project_id: u64,
1499    app_state: &Arc<AppState>,
1500    cx: &mut MutableAppContext,
1501) -> Task<Result<ViewHandle<Workspace>>> {
1502    for window_id in cx.window_ids().collect::<Vec<_>>() {
1503        if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
1504            if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
1505                return Task::ready(Ok(workspace));
1506            }
1507        }
1508    }
1509
1510    let app_state = app_state.clone();
1511    cx.spawn(|mut cx| async move {
1512        let project = Project::remote(
1513            project_id,
1514            app_state.client.clone(),
1515            app_state.user_store.clone(),
1516            app_state.languages.clone(),
1517            app_state.fs.clone(),
1518            &mut cx,
1519        )
1520        .await?;
1521        let (_, workspace) = cx.update(|cx| {
1522            cx.add_window((app_state.build_window_options)(), |cx| {
1523                (app_state.build_workspace)(project, &app_state, cx)
1524            })
1525        });
1526        Ok(workspace)
1527    })
1528}
1529
1530fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
1531    let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
1532        let project = Project::local(
1533            app_state.client.clone(),
1534            app_state.user_store.clone(),
1535            app_state.languages.clone(),
1536            app_state.fs.clone(),
1537            cx,
1538        );
1539        (app_state.build_workspace)(project, &app_state, cx)
1540    });
1541    cx.dispatch_action(window_id, vec![workspace.id()], &OpenNew(app_state.clone()));
1542}