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::test());
 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, |_, project, cx| {
 580            if project.read(cx).is_read_only() {
 581                cx.blur();
 582            }
 583            cx.notify()
 584        })
 585        .detach();
 586
 587        let pane = cx.add_view(|_| Pane::new(params.settings.clone()));
 588        let pane_id = pane.id();
 589        cx.observe(&pane, move |me, _, cx| {
 590            let active_entry = me.active_project_path(cx);
 591            me.project
 592                .update(cx, |project, cx| project.set_active_path(active_entry, cx));
 593        })
 594        .detach();
 595        cx.subscribe(&pane, move |me, _, event, cx| {
 596            me.handle_pane_event(pane_id, event, cx)
 597        })
 598        .detach();
 599        cx.focus(&pane);
 600
 601        let status_bar = cx.add_view(|cx| StatusBar::new(&pane, params.settings.clone(), cx));
 602        let mut current_user = params.user_store.read(cx).watch_current_user().clone();
 603        let mut connection_status = params.client.status().clone();
 604        let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
 605            current_user.recv().await;
 606            connection_status.recv().await;
 607            let mut stream =
 608                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 609
 610            while stream.recv().await.is_some() {
 611                cx.update(|cx| {
 612                    if let Some(this) = this.upgrade(cx) {
 613                        this.update(cx, |_, cx| cx.notify());
 614                    }
 615                })
 616            }
 617        });
 618
 619        Workspace {
 620            modal: None,
 621            weak_self: cx.weak_handle(),
 622            center: PaneGroup::new(pane.clone()),
 623            panes: vec![pane.clone()],
 624            active_pane: pane.clone(),
 625            status_bar,
 626            settings: params.settings.clone(),
 627            client: params.client.clone(),
 628            user_store: params.user_store.clone(),
 629            fs: params.fs.clone(),
 630            left_sidebar: Sidebar::new(Side::Left),
 631            right_sidebar: Sidebar::new(Side::Right),
 632            project: params.project.clone(),
 633            path_openers: params.path_openers.clone(),
 634            items: Default::default(),
 635            _observe_current_user,
 636        }
 637    }
 638
 639    pub fn weak_handle(&self) -> WeakViewHandle<Self> {
 640        self.weak_self.clone()
 641    }
 642
 643    pub fn settings(&self) -> watch::Receiver<Settings> {
 644        self.settings.clone()
 645    }
 646
 647    pub fn left_sidebar_mut(&mut self) -> &mut Sidebar {
 648        &mut self.left_sidebar
 649    }
 650
 651    pub fn right_sidebar_mut(&mut self) -> &mut Sidebar {
 652        &mut self.right_sidebar
 653    }
 654
 655    pub fn status_bar(&self) -> &ViewHandle<StatusBar> {
 656        &self.status_bar
 657    }
 658
 659    pub fn project(&self) -> &ModelHandle<Project> {
 660        &self.project
 661    }
 662
 663    pub fn worktrees<'a>(
 664        &self,
 665        cx: &'a AppContext,
 666    ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
 667        self.project.read(cx).worktrees(cx)
 668    }
 669
 670    pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
 671        paths.iter().all(|path| self.contains_path(&path, cx))
 672    }
 673
 674    pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
 675        for worktree in self.worktrees(cx) {
 676            let worktree = worktree.read(cx).as_local();
 677            if worktree.map_or(false, |w| w.contains_abs_path(path)) {
 678                return true;
 679            }
 680        }
 681        false
 682    }
 683
 684    pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
 685        let futures = self
 686            .worktrees(cx)
 687            .filter_map(|worktree| worktree.read(cx).as_local())
 688            .map(|worktree| worktree.scan_complete())
 689            .collect::<Vec<_>>();
 690        async move {
 691            for future in futures {
 692                future.await;
 693            }
 694        }
 695    }
 696
 697    pub fn open_paths(
 698        &mut self,
 699        abs_paths: &[PathBuf],
 700        cx: &mut ViewContext<Self>,
 701    ) -> Task<Vec<Option<Result<Box<dyn ItemViewHandle>, Arc<anyhow::Error>>>>> {
 702        let entries = abs_paths
 703            .iter()
 704            .cloned()
 705            .map(|path| self.project_path_for_path(&path, cx))
 706            .collect::<Vec<_>>();
 707
 708        let fs = self.fs.clone();
 709        let tasks = abs_paths
 710            .iter()
 711            .cloned()
 712            .zip(entries.into_iter())
 713            .map(|(abs_path, project_path)| {
 714                cx.spawn(|this, mut cx| {
 715                    let fs = fs.clone();
 716                    async move {
 717                        let project_path = project_path.await.ok()?;
 718                        if fs.is_file(&abs_path).await {
 719                            Some(
 720                                this.update(&mut cx, |this, cx| this.open_path(project_path, cx))
 721                                    .await,
 722                            )
 723                        } else {
 724                            None
 725                        }
 726                    }
 727                })
 728            })
 729            .collect::<Vec<_>>();
 730
 731        cx.foreground().spawn(async move {
 732            let mut items = Vec::new();
 733            for task in tasks {
 734                items.push(task.await);
 735            }
 736            items
 737        })
 738    }
 739
 740    fn project_path_for_path(
 741        &self,
 742        abs_path: &Path,
 743        cx: &mut ViewContext<Self>,
 744    ) -> Task<Result<ProjectPath>> {
 745        let entry = self.project().update(cx, |project, cx| {
 746            project.find_or_create_local_worktree(abs_path, true, cx)
 747        });
 748        cx.spawn(|_, cx| async move {
 749            let (worktree, path) = entry.await?;
 750            Ok(ProjectPath {
 751                worktree_id: worktree.read_with(&cx, |t, _| t.id()),
 752                path: path.into(),
 753            })
 754        })
 755    }
 756
 757    // Returns the model that was toggled closed if it was open
 758    pub fn toggle_modal<V, F>(&mut self, cx: &mut ViewContext<Self>, add_view: F) -> Option<ViewHandle<V>>
 759    where
 760        V: 'static + View,
 761        F: FnOnce(&mut ViewContext<Self>, &mut Self) -> ViewHandle<V>,
 762    {
 763        cx.notify();
 764        // Whatever modal was visible is getting clobbered. If its the same type as V, then return
 765        // it. Otherwise, create a new modal and set it as active.
 766        let already_open_modal = self.modal.take()
 767            .and_then(|modal| modal.downcast::<V>());
 768        if let Some(already_open_modal) = already_open_modal {
 769            cx.focus_self();
 770            Some(already_open_modal)
 771        } else {
 772            let modal = add_view(cx, self);
 773            cx.focus(&modal);
 774            self.modal = Some(modal.into());
 775            None
 776        }
 777    }
 778
 779    pub fn modal(&self) -> Option<&AnyViewHandle> {
 780        self.modal.as_ref()
 781    }
 782
 783    pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
 784        if self.modal.take().is_some() {
 785            cx.focus(&self.active_pane);
 786            cx.notify();
 787        }
 788    }
 789
 790    pub fn open_path(
 791        &mut self,
 792        path: ProjectPath,
 793        cx: &mut ViewContext<Self>,
 794    ) -> Task<Result<Box<dyn ItemViewHandle>, Arc<anyhow::Error>>> {
 795        let load_task = self.load_path(path, cx);
 796        let pane = self.active_pane().clone().downgrade();
 797        cx.spawn(|this, mut cx| async move {
 798            let item = load_task.await?;
 799            this.update(&mut cx, |this, cx| {
 800                let pane = pane
 801                    .upgrade(cx)
 802                    .ok_or_else(|| anyhow!("could not upgrade pane reference"))?;
 803                Ok(this.open_item_in_pane(item, &pane, cx))
 804            })
 805        })
 806    }
 807
 808    pub fn load_path(
 809        &mut self,
 810        path: ProjectPath,
 811        cx: &mut ViewContext<Self>,
 812    ) -> Task<Result<Box<dyn ItemHandle>>> {
 813        if let Some(existing_item) = self.item_for_path(&path, cx) {
 814            return Task::ready(Ok(existing_item));
 815        }
 816
 817        let project_path = path.clone();
 818        let path_openers = self.path_openers.clone();
 819        self.project.update(cx, |project, cx| {
 820            for opener in path_openers.iter() {
 821                if let Some(task) = opener.open(project, project_path.clone(), cx) {
 822                    return task;
 823                }
 824            }
 825            Task::ready(Err(anyhow!("no opener found for path {:?}", project_path)))
 826        })
 827    }
 828
 829    fn item_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
 830        self.items
 831            .values()
 832            .filter_map(|i| i.upgrade(cx))
 833            .find(|i| i.project_path(cx).as_ref() == Some(path))
 834    }
 835
 836    pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<ModelHandle<T>> {
 837        self.items
 838            .values()
 839            .find_map(|i| i.upgrade(cx).and_then(|i| i.to_any().downcast()))
 840    }
 841
 842    pub fn items_of_type<'a, T: Item>(
 843        &'a self,
 844        cx: &'a AppContext,
 845    ) -> impl 'a + Iterator<Item = ModelHandle<T>> {
 846        self.items
 847            .values()
 848            .filter_map(|i| i.upgrade(cx).and_then(|i| i.to_any().downcast()))
 849    }
 850
 851    pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemViewHandle>> {
 852        self.active_pane().read(cx).active_item()
 853    }
 854
 855    fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
 856        self.active_item(cx).and_then(|item| item.project_path(cx))
 857    }
 858
 859    pub fn save_active_item(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
 860        let project = self.project.clone();
 861        if let Some(item) = self.active_item(cx) {
 862            if item.can_save(cx) {
 863                if item.has_conflict(cx.as_ref()) {
 864                    const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
 865
 866                    let mut answer = cx.prompt(
 867                        PromptLevel::Warning,
 868                        CONFLICT_MESSAGE,
 869                        &["Overwrite", "Cancel"],
 870                    );
 871                    cx.spawn(|_, mut cx| async move {
 872                        let answer = answer.recv().await;
 873                        if answer == Some(0) {
 874                            cx.update(|cx| item.save(project, cx)).await?;
 875                        }
 876                        Ok(())
 877                    })
 878                } else {
 879                    item.save(project, cx)
 880                }
 881            } else if item.can_save_as(cx) {
 882                let worktree = self.worktrees(cx).next();
 883                let start_abs_path = worktree
 884                    .and_then(|w| w.read(cx).as_local())
 885                    .map_or(Path::new(""), |w| w.abs_path())
 886                    .to_path_buf();
 887                let mut abs_path = cx.prompt_for_new_path(&start_abs_path);
 888                cx.spawn(|_, mut cx| async move {
 889                    if let Some(abs_path) = abs_path.recv().await.flatten() {
 890                        cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
 891                    }
 892                    Ok(())
 893                })
 894            } else {
 895                Task::ready(Ok(()))
 896            }
 897        } else {
 898            Task::ready(Ok(()))
 899        }
 900    }
 901
 902    pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
 903        let sidebar = match action.0.side {
 904            Side::Left => &mut self.left_sidebar,
 905            Side::Right => &mut self.right_sidebar,
 906        };
 907        sidebar.toggle_item(action.0.item_index);
 908        if let Some(active_item) = sidebar.active_item() {
 909            cx.focus(active_item);
 910        } else {
 911            cx.focus_self();
 912        }
 913        cx.notify();
 914    }
 915
 916    pub fn toggle_sidebar_item_focus(
 917        &mut self,
 918        action: &ToggleSidebarItemFocus,
 919        cx: &mut ViewContext<Self>,
 920    ) {
 921        let sidebar = match action.0.side {
 922            Side::Left => &mut self.left_sidebar,
 923            Side::Right => &mut self.right_sidebar,
 924        };
 925        sidebar.activate_item(action.0.item_index);
 926        if let Some(active_item) = sidebar.active_item() {
 927            if active_item.is_focused(cx) {
 928                cx.focus_self();
 929            } else {
 930                cx.focus(active_item);
 931            }
 932        }
 933        cx.notify();
 934    }
 935
 936    pub fn debug_elements(&mut self, _: &DebugElements, cx: &mut ViewContext<Self>) {
 937        match to_string_pretty(&cx.debug_elements()) {
 938            Ok(json) => {
 939                let kib = json.len() as f32 / 1024.;
 940                cx.as_mut().write_to_clipboard(ClipboardItem::new(json));
 941                log::info!(
 942                    "copied {:.1} KiB of element debug JSON to the clipboard",
 943                    kib
 944                );
 945            }
 946            Err(error) => {
 947                log::error!("error debugging elements: {}", error);
 948            }
 949        };
 950    }
 951
 952    fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
 953        let pane = cx.add_view(|_| Pane::new(self.settings.clone()));
 954        let pane_id = pane.id();
 955        cx.observe(&pane, move |me, _, cx| {
 956            let active_entry = me.active_project_path(cx);
 957            me.project
 958                .update(cx, |project, cx| project.set_active_path(active_entry, cx));
 959        })
 960        .detach();
 961        cx.subscribe(&pane, move |me, _, event, cx| {
 962            me.handle_pane_event(pane_id, event, cx)
 963        })
 964        .detach();
 965        self.panes.push(pane.clone());
 966        self.activate_pane(pane.clone(), cx);
 967        pane
 968    }
 969
 970    pub fn open_item<T>(
 971        &mut self,
 972        item_handle: T,
 973        cx: &mut ViewContext<Self>,
 974    ) -> Box<dyn ItemViewHandle>
 975    where
 976        T: 'static + ItemHandle,
 977    {
 978        self.open_item_in_pane(item_handle, &self.active_pane().clone(), cx)
 979    }
 980
 981    pub fn open_item_in_pane<T>(
 982        &mut self,
 983        item_handle: T,
 984        pane: &ViewHandle<Pane>,
 985        cx: &mut ViewContext<Self>,
 986    ) -> Box<dyn ItemViewHandle>
 987    where
 988        T: 'static + ItemHandle,
 989    {
 990        self.items
 991            .insert(Reverse(item_handle.id()), item_handle.downgrade());
 992        pane.update(cx, |pane, cx| pane.open_item(item_handle, self, cx))
 993    }
 994
 995    pub fn activate_pane_for_item(
 996        &mut self,
 997        item: &dyn ItemHandle,
 998        cx: &mut ViewContext<Self>,
 999    ) -> bool {
1000        let pane = self.panes.iter().find_map(|pane| {
1001            if pane.read(cx).contains_item(item) {
1002                Some(pane.clone())
1003            } else {
1004                None
1005            }
1006        });
1007        if let Some(pane) = pane {
1008            self.activate_pane(pane.clone(), cx);
1009            true
1010        } else {
1011            false
1012        }
1013    }
1014
1015    pub fn activate_item(&mut self, item: &dyn ItemHandle, cx: &mut ViewContext<Self>) -> bool {
1016        let result = self.panes.iter().find_map(|pane| {
1017            if let Some(ix) = pane.read(cx).index_for_item(item) {
1018                Some((pane.clone(), ix))
1019            } else {
1020                None
1021            }
1022        });
1023        if let Some((pane, ix)) = result {
1024            self.activate_pane(pane.clone(), cx);
1025            pane.update(cx, |pane, cx| pane.activate_item(ix, cx));
1026            true
1027        } else {
1028            false
1029        }
1030    }
1031
1032    pub fn activate_next_pane(&mut self, cx: &mut ViewContext<Self>) {
1033        let ix = self
1034            .panes
1035            .iter()
1036            .position(|pane| pane == &self.active_pane)
1037            .unwrap();
1038        let next_ix = (ix + 1) % self.panes.len();
1039        self.activate_pane(self.panes[next_ix].clone(), cx);
1040    }
1041
1042    fn activate_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1043        if self.active_pane != pane {
1044            self.active_pane = pane;
1045            self.status_bar.update(cx, |status_bar, cx| {
1046                status_bar.set_active_pane(&self.active_pane, cx);
1047            });
1048            cx.focus(&self.active_pane);
1049            cx.notify();
1050        }
1051    }
1052
1053    fn handle_pane_event(
1054        &mut self,
1055        pane_id: usize,
1056        event: &pane::Event,
1057        cx: &mut ViewContext<Self>,
1058    ) {
1059        if let Some(pane) = self.pane(pane_id) {
1060            match event {
1061                pane::Event::Split(direction) => {
1062                    self.split_pane(pane, *direction, cx);
1063                }
1064                pane::Event::Remove => {
1065                    self.remove_pane(pane, cx);
1066                }
1067                pane::Event::Activate => {
1068                    self.activate_pane(pane, cx);
1069                }
1070            }
1071        } else {
1072            error!("pane {} not found", pane_id);
1073        }
1074    }
1075
1076    pub fn split_pane(
1077        &mut self,
1078        pane: ViewHandle<Pane>,
1079        direction: SplitDirection,
1080        cx: &mut ViewContext<Self>,
1081    ) -> ViewHandle<Pane> {
1082        let new_pane = self.add_pane(cx);
1083        self.activate_pane(new_pane.clone(), cx);
1084        if let Some(item) = pane.read(cx).active_item() {
1085            let nav_history = new_pane.read(cx).nav_history().clone();
1086            if let Some(clone) = item.clone_on_split(nav_history, cx.as_mut()) {
1087                let item = clone.item(cx).downgrade();
1088                self.items.insert(Reverse(item.id()), item);
1089                new_pane.update(cx, |new_pane, cx| new_pane.add_item_view(clone, cx));
1090            }
1091        }
1092        self.center.split(&pane, &new_pane, direction).unwrap();
1093        cx.notify();
1094        new_pane
1095    }
1096
1097    fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1098        if self.center.remove(&pane).unwrap() {
1099            self.panes.retain(|p| p != &pane);
1100            self.activate_pane(self.panes.last().unwrap().clone(), cx);
1101        }
1102    }
1103
1104    pub fn panes(&self) -> &[ViewHandle<Pane>] {
1105        &self.panes
1106    }
1107
1108    fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1109        self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1110    }
1111
1112    pub fn active_pane(&self) -> &ViewHandle<Pane> {
1113        &self.active_pane
1114    }
1115
1116    fn toggle_share(&mut self, _: &ToggleShare, cx: &mut ViewContext<Self>) {
1117        self.project.update(cx, |project, cx| {
1118            if project.is_local() {
1119                if project.is_shared() {
1120                    project.unshare(cx).detach();
1121                } else {
1122                    project.share(cx).detach();
1123                }
1124            }
1125        });
1126    }
1127
1128    fn render_connection_status(&self) -> Option<ElementBox> {
1129        let theme = &self.settings.borrow().theme;
1130        match &*self.client.status().borrow() {
1131            client::Status::ConnectionError
1132            | client::Status::ConnectionLost
1133            | client::Status::Reauthenticating
1134            | client::Status::Reconnecting { .. }
1135            | client::Status::ReconnectionError { .. } => Some(
1136                Container::new(
1137                    Align::new(
1138                        ConstrainedBox::new(
1139                            Svg::new("icons/offline-14.svg")
1140                                .with_color(theme.workspace.titlebar.offline_icon.color)
1141                                .boxed(),
1142                        )
1143                        .with_width(theme.workspace.titlebar.offline_icon.width)
1144                        .boxed(),
1145                    )
1146                    .boxed(),
1147                )
1148                .with_style(theme.workspace.titlebar.offline_icon.container)
1149                .boxed(),
1150            ),
1151            client::Status::UpgradeRequired => Some(
1152                Label::new(
1153                    "Please update Zed to collaborate".to_string(),
1154                    theme.workspace.titlebar.outdated_warning.text.clone(),
1155                )
1156                .contained()
1157                .with_style(theme.workspace.titlebar.outdated_warning.container)
1158                .aligned()
1159                .boxed(),
1160            ),
1161            _ => None,
1162        }
1163    }
1164
1165    fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1166        ConstrainedBox::new(
1167            Container::new(
1168                Stack::new()
1169                    .with_child(
1170                        Align::new(
1171                            Label::new("zed".into(), theme.workspace.titlebar.title.clone())
1172                                .boxed(),
1173                        )
1174                        .boxed(),
1175                    )
1176                    .with_child(
1177                        Align::new(
1178                            Flex::row()
1179                                .with_children(self.render_share_icon(theme, cx))
1180                                .with_children(self.render_collaborators(theme, cx))
1181                                .with_child(self.render_current_user(
1182                                    self.user_store.read(cx).current_user().as_ref(),
1183                                    self.project.read(cx).replica_id(),
1184                                    theme,
1185                                    cx,
1186                                ))
1187                                .with_children(self.render_connection_status())
1188                                .boxed(),
1189                        )
1190                        .right()
1191                        .boxed(),
1192                    )
1193                    .boxed(),
1194            )
1195            .with_style(theme.workspace.titlebar.container)
1196            .boxed(),
1197        )
1198        .with_height(theme.workspace.titlebar.height)
1199        .named("titlebar")
1200    }
1201
1202    fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1203        let mut collaborators = self
1204            .project
1205            .read(cx)
1206            .collaborators()
1207            .values()
1208            .cloned()
1209            .collect::<Vec<_>>();
1210        collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1211        collaborators
1212            .into_iter()
1213            .filter_map(|collaborator| {
1214                Some(self.render_avatar(
1215                    collaborator.user.avatar.clone()?,
1216                    collaborator.replica_id,
1217                    theme,
1218                ))
1219            })
1220            .collect()
1221    }
1222
1223    fn render_current_user(
1224        &self,
1225        user: Option<&Arc<User>>,
1226        replica_id: ReplicaId,
1227        theme: &Theme,
1228        cx: &mut RenderContext<Self>,
1229    ) -> ElementBox {
1230        if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1231            self.render_avatar(avatar, replica_id, theme)
1232        } else {
1233            MouseEventHandler::new::<Authenticate, _, _>(0, cx, |state, _| {
1234                let style = if state.hovered {
1235                    &theme.workspace.titlebar.hovered_sign_in_prompt
1236                } else {
1237                    &theme.workspace.titlebar.sign_in_prompt
1238                };
1239                Label::new("Sign in".to_string(), style.text.clone())
1240                    .contained()
1241                    .with_style(style.container)
1242                    .boxed()
1243            })
1244            .on_click(|cx| cx.dispatch_action(Authenticate))
1245            .with_cursor_style(CursorStyle::PointingHand)
1246            .aligned()
1247            .boxed()
1248        }
1249    }
1250
1251    fn render_avatar(
1252        &self,
1253        avatar: Arc<ImageData>,
1254        replica_id: ReplicaId,
1255        theme: &Theme,
1256    ) -> ElementBox {
1257        ConstrainedBox::new(
1258            Stack::new()
1259                .with_child(
1260                    ConstrainedBox::new(
1261                        Image::new(avatar)
1262                            .with_style(theme.workspace.titlebar.avatar)
1263                            .boxed(),
1264                    )
1265                    .with_width(theme.workspace.titlebar.avatar_width)
1266                    .aligned()
1267                    .boxed(),
1268                )
1269                .with_child(
1270                    AvatarRibbon::new(theme.editor.replica_selection_style(replica_id).cursor)
1271                        .constrained()
1272                        .with_width(theme.workspace.titlebar.avatar_ribbon.width)
1273                        .with_height(theme.workspace.titlebar.avatar_ribbon.height)
1274                        .aligned()
1275                        .bottom()
1276                        .boxed(),
1277                )
1278                .boxed(),
1279        )
1280        .with_width(theme.workspace.right_sidebar.width)
1281        .boxed()
1282    }
1283
1284    fn render_share_icon(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1285        if self.project().read(cx).is_local() && self.client.user_id().is_some() {
1286            enum Share {}
1287
1288            let color = if self.project().read(cx).is_shared() {
1289                theme.workspace.titlebar.share_icon_active_color
1290            } else {
1291                theme.workspace.titlebar.share_icon_color
1292            };
1293            Some(
1294                MouseEventHandler::new::<Share, _, _>(0, cx, |_, _| {
1295                    Align::new(
1296                        ConstrainedBox::new(
1297                            Svg::new("icons/broadcast-24.svg").with_color(color).boxed(),
1298                        )
1299                        .with_width(24.)
1300                        .boxed(),
1301                    )
1302                    .boxed()
1303                })
1304                .with_cursor_style(CursorStyle::PointingHand)
1305                .on_click(|cx| cx.dispatch_action(ToggleShare))
1306                .boxed(),
1307            )
1308        } else {
1309            None
1310        }
1311    }
1312
1313    fn render_disconnected_overlay(&self, cx: &AppContext) -> Option<ElementBox> {
1314        if self.project.read(cx).is_read_only() {
1315            let theme = &self.settings.borrow().theme;
1316            Some(
1317                EventHandler::new(
1318                    Label::new(
1319                        "Your connection to the remote project has been lost.".to_string(),
1320                        theme.workspace.disconnected_overlay.text.clone(),
1321                    )
1322                    .aligned()
1323                    .contained()
1324                    .with_style(theme.workspace.disconnected_overlay.container)
1325                    .boxed(),
1326                )
1327                .capture(|_, _, _| true)
1328                .boxed(),
1329            )
1330        } else {
1331            None
1332        }
1333    }
1334}
1335
1336impl Entity for Workspace {
1337    type Event = ();
1338}
1339
1340impl View for Workspace {
1341    fn ui_name() -> &'static str {
1342        "Workspace"
1343    }
1344
1345    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1346        let settings = self.settings.borrow();
1347        let theme = &settings.theme;
1348        Stack::new()
1349            .with_child(
1350                Flex::column()
1351                    .with_child(self.render_titlebar(&theme, cx))
1352                    .with_child(
1353                        Stack::new()
1354                            .with_child({
1355                                let mut content = Flex::row();
1356                                content.add_child(self.left_sidebar.render(&settings, cx));
1357                                if let Some(element) =
1358                                    self.left_sidebar.render_active_item(&settings, cx)
1359                                {
1360                                    content.add_child(Flexible::new(0.8, false, element).boxed());
1361                                }
1362                                content.add_child(
1363                                    Flex::column()
1364                                        .with_child(
1365                                            Flexible::new(
1366                                                1.,
1367                                                true,
1368                                                self.center.render(&settings.theme),
1369                                            )
1370                                            .boxed(),
1371                                        )
1372                                        .with_child(ChildView::new(&self.status_bar).boxed())
1373                                        .flexible(1., true)
1374                                        .boxed(),
1375                                );
1376                                if let Some(element) =
1377                                    self.right_sidebar.render_active_item(&settings, cx)
1378                                {
1379                                    content.add_child(Flexible::new(0.8, false, element).boxed());
1380                                }
1381                                content.add_child(self.right_sidebar.render(&settings, cx));
1382                                content.boxed()
1383                            })
1384                            .with_children(self.modal.as_ref().map(|m| ChildView::new(m).boxed()))
1385                            .flexible(1.0, true)
1386                            .boxed(),
1387                    )
1388                    .contained()
1389                    .with_background_color(settings.theme.workspace.background)
1390                    .boxed(),
1391            )
1392            .with_children(self.render_disconnected_overlay(cx))
1393            .named("workspace")
1394    }
1395
1396    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
1397        cx.focus(&self.active_pane);
1398    }
1399}
1400
1401pub trait WorkspaceHandle {
1402    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
1403}
1404
1405impl WorkspaceHandle for ViewHandle<Workspace> {
1406    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
1407        self.read(cx)
1408            .worktrees(cx)
1409            .flat_map(|worktree| {
1410                let worktree_id = worktree.read(cx).id();
1411                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
1412                    worktree_id,
1413                    path: f.path.clone(),
1414                })
1415            })
1416            .collect::<Vec<_>>()
1417    }
1418}
1419
1420pub struct AvatarRibbon {
1421    color: Color,
1422}
1423
1424impl AvatarRibbon {
1425    pub fn new(color: Color) -> AvatarRibbon {
1426        AvatarRibbon { color }
1427    }
1428}
1429
1430impl Element for AvatarRibbon {
1431    type LayoutState = ();
1432
1433    type PaintState = ();
1434
1435    fn layout(
1436        &mut self,
1437        constraint: gpui::SizeConstraint,
1438        _: &mut gpui::LayoutContext,
1439    ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
1440        (constraint.max, ())
1441    }
1442
1443    fn paint(
1444        &mut self,
1445        bounds: gpui::geometry::rect::RectF,
1446        _: gpui::geometry::rect::RectF,
1447        _: &mut Self::LayoutState,
1448        cx: &mut gpui::PaintContext,
1449    ) -> Self::PaintState {
1450        let mut path = PathBuilder::new();
1451        path.reset(bounds.lower_left());
1452        path.curve_to(
1453            bounds.origin() + vec2f(bounds.height(), 0.),
1454            bounds.origin(),
1455        );
1456        path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
1457        path.curve_to(bounds.lower_right(), bounds.upper_right());
1458        path.line_to(bounds.lower_left());
1459        cx.scene.push_path(path.build(self.color, None));
1460    }
1461
1462    fn dispatch_event(
1463        &mut self,
1464        _: &gpui::Event,
1465        _: gpui::geometry::rect::RectF,
1466        _: &mut Self::LayoutState,
1467        _: &mut Self::PaintState,
1468        _: &mut gpui::EventContext,
1469    ) -> bool {
1470        false
1471    }
1472
1473    fn debug(
1474        &self,
1475        bounds: gpui::geometry::rect::RectF,
1476        _: &Self::LayoutState,
1477        _: &Self::PaintState,
1478        _: &gpui::DebugContext,
1479    ) -> gpui::json::Value {
1480        json::json!({
1481            "type": "AvatarRibbon",
1482            "bounds": bounds.to_json(),
1483            "color": self.color.to_json(),
1484        })
1485    }
1486}
1487
1488impl std::fmt::Debug for OpenParams {
1489    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1490        f.debug_struct("OpenParams")
1491            .field("paths", &self.paths)
1492            .finish()
1493    }
1494}
1495
1496fn open(action: &Open, cx: &mut MutableAppContext) {
1497    let app_state = action.0.clone();
1498    let mut paths = cx.prompt_for_paths(PathPromptOptions {
1499        files: true,
1500        directories: true,
1501        multiple: true,
1502    });
1503    cx.spawn(|mut cx| async move {
1504        if let Some(paths) = paths.recv().await.flatten() {
1505            cx.update(|cx| cx.dispatch_global_action(OpenPaths(OpenParams { paths, app_state })));
1506        }
1507    })
1508    .detach();
1509}
1510
1511pub fn open_paths(
1512    abs_paths: &[PathBuf],
1513    app_state: &Arc<AppState>,
1514    cx: &mut MutableAppContext,
1515) -> Task<ViewHandle<Workspace>> {
1516    log::info!("open paths {:?}", abs_paths);
1517
1518    // Open paths in existing workspace if possible
1519    let mut existing = None;
1520    for window_id in cx.window_ids().collect::<Vec<_>>() {
1521        if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
1522            if workspace_handle.update(cx, |workspace, cx| {
1523                if workspace.contains_paths(abs_paths, cx.as_ref()) {
1524                    cx.activate_window(window_id);
1525                    existing = Some(workspace_handle.clone());
1526                    true
1527                } else {
1528                    false
1529                }
1530            }) {
1531                break;
1532            }
1533        }
1534    }
1535
1536    let workspace = existing.unwrap_or_else(|| {
1537        cx.add_window((app_state.build_window_options)(), |cx| {
1538            let project = Project::local(
1539                app_state.client.clone(),
1540                app_state.user_store.clone(),
1541                app_state.languages.clone(),
1542                app_state.fs.clone(),
1543                cx,
1544            );
1545            (app_state.build_workspace)(project, &app_state, cx)
1546        })
1547        .1
1548    });
1549
1550    let task = workspace.update(cx, |workspace, cx| workspace.open_paths(abs_paths, cx));
1551    cx.spawn(|_| async move {
1552        task.await;
1553        workspace
1554    })
1555}
1556
1557pub fn join_project(
1558    project_id: u64,
1559    app_state: &Arc<AppState>,
1560    cx: &mut MutableAppContext,
1561) -> Task<Result<ViewHandle<Workspace>>> {
1562    for window_id in cx.window_ids().collect::<Vec<_>>() {
1563        if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
1564            if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
1565                return Task::ready(Ok(workspace));
1566            }
1567        }
1568    }
1569
1570    let app_state = app_state.clone();
1571    cx.spawn(|mut cx| async move {
1572        let project = Project::remote(
1573            project_id,
1574            app_state.client.clone(),
1575            app_state.user_store.clone(),
1576            app_state.languages.clone(),
1577            app_state.fs.clone(),
1578            &mut cx,
1579        )
1580        .await?;
1581        let (_, workspace) = cx.update(|cx| {
1582            cx.add_window((app_state.build_window_options)(), |cx| {
1583                (app_state.build_workspace)(project, &app_state, cx)
1584            })
1585        });
1586        Ok(workspace)
1587    })
1588}
1589
1590fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
1591    let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
1592        let project = Project::local(
1593            app_state.client.clone(),
1594            app_state.user_store.clone(),
1595            app_state.languages.clone(),
1596            app_state.fs.clone(),
1597            cx,
1598        );
1599        (app_state.build_workspace)(project, &app_state, cx)
1600    });
1601    cx.dispatch_action(window_id, vec![workspace.id()], &OpenNew(app_state.clone()));
1602}