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