workspace.rs

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