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 pub fn activate_next_pane(&mut self, cx: &mut ViewContext<Self>) {
983 let ix = self
984 .panes
985 .iter()
986 .position(|pane| pane == &self.active_pane)
987 .unwrap();
988 let next_ix = (ix + 1) % self.panes.len();
989 self.activate_pane(self.panes[next_ix].clone(), cx);
990 }
991
992 fn activate_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
993 self.active_pane = pane;
994 self.status_bar.update(cx, |status_bar, cx| {
995 status_bar.set_active_pane(&self.active_pane, cx);
996 });
997 cx.focus(&self.active_pane);
998 cx.notify();
999 }
1000
1001 fn handle_pane_event(
1002 &mut self,
1003 pane_id: usize,
1004 event: &pane::Event,
1005 cx: &mut ViewContext<Self>,
1006 ) {
1007 if let Some(pane) = self.pane(pane_id) {
1008 match event {
1009 pane::Event::Split(direction) => {
1010 self.split_pane(pane, *direction, cx);
1011 }
1012 pane::Event::Remove => {
1013 self.remove_pane(pane, cx);
1014 }
1015 pane::Event::Activate => {
1016 self.activate_pane(pane, cx);
1017 }
1018 }
1019 } else {
1020 error!("pane {} not found", pane_id);
1021 }
1022 }
1023
1024 pub fn split_pane(
1025 &mut self,
1026 pane: ViewHandle<Pane>,
1027 direction: SplitDirection,
1028 cx: &mut ViewContext<Self>,
1029 ) -> ViewHandle<Pane> {
1030 let new_pane = self.add_pane(cx);
1031 self.activate_pane(new_pane.clone(), cx);
1032 if let Some(item) = pane.read(cx).active_item() {
1033 if let Some(clone) = item.clone_on_split(cx.as_mut()) {
1034 new_pane.update(cx, |new_pane, cx| new_pane.add_item_view(clone, cx));
1035 }
1036 }
1037 self.center
1038 .split(pane.id(), new_pane.id(), direction)
1039 .unwrap();
1040 cx.notify();
1041 new_pane
1042 }
1043
1044 fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1045 if self.center.remove(pane.id()).unwrap() {
1046 self.panes.retain(|p| p != &pane);
1047 self.activate_pane(self.panes.last().unwrap().clone(), cx);
1048 }
1049 }
1050
1051 pub fn panes(&self) -> &[ViewHandle<Pane>] {
1052 &self.panes
1053 }
1054
1055 fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1056 self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1057 }
1058
1059 pub fn active_pane(&self) -> &ViewHandle<Pane> {
1060 &self.active_pane
1061 }
1062
1063 fn toggle_share(&mut self, _: &ToggleShare, cx: &mut ViewContext<Self>) {
1064 self.project.update(cx, |project, cx| {
1065 if project.is_local() {
1066 if project.is_shared() {
1067 project.unshare(cx).detach();
1068 } else {
1069 project.share(cx).detach();
1070 }
1071 }
1072 });
1073 }
1074
1075 fn render_connection_status(&self) -> Option<ElementBox> {
1076 let theme = &self.settings.borrow().theme;
1077 match &*self.client.status().borrow() {
1078 client::Status::ConnectionError
1079 | client::Status::ConnectionLost
1080 | client::Status::Reauthenticating
1081 | client::Status::Reconnecting { .. }
1082 | client::Status::ReconnectionError { .. } => Some(
1083 Container::new(
1084 Align::new(
1085 ConstrainedBox::new(
1086 Svg::new("icons/offline-14.svg")
1087 .with_color(theme.workspace.titlebar.offline_icon.color)
1088 .boxed(),
1089 )
1090 .with_width(theme.workspace.titlebar.offline_icon.width)
1091 .boxed(),
1092 )
1093 .boxed(),
1094 )
1095 .with_style(theme.workspace.titlebar.offline_icon.container)
1096 .boxed(),
1097 ),
1098 client::Status::UpgradeRequired => Some(
1099 Label::new(
1100 "Please update Zed to collaborate".to_string(),
1101 theme.workspace.titlebar.outdated_warning.text.clone(),
1102 )
1103 .contained()
1104 .with_style(theme.workspace.titlebar.outdated_warning.container)
1105 .aligned()
1106 .boxed(),
1107 ),
1108 _ => None,
1109 }
1110 }
1111
1112 fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1113 ConstrainedBox::new(
1114 Container::new(
1115 Stack::new()
1116 .with_child(
1117 Align::new(
1118 Label::new("zed".into(), theme.workspace.titlebar.title.clone())
1119 .boxed(),
1120 )
1121 .boxed(),
1122 )
1123 .with_child(
1124 Align::new(
1125 Flex::row()
1126 .with_children(self.render_share_icon(theme, cx))
1127 .with_children(self.render_collaborators(theme, cx))
1128 .with_child(self.render_avatar(
1129 self.user_store.read(cx).current_user().as_ref(),
1130 self.project.read(cx).replica_id(),
1131 theme,
1132 cx,
1133 ))
1134 .with_children(self.render_connection_status())
1135 .boxed(),
1136 )
1137 .right()
1138 .boxed(),
1139 )
1140 .boxed(),
1141 )
1142 .with_style(theme.workspace.titlebar.container)
1143 .boxed(),
1144 )
1145 .with_height(theme.workspace.titlebar.height)
1146 .named("titlebar")
1147 }
1148
1149 fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1150 let mut collaborators = self
1151 .project
1152 .read(cx)
1153 .collaborators()
1154 .values()
1155 .cloned()
1156 .collect::<Vec<_>>();
1157 collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1158 collaborators
1159 .into_iter()
1160 .map(|collaborator| {
1161 self.render_avatar(Some(&collaborator.user), collaborator.replica_id, theme, cx)
1162 })
1163 .collect()
1164 }
1165
1166 fn render_avatar(
1167 &self,
1168 user: Option<&Arc<User>>,
1169 replica_id: ReplicaId,
1170 theme: &Theme,
1171 cx: &mut RenderContext<Self>,
1172 ) -> ElementBox {
1173 if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1174 ConstrainedBox::new(
1175 Stack::new()
1176 .with_child(
1177 ConstrainedBox::new(
1178 Image::new(avatar)
1179 .with_style(theme.workspace.titlebar.avatar)
1180 .boxed(),
1181 )
1182 .with_width(theme.workspace.titlebar.avatar_width)
1183 .aligned()
1184 .boxed(),
1185 )
1186 .with_child(
1187 AvatarRibbon::new(theme.editor.replica_selection_style(replica_id).cursor)
1188 .constrained()
1189 .with_width(theme.workspace.titlebar.avatar_ribbon.width)
1190 .with_height(theme.workspace.titlebar.avatar_ribbon.height)
1191 .aligned()
1192 .bottom()
1193 .boxed(),
1194 )
1195 .boxed(),
1196 )
1197 .with_width(theme.workspace.right_sidebar.width)
1198 .boxed()
1199 } else {
1200 MouseEventHandler::new::<Authenticate, _, _, _>(0, cx, |state, _| {
1201 let style = if state.hovered {
1202 &theme.workspace.titlebar.hovered_sign_in_prompt
1203 } else {
1204 &theme.workspace.titlebar.sign_in_prompt
1205 };
1206 Label::new("Sign in".to_string(), style.text.clone())
1207 .contained()
1208 .with_style(style.container)
1209 .boxed()
1210 })
1211 .on_click(|cx| cx.dispatch_action(Authenticate))
1212 .with_cursor_style(CursorStyle::PointingHand)
1213 .aligned()
1214 .boxed()
1215 }
1216 }
1217
1218 fn render_share_icon(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1219 if self.project().read(cx).is_local() && self.client.user_id().is_some() {
1220 enum Share {}
1221
1222 let color = if self.project().read(cx).is_shared() {
1223 theme.workspace.titlebar.share_icon_active_color
1224 } else {
1225 theme.workspace.titlebar.share_icon_color
1226 };
1227 Some(
1228 MouseEventHandler::new::<Share, _, _, _>(0, cx, |_, _| {
1229 Align::new(
1230 ConstrainedBox::new(
1231 Svg::new("icons/broadcast-24.svg").with_color(color).boxed(),
1232 )
1233 .with_width(24.)
1234 .boxed(),
1235 )
1236 .boxed()
1237 })
1238 .with_cursor_style(CursorStyle::PointingHand)
1239 .on_click(|cx| cx.dispatch_action(ToggleShare))
1240 .boxed(),
1241 )
1242 } else {
1243 None
1244 }
1245 }
1246}
1247
1248impl Entity for Workspace {
1249 type Event = ();
1250}
1251
1252impl View for Workspace {
1253 fn ui_name() -> &'static str {
1254 "Workspace"
1255 }
1256
1257 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1258 let settings = self.settings.borrow();
1259 let theme = &settings.theme;
1260 Flex::column()
1261 .with_child(self.render_titlebar(&theme, cx))
1262 .with_child(
1263 Stack::new()
1264 .with_child({
1265 let mut content = Flex::row();
1266 content.add_child(self.left_sidebar.render(&settings, cx));
1267 if let Some(element) = self.left_sidebar.render_active_item(&settings, cx) {
1268 content.add_child(Flexible::new(0.8, false, element).boxed());
1269 }
1270 content.add_child(
1271 Flex::column()
1272 .with_child(
1273 Flexible::new(1., true, self.center.render(&settings.theme))
1274 .boxed(),
1275 )
1276 .with_child(ChildView::new(self.status_bar.id()).boxed())
1277 .flexible(1., true)
1278 .boxed(),
1279 );
1280 if let Some(element) = self.right_sidebar.render_active_item(&settings, cx)
1281 {
1282 content.add_child(Flexible::new(0.8, false, element).boxed());
1283 }
1284 content.add_child(self.right_sidebar.render(&settings, cx));
1285 content.boxed()
1286 })
1287 .with_children(self.modal.as_ref().map(|m| ChildView::new(m.id()).boxed()))
1288 .flexible(1.0, true)
1289 .boxed(),
1290 )
1291 .contained()
1292 .with_background_color(settings.theme.workspace.background)
1293 .named("workspace")
1294 }
1295
1296 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
1297 cx.focus(&self.active_pane);
1298 }
1299}
1300
1301pub trait WorkspaceHandle {
1302 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
1303}
1304
1305impl WorkspaceHandle for ViewHandle<Workspace> {
1306 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
1307 self.read(cx)
1308 .worktrees(cx)
1309 .iter()
1310 .flat_map(|worktree| {
1311 let worktree_id = worktree.read(cx).id();
1312 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
1313 worktree_id,
1314 path: f.path.clone(),
1315 })
1316 })
1317 .collect::<Vec<_>>()
1318 }
1319}
1320
1321pub struct AvatarRibbon {
1322 color: Color,
1323}
1324
1325impl AvatarRibbon {
1326 pub fn new(color: Color) -> AvatarRibbon {
1327 AvatarRibbon { color }
1328 }
1329}
1330
1331impl Element for AvatarRibbon {
1332 type LayoutState = ();
1333
1334 type PaintState = ();
1335
1336 fn layout(
1337 &mut self,
1338 constraint: gpui::SizeConstraint,
1339 _: &mut gpui::LayoutContext,
1340 ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
1341 (constraint.max, ())
1342 }
1343
1344 fn paint(
1345 &mut self,
1346 bounds: gpui::geometry::rect::RectF,
1347 _: gpui::geometry::rect::RectF,
1348 _: &mut Self::LayoutState,
1349 cx: &mut gpui::PaintContext,
1350 ) -> Self::PaintState {
1351 let mut path = PathBuilder::new();
1352 path.reset(bounds.lower_left());
1353 path.curve_to(
1354 bounds.origin() + vec2f(bounds.height(), 0.),
1355 bounds.origin(),
1356 );
1357 path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
1358 path.curve_to(bounds.lower_right(), bounds.upper_right());
1359 path.line_to(bounds.lower_left());
1360 cx.scene.push_path(path.build(self.color, None));
1361 }
1362
1363 fn dispatch_event(
1364 &mut self,
1365 _: &gpui::Event,
1366 _: gpui::geometry::rect::RectF,
1367 _: &mut Self::LayoutState,
1368 _: &mut Self::PaintState,
1369 _: &mut gpui::EventContext,
1370 ) -> bool {
1371 false
1372 }
1373
1374 fn debug(
1375 &self,
1376 bounds: gpui::geometry::rect::RectF,
1377 _: &Self::LayoutState,
1378 _: &Self::PaintState,
1379 _: &gpui::DebugContext,
1380 ) -> gpui::json::Value {
1381 json::json!({
1382 "type": "AvatarRibbon",
1383 "bounds": bounds.to_json(),
1384 "color": self.color.to_json(),
1385 })
1386 }
1387}
1388
1389impl std::fmt::Debug for OpenParams {
1390 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1391 f.debug_struct("OpenParams")
1392 .field("paths", &self.paths)
1393 .finish()
1394 }
1395}
1396
1397fn open(action: &Open, cx: &mut MutableAppContext) {
1398 let app_state = action.0.clone();
1399 cx.prompt_for_paths(
1400 PathPromptOptions {
1401 files: true,
1402 directories: true,
1403 multiple: true,
1404 },
1405 move |paths, cx| {
1406 if let Some(paths) = paths {
1407 cx.dispatch_global_action(OpenPaths(OpenParams { paths, app_state }));
1408 }
1409 },
1410 );
1411}
1412
1413pub fn open_paths(
1414 abs_paths: &[PathBuf],
1415 app_state: &Arc<AppState>,
1416 cx: &mut MutableAppContext,
1417) -> Task<ViewHandle<Workspace>> {
1418 log::info!("open paths {:?}", abs_paths);
1419
1420 // Open paths in existing workspace if possible
1421 let mut existing = None;
1422 for window_id in cx.window_ids().collect::<Vec<_>>() {
1423 if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
1424 if workspace.update(cx, |view, cx| {
1425 if view.contains_paths(abs_paths, cx.as_ref()) {
1426 existing = Some(workspace.clone());
1427 true
1428 } else {
1429 false
1430 }
1431 }) {
1432 break;
1433 }
1434 }
1435 }
1436
1437 let workspace = existing.unwrap_or_else(|| {
1438 cx.add_window((app_state.build_window_options)(), |cx| {
1439 let project = Project::local(
1440 app_state.client.clone(),
1441 app_state.user_store.clone(),
1442 app_state.languages.clone(),
1443 app_state.fs.clone(),
1444 cx,
1445 );
1446 (app_state.build_workspace)(project, &app_state, cx)
1447 })
1448 .1
1449 });
1450
1451 let task = workspace.update(cx, |workspace, cx| workspace.open_paths(abs_paths, cx));
1452 cx.spawn(|_| async move {
1453 task.await;
1454 workspace
1455 })
1456}
1457
1458pub fn join_project(
1459 project_id: u64,
1460 app_state: &Arc<AppState>,
1461 cx: &mut MutableAppContext,
1462) -> Task<Result<ViewHandle<Workspace>>> {
1463 for window_id in cx.window_ids().collect::<Vec<_>>() {
1464 if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
1465 if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
1466 return Task::ready(Ok(workspace));
1467 }
1468 }
1469 }
1470
1471 let app_state = app_state.clone();
1472 cx.spawn(|mut cx| async move {
1473 let project = Project::remote(
1474 project_id,
1475 app_state.client.clone(),
1476 app_state.user_store.clone(),
1477 app_state.languages.clone(),
1478 app_state.fs.clone(),
1479 &mut cx,
1480 )
1481 .await?;
1482 let (_, workspace) = cx.update(|cx| {
1483 cx.add_window((app_state.build_window_options)(), |cx| {
1484 (app_state.build_workspace)(project, &app_state, cx)
1485 })
1486 });
1487 Ok(workspace)
1488 })
1489}
1490
1491fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
1492 let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
1493 let project = Project::local(
1494 app_state.client.clone(),
1495 app_state.user_store.clone(),
1496 app_state.languages.clone(),
1497 app_state.fs.clone(),
1498 cx,
1499 );
1500 (app_state.build_workspace)(project, &app_state, cx)
1501 });
1502 cx.dispatch_action(window_id, vec![workspace.id()], &OpenNew(app_state.clone()));
1503}