workspace.rs

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