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