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