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