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