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