1pub mod menu;
2pub mod pane;
3pub mod pane_group;
4pub mod settings;
5pub mod sidebar;
6mod status_bar;
7
8use anyhow::{anyhow, Result};
9use client::{Authenticate, ChannelList, Client, User, UserStore};
10use clock::ReplicaId;
11use collections::HashSet;
12use gpui::{
13 action,
14 color::Color,
15 elements::*,
16 geometry::{vector::vec2f, PathBuilder},
17 json::{self, to_string_pretty, ToJson},
18 keymap::Binding,
19 platform::{CursorStyle, WindowOptions},
20 AnyModelHandle, AnyViewHandle, AppContext, ClipboardItem, Entity, ModelContext, ModelHandle,
21 MutableAppContext, PathPromptOptions, PromptLevel, RenderContext, Task, View, ViewContext,
22 ViewHandle, WeakModelHandle, WeakViewHandle,
23};
24use language::LanguageRegistry;
25use log::error;
26pub use pane::*;
27pub use pane_group::*;
28use parking_lot::Mutex;
29use postage::{prelude::Stream, watch};
30use project::{fs, Fs, Project, ProjectEntry, ProjectPath, Worktree};
31pub use settings::Settings;
32use sidebar::{Side, Sidebar, SidebarItemId, ToggleSidebarItem, ToggleSidebarItemFocus};
33use status_bar::StatusBar;
34pub use status_bar::StatusItemView;
35use std::{
36 any::Any,
37 future::Future,
38 hash::{Hash, Hasher},
39 path::{Path, PathBuf},
40 rc::Rc,
41 sync::Arc,
42};
43use theme::{Theme, ThemeRegistry};
44
45action!(Open, Arc<AppState>);
46action!(OpenNew, Arc<AppState>);
47action!(OpenPaths, OpenParams);
48action!(ToggleShare);
49action!(JoinProject, JoinProjectParams);
50action!(Save);
51action!(DebugElements);
52
53pub fn init(cx: &mut MutableAppContext) {
54 pane::init(cx);
55 menu::init(cx);
56
57 cx.add_global_action(open);
58 cx.add_global_action(move |action: &OpenPaths, cx: &mut MutableAppContext| {
59 open_paths(&action.0.paths, &action.0.app_state, cx).detach();
60 });
61 cx.add_global_action(move |action: &OpenNew, cx: &mut MutableAppContext| {
62 open_new(&action.0, cx)
63 });
64 cx.add_global_action(move |action: &JoinProject, cx: &mut MutableAppContext| {
65 join_project(action.0.project_id, &action.0.app_state, cx).detach();
66 });
67
68 cx.add_action(Workspace::toggle_share);
69 cx.add_action(Workspace::save_active_item);
70 cx.add_action(Workspace::debug_elements);
71 cx.add_action(Workspace::toggle_sidebar_item);
72 cx.add_action(Workspace::toggle_sidebar_item_focus);
73 cx.add_bindings(vec![
74 Binding::new("cmd-s", Save, None),
75 Binding::new("cmd-alt-i", DebugElements, None),
76 Binding::new(
77 "cmd-shift-!",
78 ToggleSidebarItem(SidebarItemId {
79 side: Side::Left,
80 item_index: 0,
81 }),
82 None,
83 ),
84 Binding::new(
85 "cmd-1",
86 ToggleSidebarItemFocus(SidebarItemId {
87 side: Side::Left,
88 item_index: 0,
89 }),
90 None,
91 ),
92 ]);
93}
94
95pub struct AppState {
96 pub settings_tx: Arc<Mutex<watch::Sender<Settings>>>,
97 pub settings: watch::Receiver<Settings>,
98 pub languages: Arc<LanguageRegistry>,
99 pub themes: Arc<ThemeRegistry>,
100 pub client: Arc<client::Client>,
101 pub user_store: ModelHandle<client::UserStore>,
102 pub fs: Arc<dyn fs::Fs>,
103 pub channel_list: ModelHandle<client::ChannelList>,
104 pub path_openers: Arc<[Box<dyn PathOpener>]>,
105 pub build_window_options: &'static dyn Fn() -> WindowOptions<'static>,
106 pub build_workspace: &'static dyn Fn(
107 ModelHandle<Project>,
108 &Arc<AppState>,
109 &mut ViewContext<Workspace>,
110 ) -> Workspace,
111}
112
113#[derive(Clone)]
114pub struct OpenParams {
115 pub paths: Vec<PathBuf>,
116 pub app_state: Arc<AppState>,
117}
118
119#[derive(Clone)]
120pub struct JoinProjectParams {
121 pub project_id: u64,
122 pub app_state: Arc<AppState>,
123}
124
125pub trait PathOpener {
126 fn open(
127 &self,
128 project: &mut Project,
129 path: ProjectPath,
130 cx: &mut ModelContext<Project>,
131 ) -> Option<Task<Result<Box<dyn ItemHandle>>>>;
132}
133
134pub trait Item: Entity + Sized {
135 type View: ItemView;
136
137 fn build_view(
138 handle: ModelHandle<Self>,
139 workspace: &Workspace,
140 nav_history: Rc<NavHistory>,
141 cx: &mut ViewContext<Self::View>,
142 ) -> Self::View;
143 fn project_entry(&self) -> Option<ProjectEntry>;
144}
145
146pub trait ItemView: View {
147 type ItemHandle: ItemHandle;
148
149 fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
150 fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) {}
151 fn item_handle(&self, cx: &AppContext) -> Self::ItemHandle;
152 fn title(&self, cx: &AppContext) -> String;
153 fn project_entry(&self, cx: &AppContext) -> Option<ProjectEntry>;
154 fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
155 where
156 Self: Sized,
157 {
158 None
159 }
160 fn is_dirty(&self, _: &AppContext) -> bool {
161 false
162 }
163 fn has_conflict(&self, _: &AppContext) -> bool {
164 false
165 }
166 fn can_save(&self, cx: &AppContext) -> bool;
167 fn save(&mut self, cx: &mut ViewContext<Self>) -> Result<Task<Result<()>>>;
168 fn can_save_as(&self, cx: &AppContext) -> bool;
169 fn save_as(
170 &mut self,
171 project: ModelHandle<Project>,
172 abs_path: PathBuf,
173 cx: &mut ViewContext<Self>,
174 ) -> Task<anyhow::Result<()>>;
175 fn should_activate_item_on_event(_: &Self::Event) -> bool {
176 false
177 }
178 fn should_close_item_on_event(_: &Self::Event) -> bool {
179 false
180 }
181 fn should_update_tab_on_event(_: &Self::Event) -> bool {
182 false
183 }
184}
185
186pub trait ItemHandle: Send + Sync {
187 fn id(&self) -> usize;
188 fn add_view(
189 &self,
190 window_id: usize,
191 workspace: &Workspace,
192 nav_history: Rc<NavHistory>,
193 cx: &mut MutableAppContext,
194 ) -> Box<dyn ItemViewHandle>;
195 fn boxed_clone(&self) -> Box<dyn ItemHandle>;
196 fn downgrade(&self) -> Box<dyn WeakItemHandle>;
197 fn to_any(&self) -> AnyModelHandle;
198 fn project_entry(&self, cx: &AppContext) -> Option<ProjectEntry>;
199}
200
201pub trait WeakItemHandle {
202 fn id(&self) -> usize;
203 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>>;
204}
205
206pub trait ItemViewHandle {
207 fn item_handle(&self, cx: &AppContext) -> Box<dyn ItemHandle>;
208 fn title(&self, cx: &AppContext) -> String;
209 fn project_entry(&self, cx: &AppContext) -> Option<ProjectEntry>;
210 fn boxed_clone(&self) -> Box<dyn ItemViewHandle>;
211 fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemViewHandle>>;
212 fn added_to_pane(&mut self, cx: &mut ViewContext<Pane>);
213 fn deactivated(&self, cx: &mut MutableAppContext);
214 fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext);
215 fn id(&self) -> usize;
216 fn to_any(&self) -> AnyViewHandle;
217 fn is_dirty(&self, cx: &AppContext) -> bool;
218 fn has_conflict(&self, cx: &AppContext) -> bool;
219 fn can_save(&self, cx: &AppContext) -> bool;
220 fn can_save_as(&self, cx: &AppContext) -> bool;
221 fn save(&self, cx: &mut MutableAppContext) -> Result<Task<Result<()>>>;
222 fn save_as(
223 &self,
224 project: ModelHandle<Project>,
225 abs_path: PathBuf,
226 cx: &mut MutableAppContext,
227 ) -> Task<anyhow::Result<()>>;
228}
229
230pub trait WeakItemViewHandle {
231 fn id(&self) -> usize;
232 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemViewHandle>>;
233}
234
235impl<T: Item> ItemHandle for ModelHandle<T> {
236 fn id(&self) -> usize {
237 self.id()
238 }
239
240 fn add_view(
241 &self,
242 window_id: usize,
243 workspace: &Workspace,
244 nav_history: Rc<NavHistory>,
245 cx: &mut MutableAppContext,
246 ) -> Box<dyn ItemViewHandle> {
247 Box::new(cx.add_view(window_id, |cx| {
248 T::build_view(self.clone(), workspace, nav_history, cx)
249 }))
250 }
251
252 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
253 Box::new(self.clone())
254 }
255
256 fn downgrade(&self) -> Box<dyn WeakItemHandle> {
257 Box::new(self.downgrade())
258 }
259
260 fn to_any(&self) -> AnyModelHandle {
261 self.clone().into()
262 }
263
264 fn project_entry(&self, cx: &AppContext) -> Option<ProjectEntry> {
265 self.read(cx).project_entry()
266 }
267}
268
269impl ItemHandle for Box<dyn ItemHandle> {
270 fn id(&self) -> usize {
271 ItemHandle::id(self.as_ref())
272 }
273
274 fn add_view(
275 &self,
276 window_id: usize,
277 workspace: &Workspace,
278 nav_history: Rc<NavHistory>,
279 cx: &mut MutableAppContext,
280 ) -> Box<dyn ItemViewHandle> {
281 ItemHandle::add_view(self.as_ref(), window_id, workspace, nav_history, cx)
282 }
283
284 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
285 self.as_ref().boxed_clone()
286 }
287
288 fn downgrade(&self) -> Box<dyn WeakItemHandle> {
289 self.as_ref().downgrade()
290 }
291
292 fn to_any(&self) -> AnyModelHandle {
293 self.as_ref().to_any()
294 }
295
296 fn project_entry(&self, cx: &AppContext) -> Option<ProjectEntry> {
297 self.as_ref().project_entry(cx)
298 }
299}
300
301impl<T: Item> WeakItemHandle for WeakModelHandle<T> {
302 fn id(&self) -> usize {
303 WeakModelHandle::id(self)
304 }
305
306 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
307 WeakModelHandle::<T>::upgrade(*self, cx).map(|i| Box::new(i) as Box<dyn ItemHandle>)
308 }
309}
310
311impl Hash for Box<dyn WeakItemHandle> {
312 fn hash<H: Hasher>(&self, state: &mut H) {
313 self.id().hash(state);
314 }
315}
316
317impl PartialEq for Box<dyn WeakItemHandle> {
318 fn eq(&self, other: &Self) -> bool {
319 self.id() == other.id()
320 }
321}
322
323impl Eq for Box<dyn WeakItemHandle> {}
324
325impl<T: ItemView> ItemViewHandle for ViewHandle<T> {
326 fn item_handle(&self, cx: &AppContext) -> Box<dyn ItemHandle> {
327 Box::new(self.read(cx).item_handle(cx))
328 }
329
330 fn title(&self, cx: &AppContext) -> String {
331 self.read(cx).title(cx)
332 }
333
334 fn project_entry(&self, cx: &AppContext) -> Option<ProjectEntry> {
335 self.read(cx).project_entry(cx)
336 }
337
338 fn boxed_clone(&self) -> Box<dyn ItemViewHandle> {
339 Box::new(self.clone())
340 }
341
342 fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemViewHandle>> {
343 self.update(cx, |item, cx| {
344 cx.add_option_view(|cx| item.clone_on_split(cx))
345 })
346 .map(|handle| Box::new(handle) as Box<dyn ItemViewHandle>)
347 }
348
349 fn added_to_pane(&mut self, cx: &mut ViewContext<Pane>) {
350 cx.subscribe(self, |pane, item, event, cx| {
351 if T::should_close_item_on_event(event) {
352 pane.close_item(item.id(), cx);
353 return;
354 }
355 if T::should_activate_item_on_event(event) {
356 if let Some(ix) = pane.index_for_item_view(&item) {
357 pane.activate_item(ix, cx);
358 pane.activate(cx);
359 }
360 }
361 if T::should_update_tab_on_event(event) {
362 cx.notify()
363 }
364 })
365 .detach();
366 }
367
368 fn deactivated(&self, cx: &mut MutableAppContext) {
369 self.update(cx, |this, cx| this.deactivated(cx));
370 }
371
372 fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) {
373 self.update(cx, |this, cx| this.navigate(data, cx));
374 }
375
376 fn save(&self, cx: &mut MutableAppContext) -> Result<Task<Result<()>>> {
377 self.update(cx, |item, cx| item.save(cx))
378 }
379
380 fn save_as(
381 &self,
382 project: ModelHandle<Project>,
383 abs_path: PathBuf,
384 cx: &mut MutableAppContext,
385 ) -> Task<anyhow::Result<()>> {
386 self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
387 }
388
389 fn is_dirty(&self, cx: &AppContext) -> bool {
390 self.read(cx).is_dirty(cx)
391 }
392
393 fn has_conflict(&self, cx: &AppContext) -> bool {
394 self.read(cx).has_conflict(cx)
395 }
396
397 fn id(&self) -> usize {
398 self.id()
399 }
400
401 fn to_any(&self) -> AnyViewHandle {
402 self.into()
403 }
404
405 fn can_save(&self, cx: &AppContext) -> bool {
406 self.read(cx).can_save(cx)
407 }
408
409 fn can_save_as(&self, cx: &AppContext) -> bool {
410 self.read(cx).can_save_as(cx)
411 }
412}
413
414impl Clone for Box<dyn ItemViewHandle> {
415 fn clone(&self) -> Box<dyn ItemViewHandle> {
416 self.boxed_clone()
417 }
418}
419
420impl Clone for Box<dyn ItemHandle> {
421 fn clone(&self) -> Box<dyn ItemHandle> {
422 self.boxed_clone()
423 }
424}
425
426impl<T: ItemView> WeakItemViewHandle for WeakViewHandle<T> {
427 fn id(&self) -> usize {
428 self.id()
429 }
430
431 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemViewHandle>> {
432 self.upgrade(cx)
433 .map(|v| Box::new(v) as Box<dyn ItemViewHandle>)
434 }
435}
436
437#[derive(Clone)]
438pub struct WorkspaceParams {
439 pub project: ModelHandle<Project>,
440 pub client: Arc<Client>,
441 pub fs: Arc<dyn Fs>,
442 pub languages: Arc<LanguageRegistry>,
443 pub settings: watch::Receiver<Settings>,
444 pub user_store: ModelHandle<UserStore>,
445 pub channel_list: ModelHandle<ChannelList>,
446 pub path_openers: Arc<[Box<dyn PathOpener>]>,
447}
448
449impl WorkspaceParams {
450 #[cfg(any(test, feature = "test-support"))]
451 pub fn test(cx: &mut MutableAppContext) -> Self {
452 let fs = Arc::new(project::FakeFs::new());
453 let languages = Arc::new(LanguageRegistry::new());
454 let http_client = client::test::FakeHttpClient::new(|_| async move {
455 Ok(client::http::ServerResponse::new(404))
456 });
457 let client = Client::new(http_client.clone());
458 let theme =
459 gpui::fonts::with_font_cache(cx.font_cache().clone(), || theme::Theme::default());
460 let settings = Settings::new("Courier", cx.font_cache(), Arc::new(theme)).unwrap();
461 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
462 let project = Project::local(
463 client.clone(),
464 user_store.clone(),
465 languages.clone(),
466 fs.clone(),
467 cx,
468 );
469 Self {
470 project,
471 channel_list: cx
472 .add_model(|cx| ChannelList::new(user_store.clone(), client.clone(), cx)),
473 client,
474 fs,
475 languages,
476 settings: watch::channel_with(settings).1,
477 user_store,
478 path_openers: Arc::from([]),
479 }
480 }
481
482 #[cfg(any(test, feature = "test-support"))]
483 pub fn local(app_state: &Arc<AppState>, cx: &mut MutableAppContext) -> Self {
484 Self {
485 project: Project::local(
486 app_state.client.clone(),
487 app_state.user_store.clone(),
488 app_state.languages.clone(),
489 app_state.fs.clone(),
490 cx,
491 ),
492 client: app_state.client.clone(),
493 fs: app_state.fs.clone(),
494 languages: app_state.languages.clone(),
495 settings: app_state.settings.clone(),
496 user_store: app_state.user_store.clone(),
497 channel_list: app_state.channel_list.clone(),
498 path_openers: app_state.path_openers.clone(),
499 }
500 }
501}
502
503pub struct Workspace {
504 pub settings: watch::Receiver<Settings>,
505 weak_self: WeakViewHandle<Self>,
506 client: Arc<Client>,
507 user_store: ModelHandle<client::UserStore>,
508 fs: Arc<dyn Fs>,
509 modal: Option<AnyViewHandle>,
510 center: PaneGroup,
511 left_sidebar: Sidebar,
512 right_sidebar: Sidebar,
513 panes: Vec<ViewHandle<Pane>>,
514 active_pane: ViewHandle<Pane>,
515 status_bar: ViewHandle<StatusBar>,
516 project: ModelHandle<Project>,
517 path_openers: Arc<[Box<dyn PathOpener>]>,
518 items: HashSet<Box<dyn WeakItemHandle>>,
519 _observe_current_user: Task<()>,
520}
521
522impl Workspace {
523 pub fn new(params: &WorkspaceParams, cx: &mut ViewContext<Self>) -> Self {
524 cx.observe(¶ms.project, |_, _, cx| cx.notify()).detach();
525
526 let pane = cx.add_view(|_| Pane::new(params.settings.clone()));
527 let pane_id = pane.id();
528 cx.observe(&pane, move |me, _, cx| {
529 let active_entry = me.active_project_path(cx);
530 me.project
531 .update(cx, |project, cx| project.set_active_path(active_entry, cx));
532 })
533 .detach();
534 cx.subscribe(&pane, move |me, _, event, cx| {
535 me.handle_pane_event(pane_id, event, cx)
536 })
537 .detach();
538 cx.focus(&pane);
539
540 let status_bar = cx.add_view(|cx| StatusBar::new(&pane, params.settings.clone(), cx));
541 let mut current_user = params.user_store.read(cx).watch_current_user().clone();
542 let mut connection_status = params.client.status().clone();
543 let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
544 current_user.recv().await;
545 connection_status.recv().await;
546 let mut stream =
547 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
548
549 while stream.recv().await.is_some() {
550 cx.update(|cx| {
551 if let Some(this) = this.upgrade(&cx) {
552 this.update(cx, |_, cx| cx.notify());
553 }
554 })
555 }
556 });
557
558 Workspace {
559 modal: None,
560 weak_self: cx.weak_handle(),
561 center: PaneGroup::new(pane.id()),
562 panes: vec![pane.clone()],
563 active_pane: pane.clone(),
564 status_bar,
565 settings: params.settings.clone(),
566 client: params.client.clone(),
567 user_store: params.user_store.clone(),
568 fs: params.fs.clone(),
569 left_sidebar: Sidebar::new(Side::Left),
570 right_sidebar: Sidebar::new(Side::Right),
571 project: params.project.clone(),
572 path_openers: params.path_openers.clone(),
573 items: Default::default(),
574 _observe_current_user,
575 }
576 }
577
578 pub fn weak_handle(&self) -> WeakViewHandle<Self> {
579 self.weak_self.clone()
580 }
581
582 pub fn settings(&self) -> watch::Receiver<Settings> {
583 self.settings.clone()
584 }
585
586 pub fn left_sidebar_mut(&mut self) -> &mut Sidebar {
587 &mut self.left_sidebar
588 }
589
590 pub fn right_sidebar_mut(&mut self) -> &mut Sidebar {
591 &mut self.right_sidebar
592 }
593
594 pub fn status_bar(&self) -> &ViewHandle<StatusBar> {
595 &self.status_bar
596 }
597
598 pub fn project(&self) -> &ModelHandle<Project> {
599 &self.project
600 }
601
602 pub fn worktrees<'a>(&self, cx: &'a AppContext) -> &'a [ModelHandle<Worktree>] {
603 &self.project.read(cx).worktrees()
604 }
605
606 pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
607 paths.iter().all(|path| self.contains_path(&path, cx))
608 }
609
610 pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
611 for worktree in self.worktrees(cx) {
612 let worktree = worktree.read(cx).as_local();
613 if worktree.map_or(false, |w| w.contains_abs_path(path)) {
614 return true;
615 }
616 }
617 false
618 }
619
620 pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
621 let futures = self
622 .worktrees(cx)
623 .iter()
624 .filter_map(|worktree| worktree.read(cx).as_local())
625 .map(|worktree| worktree.scan_complete())
626 .collect::<Vec<_>>();
627 async move {
628 for future in futures {
629 future.await;
630 }
631 }
632 }
633
634 pub fn open_paths(
635 &mut self,
636 abs_paths: &[PathBuf],
637 cx: &mut ViewContext<Self>,
638 ) -> Task<Vec<Option<Result<Box<dyn ItemViewHandle>, Arc<anyhow::Error>>>>> {
639 let entries = abs_paths
640 .iter()
641 .cloned()
642 .map(|path| self.project_path_for_path(&path, cx))
643 .collect::<Vec<_>>();
644
645 let fs = self.fs.clone();
646 let tasks = abs_paths
647 .iter()
648 .cloned()
649 .zip(entries.into_iter())
650 .map(|(abs_path, project_path)| {
651 cx.spawn(|this, mut cx| {
652 let fs = fs.clone();
653 async move {
654 let project_path = project_path.await.ok()?;
655 if fs.is_file(&abs_path).await {
656 Some(
657 this.update(&mut cx, |this, cx| this.open_path(project_path, cx))
658 .await,
659 )
660 } else {
661 None
662 }
663 }
664 })
665 })
666 .collect::<Vec<_>>();
667
668 cx.foreground().spawn(async move {
669 let mut items = Vec::new();
670 for task in tasks {
671 items.push(task.await);
672 }
673 items
674 })
675 }
676
677 fn project_path_for_path(
678 &self,
679 abs_path: &Path,
680 cx: &mut ViewContext<Self>,
681 ) -> Task<Result<ProjectPath>> {
682 let entry = self.project().update(cx, |project, cx| {
683 project.worktree_for_abs_path(abs_path, cx)
684 });
685 cx.spawn(|_, cx| async move {
686 let (worktree, path) = entry.await?;
687 Ok(ProjectPath {
688 worktree_id: worktree.read_with(&cx, |t, _| t.id()),
689 path: path.into(),
690 })
691 })
692 }
693
694 pub fn add_worktree(
695 &self,
696 path: &Path,
697 cx: &mut ViewContext<Self>,
698 ) -> Task<Result<ModelHandle<Worktree>>> {
699 self.project
700 .update(cx, |project, cx| project.add_local_worktree(path, cx))
701 }
702
703 pub fn toggle_modal<V, F>(&mut self, cx: &mut ViewContext<Self>, add_view: F)
704 where
705 V: 'static + View,
706 F: FnOnce(&mut ViewContext<Self>, &mut Self) -> ViewHandle<V>,
707 {
708 if self.modal.as_ref().map_or(false, |modal| modal.is::<V>()) {
709 self.modal.take();
710 cx.focus_self();
711 } else {
712 let modal = add_view(cx, self);
713 cx.focus(&modal);
714 self.modal = Some(modal.into());
715 }
716 cx.notify();
717 }
718
719 pub fn modal(&self) -> Option<&AnyViewHandle> {
720 self.modal.as_ref()
721 }
722
723 pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
724 if self.modal.take().is_some() {
725 cx.focus(&self.active_pane);
726 cx.notify();
727 }
728 }
729
730 pub fn open_path(
731 &mut self,
732 path: ProjectPath,
733 cx: &mut ViewContext<Self>,
734 ) -> Task<Result<Box<dyn ItemViewHandle>, Arc<anyhow::Error>>> {
735 let load_task = self.load_path(path, cx);
736 let pane = self.active_pane().clone().downgrade();
737 cx.spawn(|this, mut cx| async move {
738 let item = load_task.await?;
739 this.update(&mut cx, |this, cx| {
740 let pane = pane
741 .upgrade(&cx)
742 .ok_or_else(|| anyhow!("could not upgrade pane reference"))?;
743 Ok(this.open_item_in_pane(item, &pane, cx))
744 })
745 })
746 }
747
748 pub fn load_entry(
749 &mut self,
750 path: ProjectEntry,
751 cx: &mut ViewContext<Self>,
752 ) -> Task<Result<Box<dyn ItemHandle>>> {
753 if let Some(path) = self.project.read(cx).path_for_entry(path, cx) {
754 self.load_path(path, cx)
755 } else {
756 Task::ready(Err(anyhow!("entry does not exist")))
757 }
758 }
759
760 pub fn load_path(
761 &mut self,
762 path: ProjectPath,
763 cx: &mut ViewContext<Self>,
764 ) -> Task<Result<Box<dyn ItemHandle>>> {
765 if let Some(existing_item) = self.item_for_path(&path, cx) {
766 return Task::ready(Ok(existing_item));
767 }
768
769 let project_path = path.clone();
770 let path_openers = self.path_openers.clone();
771 self.project.update(cx, |project, cx| {
772 for opener in path_openers.iter() {
773 if let Some(task) = opener.open(project, project_path.clone(), cx) {
774 return task;
775 }
776 }
777 Task::ready(Err(anyhow!("no opener found for path {:?}", project_path)))
778 })
779 }
780
781 fn item_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
782 let project = self.project.read(cx);
783 self.items.iter().filter_map(|i| i.upgrade(cx)).find(|i| {
784 let item_path = i
785 .project_entry(cx)
786 .and_then(|entry| project.path_for_entry(entry, cx));
787 item_path.as_ref() == Some(path)
788 })
789 }
790
791 pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<ModelHandle<T>> {
792 self.items
793 .iter()
794 .find_map(|i| i.upgrade(cx).and_then(|i| i.to_any().downcast()))
795 }
796
797 pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemViewHandle>> {
798 self.active_pane().read(cx).active_item()
799 }
800
801 fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
802 self.active_item(cx)
803 .and_then(|item| item.project_entry(cx))
804 .and_then(|entry| self.project.read(cx).path_for_entry(entry, cx))
805 }
806
807 pub fn save_active_item(&mut self, _: &Save, cx: &mut ViewContext<Self>) {
808 if let Some(item) = self.active_item(cx) {
809 let handle = cx.handle();
810 if item.can_save(cx) {
811 if item.has_conflict(cx.as_ref()) {
812 const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
813
814 cx.prompt(
815 PromptLevel::Warning,
816 CONFLICT_MESSAGE,
817 &["Overwrite", "Cancel"],
818 move |answer, cx| {
819 if answer == 0 {
820 cx.spawn(|mut cx| async move {
821 if let Err(error) = cx.update(|cx| item.save(cx)).unwrap().await
822 {
823 error!("failed to save item: {:?}, ", error);
824 }
825 })
826 .detach();
827 }
828 },
829 );
830 } else {
831 cx.spawn(|_, mut cx| async move {
832 if let Err(error) = cx.update(|cx| item.save(cx)).unwrap().await {
833 error!("failed to save item: {:?}, ", error);
834 }
835 })
836 .detach();
837 }
838 } else if item.can_save_as(cx) {
839 let worktree = self.worktrees(cx).first();
840 let start_abs_path = worktree
841 .and_then(|w| w.read(cx).as_local())
842 .map_or(Path::new(""), |w| w.abs_path())
843 .to_path_buf();
844 cx.prompt_for_new_path(&start_abs_path, move |abs_path, cx| {
845 if let Some(abs_path) = abs_path {
846 let project = handle.read(cx).project().clone();
847 cx.update(|cx| item.save_as(project, abs_path, cx).detach_and_log_err(cx));
848 }
849 });
850 }
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 cx.prompt_for_paths(
1401 PathPromptOptions {
1402 files: true,
1403 directories: true,
1404 multiple: true,
1405 },
1406 move |paths, cx| {
1407 if let Some(paths) = paths {
1408 cx.dispatch_global_action(OpenPaths(OpenParams { paths, app_state }));
1409 }
1410 },
1411 );
1412}
1413
1414pub fn open_paths(
1415 abs_paths: &[PathBuf],
1416 app_state: &Arc<AppState>,
1417 cx: &mut MutableAppContext,
1418) -> Task<ViewHandle<Workspace>> {
1419 log::info!("open paths {:?}", abs_paths);
1420
1421 // Open paths in existing workspace if possible
1422 let mut existing = None;
1423 for window_id in cx.window_ids().collect::<Vec<_>>() {
1424 if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
1425 if workspace.update(cx, |view, cx| {
1426 if view.contains_paths(abs_paths, cx.as_ref()) {
1427 existing = Some(workspace.clone());
1428 true
1429 } else {
1430 false
1431 }
1432 }) {
1433 break;
1434 }
1435 }
1436 }
1437
1438 let workspace = existing.unwrap_or_else(|| {
1439 cx.add_window((app_state.build_window_options)(), |cx| {
1440 let project = Project::local(
1441 app_state.client.clone(),
1442 app_state.user_store.clone(),
1443 app_state.languages.clone(),
1444 app_state.fs.clone(),
1445 cx,
1446 );
1447 (app_state.build_workspace)(project, &app_state, cx)
1448 })
1449 .1
1450 });
1451
1452 let task = workspace.update(cx, |workspace, cx| workspace.open_paths(abs_paths, cx));
1453 cx.spawn(|_| async move {
1454 task.await;
1455 workspace
1456 })
1457}
1458
1459pub fn join_project(
1460 project_id: u64,
1461 app_state: &Arc<AppState>,
1462 cx: &mut MutableAppContext,
1463) -> Task<Result<ViewHandle<Workspace>>> {
1464 for window_id in cx.window_ids().collect::<Vec<_>>() {
1465 if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
1466 if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
1467 return Task::ready(Ok(workspace));
1468 }
1469 }
1470 }
1471
1472 let app_state = app_state.clone();
1473 cx.spawn(|mut cx| async move {
1474 let project = Project::remote(
1475 project_id,
1476 app_state.client.clone(),
1477 app_state.user_store.clone(),
1478 app_state.languages.clone(),
1479 app_state.fs.clone(),
1480 &mut cx,
1481 )
1482 .await?;
1483 let (_, workspace) = cx.update(|cx| {
1484 cx.add_window((app_state.build_window_options)(), |cx| {
1485 (app_state.build_workspace)(project, &app_state, cx)
1486 })
1487 });
1488 Ok(workspace)
1489 })
1490}
1491
1492fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
1493 let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
1494 let project = Project::local(
1495 app_state.client.clone(),
1496 app_state.user_store.clone(),
1497 app_state.languages.clone(),
1498 app_state.fs.clone(),
1499 cx,
1500 );
1501 (app_state.build_workspace)(project, &app_state, cx)
1502 });
1503 cx.dispatch_action(window_id, vec![workspace.id()], &OpenNew(app_state.clone()));
1504}