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