workspace.rs

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