workspace.rs

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