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