1pub mod lsp_status;
2pub mod menu;
3pub mod pane;
4pub mod pane_group;
5pub mod settings;
6pub mod sidebar;
7mod status_bar;
8
9use anyhow::{anyhow, Context, Result};
10use client::{
11 proto, Authenticate, ChannelList, Client, PeerId, Subscription, TypedEnvelope, User, UserStore,
12};
13use clock::ReplicaId;
14use collections::{hash_map, HashMap, HashSet};
15use gpui::{
16 action,
17 color::Color,
18 elements::*,
19 geometry::{vector::vec2f, PathBuilder},
20 json::{self, to_string_pretty, ToJson},
21 keymap::Binding,
22 platform::{CursorStyle, WindowOptions},
23 AnyModelHandle, AnyViewHandle, AppContext, AsyncAppContext, Border, ClipboardItem, Entity,
24 ImageData, ModelHandle, MutableAppContext, PathPromptOptions, PromptLevel, RenderContext, Task,
25 View, ViewContext, ViewHandle, WeakViewHandle,
26};
27use language::LanguageRegistry;
28use log::error;
29pub use pane::*;
30pub use pane_group::*;
31use postage::prelude::Stream;
32use project::{fs, Fs, Project, ProjectEntryId, ProjectPath, Worktree};
33pub use settings::Settings;
34use sidebar::{Side, Sidebar, SidebarItemId, ToggleSidebarItem, ToggleSidebarItemFocus};
35use status_bar::StatusBar;
36pub use status_bar::StatusItemView;
37use std::{
38 any::{Any, TypeId},
39 cell::RefCell,
40 fmt,
41 future::Future,
42 path::{Path, PathBuf},
43 rc::Rc,
44 sync::{
45 atomic::{AtomicBool, Ordering::SeqCst},
46 Arc,
47 },
48};
49use theme::{Theme, ThemeRegistry};
50use util::ResultExt;
51
52type ProjectItemBuilders = HashMap<
53 TypeId,
54 fn(usize, ModelHandle<Project>, AnyModelHandle, &mut MutableAppContext) -> Box<dyn ItemHandle>,
55>;
56
57type FollowableItemBuilder = fn(
58 ViewHandle<Pane>,
59 ModelHandle<Project>,
60 &mut Option<proto::view::Variant>,
61 &mut MutableAppContext,
62) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>;
63type FollowableItemBuilders = HashMap<
64 TypeId,
65 (
66 FollowableItemBuilder,
67 fn(AnyViewHandle) -> Box<dyn FollowableItemHandle>,
68 ),
69>;
70
71action!(Open, Arc<AppState>);
72action!(OpenNew, Arc<AppState>);
73action!(OpenPaths, OpenParams);
74action!(ToggleShare);
75action!(ToggleFollow, PeerId);
76action!(FollowNextCollaborator);
77action!(Unfollow);
78action!(JoinProject, JoinProjectParams);
79action!(Save);
80action!(DebugElements);
81action!(ActivatePreviousPane);
82action!(ActivateNextPane);
83
84pub fn init(client: &Arc<Client>, cx: &mut MutableAppContext) {
85 pane::init(cx);
86 menu::init(cx);
87
88 cx.add_global_action(open);
89 cx.add_global_action(move |action: &OpenPaths, cx: &mut MutableAppContext| {
90 open_paths(&action.0.paths, &action.0.app_state, cx).detach();
91 });
92 cx.add_global_action(move |action: &OpenNew, cx: &mut MutableAppContext| {
93 open_new(&action.0, cx)
94 });
95 cx.add_global_action(move |action: &JoinProject, cx: &mut MutableAppContext| {
96 join_project(action.0.project_id, &action.0.app_state, cx).detach();
97 });
98
99 cx.add_action(Workspace::toggle_share);
100 cx.add_async_action(Workspace::toggle_follow);
101 cx.add_async_action(Workspace::follow_next_collaborator);
102 cx.add_action(
103 |workspace: &mut Workspace, _: &Unfollow, cx: &mut ViewContext<Workspace>| {
104 let pane = workspace.active_pane().clone();
105 workspace.unfollow(&pane, cx);
106 },
107 );
108 cx.add_action(
109 |workspace: &mut Workspace, _: &Save, cx: &mut ViewContext<Workspace>| {
110 workspace.save_active_item(cx).detach_and_log_err(cx);
111 },
112 );
113 cx.add_action(Workspace::debug_elements);
114 cx.add_action(Workspace::toggle_sidebar_item);
115 cx.add_action(Workspace::toggle_sidebar_item_focus);
116 cx.add_action(|workspace: &mut Workspace, _: &ActivatePreviousPane, cx| {
117 workspace.activate_previous_pane(cx)
118 });
119 cx.add_action(|workspace: &mut Workspace, _: &ActivateNextPane, cx| {
120 workspace.activate_next_pane(cx)
121 });
122 cx.add_bindings(vec![
123 Binding::new("ctrl-alt-cmd-f", FollowNextCollaborator, None),
124 Binding::new("cmd-s", Save, None),
125 Binding::new("cmd-alt-i", DebugElements, None),
126 Binding::new("cmd-k cmd-left", ActivatePreviousPane, None),
127 Binding::new("cmd-k cmd-right", ActivateNextPane, None),
128 Binding::new(
129 "cmd-shift-!",
130 ToggleSidebarItem(SidebarItemId {
131 side: Side::Left,
132 item_index: 0,
133 }),
134 None,
135 ),
136 Binding::new(
137 "cmd-1",
138 ToggleSidebarItemFocus(SidebarItemId {
139 side: Side::Left,
140 item_index: 0,
141 }),
142 None,
143 ),
144 ]);
145
146 client.add_view_request_handler(Workspace::handle_follow);
147 client.add_view_message_handler(Workspace::handle_unfollow);
148 client.add_view_message_handler(Workspace::handle_update_followers);
149}
150
151pub fn register_project_item<I: ProjectItem>(cx: &mut MutableAppContext) {
152 cx.update_default_global(|builders: &mut ProjectItemBuilders, _| {
153 builders.insert(TypeId::of::<I::Item>(), |window_id, project, model, cx| {
154 let item = model.downcast::<I::Item>().unwrap();
155 Box::new(cx.add_view(window_id, |cx| I::for_project_item(project, item, cx)))
156 });
157 });
158}
159
160pub fn register_followable_item<I: FollowableItem>(cx: &mut MutableAppContext) {
161 cx.update_default_global(|builders: &mut FollowableItemBuilders, _| {
162 builders.insert(
163 TypeId::of::<I>(),
164 (
165 |pane, project, state, cx| {
166 I::from_state_proto(pane, project, state, cx).map(|task| {
167 cx.foreground()
168 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
169 })
170 },
171 |this| Box::new(this.downcast::<I>().unwrap()),
172 ),
173 );
174 });
175}
176
177pub struct AppState {
178 pub languages: Arc<LanguageRegistry>,
179 pub themes: Arc<ThemeRegistry>,
180 pub client: Arc<client::Client>,
181 pub user_store: ModelHandle<client::UserStore>,
182 pub fs: Arc<dyn fs::Fs>,
183 pub channel_list: ModelHandle<client::ChannelList>,
184 pub build_window_options: &'static dyn Fn() -> WindowOptions<'static>,
185 pub build_workspace: &'static dyn Fn(
186 ModelHandle<Project>,
187 &Arc<AppState>,
188 &mut ViewContext<Workspace>,
189 ) -> Workspace,
190}
191
192#[derive(Clone)]
193pub struct OpenParams {
194 pub paths: Vec<PathBuf>,
195 pub app_state: Arc<AppState>,
196}
197
198#[derive(Clone)]
199pub struct JoinProjectParams {
200 pub project_id: u64,
201 pub app_state: Arc<AppState>,
202}
203
204pub trait Item: View {
205 fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
206 fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
207 false
208 }
209 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox;
210 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
211 fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
212 fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>);
213 fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
214 where
215 Self: Sized,
216 {
217 None
218 }
219 fn is_dirty(&self, _: &AppContext) -> bool {
220 false
221 }
222 fn has_conflict(&self, _: &AppContext) -> bool {
223 false
224 }
225 fn can_save(&self, cx: &AppContext) -> bool;
226 fn save(
227 &mut self,
228 project: ModelHandle<Project>,
229 cx: &mut ViewContext<Self>,
230 ) -> Task<Result<()>>;
231 fn can_save_as(&self, cx: &AppContext) -> bool;
232 fn save_as(
233 &mut self,
234 project: ModelHandle<Project>,
235 abs_path: PathBuf,
236 cx: &mut ViewContext<Self>,
237 ) -> Task<Result<()>>;
238 fn should_activate_item_on_event(_: &Self::Event) -> bool {
239 false
240 }
241 fn should_close_item_on_event(_: &Self::Event) -> bool {
242 false
243 }
244 fn should_update_tab_on_event(_: &Self::Event) -> bool {
245 false
246 }
247 fn act_as_type(
248 &self,
249 type_id: TypeId,
250 self_handle: &ViewHandle<Self>,
251 _: &AppContext,
252 ) -> Option<AnyViewHandle> {
253 if TypeId::of::<Self>() == type_id {
254 Some(self_handle.into())
255 } else {
256 None
257 }
258 }
259}
260
261pub trait ProjectItem: Item {
262 type Item: project::Item;
263
264 fn for_project_item(
265 project: ModelHandle<Project>,
266 item: ModelHandle<Self::Item>,
267 cx: &mut ViewContext<Self>,
268 ) -> Self;
269}
270
271pub trait FollowableItem: Item {
272 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
273 fn from_state_proto(
274 pane: ViewHandle<Pane>,
275 project: ModelHandle<Project>,
276 state: &mut Option<proto::view::Variant>,
277 cx: &mut MutableAppContext,
278 ) -> Option<Task<Result<ViewHandle<Self>>>>;
279 fn add_event_to_update_proto(
280 &self,
281 event: &Self::Event,
282 update: &mut Option<proto::update_view::Variant>,
283 cx: &AppContext,
284 ) -> bool;
285 fn apply_update_proto(
286 &mut self,
287 message: proto::update_view::Variant,
288 cx: &mut ViewContext<Self>,
289 ) -> Result<()>;
290
291 fn set_leader_replica_id(&mut self, leader_replica_id: Option<u16>, cx: &mut ViewContext<Self>);
292 fn should_unfollow_on_event(event: &Self::Event, cx: &AppContext) -> bool;
293}
294
295pub trait FollowableItemHandle: ItemHandle {
296 fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext);
297 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
298 fn add_event_to_update_proto(
299 &self,
300 event: &dyn Any,
301 update: &mut Option<proto::update_view::Variant>,
302 cx: &AppContext,
303 ) -> bool;
304 fn apply_update_proto(
305 &self,
306 message: proto::update_view::Variant,
307 cx: &mut MutableAppContext,
308 ) -> Result<()>;
309 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool;
310}
311
312impl<T: FollowableItem> FollowableItemHandle for ViewHandle<T> {
313 fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext) {
314 self.update(cx, |this, cx| {
315 this.set_leader_replica_id(leader_replica_id, cx)
316 })
317 }
318
319 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
320 self.read(cx).to_state_proto(cx)
321 }
322
323 fn add_event_to_update_proto(
324 &self,
325 event: &dyn Any,
326 update: &mut Option<proto::update_view::Variant>,
327 cx: &AppContext,
328 ) -> bool {
329 if let Some(event) = event.downcast_ref() {
330 self.read(cx).add_event_to_update_proto(event, update, cx)
331 } else {
332 false
333 }
334 }
335
336 fn apply_update_proto(
337 &self,
338 message: proto::update_view::Variant,
339 cx: &mut MutableAppContext,
340 ) -> Result<()> {
341 self.update(cx, |this, cx| this.apply_update_proto(message, cx))
342 }
343
344 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool {
345 if let Some(event) = event.downcast_ref() {
346 T::should_unfollow_on_event(event, cx)
347 } else {
348 false
349 }
350 }
351}
352
353pub trait ItemHandle: 'static + fmt::Debug {
354 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox;
355 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
356 fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
357 fn boxed_clone(&self) -> Box<dyn ItemHandle>;
358 fn set_nav_history(&self, nav_history: Rc<RefCell<NavHistory>>, cx: &mut MutableAppContext);
359 fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>>;
360 fn added_to_pane(
361 &self,
362 workspace: &mut Workspace,
363 pane: ViewHandle<Pane>,
364 cx: &mut ViewContext<Workspace>,
365 );
366 fn deactivated(&self, cx: &mut MutableAppContext);
367 fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool;
368 fn id(&self) -> usize;
369 fn to_any(&self) -> AnyViewHandle;
370 fn is_dirty(&self, cx: &AppContext) -> bool;
371 fn has_conflict(&self, cx: &AppContext) -> bool;
372 fn can_save(&self, cx: &AppContext) -> bool;
373 fn can_save_as(&self, cx: &AppContext) -> bool;
374 fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>>;
375 fn save_as(
376 &self,
377 project: ModelHandle<Project>,
378 abs_path: PathBuf,
379 cx: &mut MutableAppContext,
380 ) -> Task<Result<()>>;
381 fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle>;
382 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
383}
384
385pub trait WeakItemHandle {
386 fn id(&self) -> usize;
387 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>>;
388}
389
390impl dyn ItemHandle {
391 pub fn downcast<T: View>(&self) -> Option<ViewHandle<T>> {
392 self.to_any().downcast()
393 }
394
395 pub fn act_as<T: View>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
396 self.act_as_type(TypeId::of::<T>(), cx)
397 .and_then(|t| t.downcast())
398 }
399}
400
401impl<T: Item> ItemHandle for ViewHandle<T> {
402 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
403 self.read(cx).tab_content(style, cx)
404 }
405
406 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
407 self.read(cx).project_path(cx)
408 }
409
410 fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
411 self.read(cx).project_entry_id(cx)
412 }
413
414 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
415 Box::new(self.clone())
416 }
417
418 fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>> {
419 self.update(cx, |item, cx| {
420 cx.add_option_view(|cx| item.clone_on_split(cx))
421 })
422 .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
423 }
424
425 fn set_nav_history(&self, nav_history: Rc<RefCell<NavHistory>>, cx: &mut MutableAppContext) {
426 self.update(cx, |item, cx| {
427 item.set_nav_history(ItemNavHistory::new(nav_history, &cx.handle()), cx);
428 })
429 }
430
431 fn added_to_pane(
432 &self,
433 workspace: &mut Workspace,
434 pane: ViewHandle<Pane>,
435 cx: &mut ViewContext<Workspace>,
436 ) {
437 if let Some(followed_item) = self.to_followable_item_handle(cx) {
438 if let Some(message) = followed_item.to_state_proto(cx) {
439 workspace.update_followers(
440 proto::update_followers::Variant::CreateView(proto::View {
441 id: followed_item.id() as u64,
442 variant: Some(message),
443 leader_id: workspace.leader_for_pane(&pane).map(|id| id.0),
444 }),
445 cx,
446 );
447 }
448 }
449
450 let pending_update = Rc::new(RefCell::new(None));
451 let pending_update_scheduled = Rc::new(AtomicBool::new(false));
452 let pane = pane.downgrade();
453 cx.subscribe(self, move |workspace, item, event, cx| {
454 let pane = if let Some(pane) = pane.upgrade(cx) {
455 pane
456 } else {
457 log::error!("unexpected item event after pane was dropped");
458 return;
459 };
460
461 if let Some(item) = item.to_followable_item_handle(cx) {
462 let leader_id = workspace.leader_for_pane(&pane);
463
464 if leader_id.is_some() && item.should_unfollow_on_event(event, cx) {
465 workspace.unfollow(&pane, cx);
466 }
467
468 if item.add_event_to_update_proto(event, &mut *pending_update.borrow_mut(), cx)
469 && !pending_update_scheduled.load(SeqCst)
470 {
471 pending_update_scheduled.store(true, SeqCst);
472 cx.after_window_update({
473 let pending_update = pending_update.clone();
474 let pending_update_scheduled = pending_update_scheduled.clone();
475 move |this, cx| {
476 pending_update_scheduled.store(false, SeqCst);
477 this.update_followers(
478 proto::update_followers::Variant::UpdateView(proto::UpdateView {
479 id: item.id() as u64,
480 variant: pending_update.borrow_mut().take(),
481 leader_id: leader_id.map(|id| id.0),
482 }),
483 cx,
484 );
485 }
486 });
487 }
488 }
489
490 if T::should_close_item_on_event(event) {
491 pane.update(cx, |pane, cx| pane.close_item(item.id(), cx));
492 return;
493 }
494
495 if T::should_activate_item_on_event(event) {
496 pane.update(cx, |pane, cx| {
497 if let Some(ix) = pane.index_for_item(&item) {
498 pane.activate_item(ix, true, cx);
499 pane.activate(cx);
500 }
501 });
502 }
503
504 if T::should_update_tab_on_event(event) {
505 pane.update(cx, |_, cx| cx.notify());
506 }
507 })
508 .detach();
509 }
510
511 fn deactivated(&self, cx: &mut MutableAppContext) {
512 self.update(cx, |this, cx| this.deactivated(cx));
513 }
514
515 fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool {
516 self.update(cx, |this, cx| this.navigate(data, cx))
517 }
518
519 fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>> {
520 self.update(cx, |item, cx| item.save(project, cx))
521 }
522
523 fn save_as(
524 &self,
525 project: ModelHandle<Project>,
526 abs_path: PathBuf,
527 cx: &mut MutableAppContext,
528 ) -> Task<anyhow::Result<()>> {
529 self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
530 }
531
532 fn is_dirty(&self, cx: &AppContext) -> bool {
533 self.read(cx).is_dirty(cx)
534 }
535
536 fn has_conflict(&self, cx: &AppContext) -> bool {
537 self.read(cx).has_conflict(cx)
538 }
539
540 fn id(&self) -> usize {
541 self.id()
542 }
543
544 fn to_any(&self) -> AnyViewHandle {
545 self.into()
546 }
547
548 fn can_save(&self, cx: &AppContext) -> bool {
549 self.read(cx).can_save(cx)
550 }
551
552 fn can_save_as(&self, cx: &AppContext) -> bool {
553 self.read(cx).can_save_as(cx)
554 }
555
556 fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle> {
557 self.read(cx).act_as_type(type_id, self, cx)
558 }
559
560 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
561 if cx.has_global::<FollowableItemBuilders>() {
562 let builders = cx.global::<FollowableItemBuilders>();
563 let item = self.to_any();
564 Some(builders.get(&item.view_type())?.1(item))
565 } else {
566 None
567 }
568 }
569}
570
571impl Into<AnyViewHandle> for Box<dyn ItemHandle> {
572 fn into(self) -> AnyViewHandle {
573 self.to_any()
574 }
575}
576
577impl Clone for Box<dyn ItemHandle> {
578 fn clone(&self) -> Box<dyn ItemHandle> {
579 self.boxed_clone()
580 }
581}
582
583impl<T: Item> WeakItemHandle for WeakViewHandle<T> {
584 fn id(&self) -> usize {
585 self.id()
586 }
587
588 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
589 self.upgrade(cx).map(|v| Box::new(v) as Box<dyn ItemHandle>)
590 }
591}
592
593#[derive(Clone)]
594pub struct WorkspaceParams {
595 pub project: ModelHandle<Project>,
596 pub client: Arc<Client>,
597 pub fs: Arc<dyn Fs>,
598 pub languages: Arc<LanguageRegistry>,
599 pub user_store: ModelHandle<UserStore>,
600 pub channel_list: ModelHandle<ChannelList>,
601}
602
603impl WorkspaceParams {
604 #[cfg(any(test, feature = "test-support"))]
605 pub fn test(cx: &mut MutableAppContext) -> Self {
606 let settings = Settings::test(cx);
607 cx.set_global(settings);
608
609 let fs = project::FakeFs::new(cx.background().clone());
610 let languages = Arc::new(LanguageRegistry::test());
611 let http_client = client::test::FakeHttpClient::new(|_| async move {
612 Ok(client::http::ServerResponse::new(404))
613 });
614 let client = Client::new(http_client.clone());
615 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
616 let project = Project::local(
617 client.clone(),
618 user_store.clone(),
619 languages.clone(),
620 fs.clone(),
621 cx,
622 );
623 Self {
624 project,
625 channel_list: cx
626 .add_model(|cx| ChannelList::new(user_store.clone(), client.clone(), cx)),
627 client,
628 fs,
629 languages,
630 user_store,
631 }
632 }
633
634 #[cfg(any(test, feature = "test-support"))]
635 pub fn local(app_state: &Arc<AppState>, cx: &mut MutableAppContext) -> Self {
636 Self {
637 project: Project::local(
638 app_state.client.clone(),
639 app_state.user_store.clone(),
640 app_state.languages.clone(),
641 app_state.fs.clone(),
642 cx,
643 ),
644 client: app_state.client.clone(),
645 fs: app_state.fs.clone(),
646 languages: app_state.languages.clone(),
647 user_store: app_state.user_store.clone(),
648 channel_list: app_state.channel_list.clone(),
649 }
650 }
651}
652
653pub struct Workspace {
654 weak_self: WeakViewHandle<Self>,
655 client: Arc<Client>,
656 user_store: ModelHandle<client::UserStore>,
657 remote_entity_subscription: Option<Subscription>,
658 fs: Arc<dyn Fs>,
659 modal: Option<AnyViewHandle>,
660 center: PaneGroup,
661 left_sidebar: Sidebar,
662 right_sidebar: Sidebar,
663 panes: Vec<ViewHandle<Pane>>,
664 active_pane: ViewHandle<Pane>,
665 status_bar: ViewHandle<StatusBar>,
666 project: ModelHandle<Project>,
667 leader_state: LeaderState,
668 follower_states_by_leader: FollowerStatesByLeader,
669 last_leaders_by_pane: HashMap<WeakViewHandle<Pane>, PeerId>,
670 _observe_current_user: Task<()>,
671}
672
673#[derive(Default)]
674struct LeaderState {
675 followers: HashSet<PeerId>,
676}
677
678type FollowerStatesByLeader = HashMap<PeerId, HashMap<ViewHandle<Pane>, FollowerState>>;
679
680#[derive(Default)]
681struct FollowerState {
682 active_view_id: Option<u64>,
683 items_by_leader_view_id: HashMap<u64, FollowerItem>,
684}
685
686#[derive(Debug)]
687enum FollowerItem {
688 Loading(Vec<proto::update_view::Variant>),
689 Loaded(Box<dyn FollowableItemHandle>),
690}
691
692impl Workspace {
693 pub fn new(params: &WorkspaceParams, cx: &mut ViewContext<Self>) -> Self {
694 cx.observe(¶ms.project, |_, project, cx| {
695 if project.read(cx).is_read_only() {
696 cx.blur();
697 }
698 cx.notify()
699 })
700 .detach();
701
702 cx.subscribe(¶ms.project, move |this, project, event, cx| {
703 match event {
704 project::Event::RemoteIdChanged(remote_id) => {
705 this.project_remote_id_changed(*remote_id, cx);
706 }
707 project::Event::CollaboratorLeft(peer_id) => {
708 this.collaborator_left(*peer_id, cx);
709 }
710 _ => {}
711 }
712 if project.read(cx).is_read_only() {
713 cx.blur();
714 }
715 cx.notify()
716 })
717 .detach();
718
719 let pane = cx.add_view(|_| Pane::new());
720 let pane_id = pane.id();
721 cx.observe(&pane, move |me, _, cx| {
722 let active_entry = me.active_project_path(cx);
723 me.project
724 .update(cx, |project, cx| project.set_active_path(active_entry, cx));
725 })
726 .detach();
727 cx.subscribe(&pane, move |me, _, event, cx| {
728 me.handle_pane_event(pane_id, event, cx)
729 })
730 .detach();
731 cx.focus(&pane);
732
733 let status_bar = cx.add_view(|cx| StatusBar::new(&pane, cx));
734 let mut current_user = params.user_store.read(cx).watch_current_user().clone();
735 let mut connection_status = params.client.status().clone();
736 let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
737 current_user.recv().await;
738 connection_status.recv().await;
739 let mut stream =
740 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
741
742 while stream.recv().await.is_some() {
743 cx.update(|cx| {
744 if let Some(this) = this.upgrade(cx) {
745 this.update(cx, |_, cx| cx.notify());
746 }
747 })
748 }
749 });
750
751 let weak_self = cx.weak_handle();
752
753 cx.emit_global(WorkspaceCreated(weak_self.clone()));
754
755 let mut this = Workspace {
756 modal: None,
757 weak_self,
758 center: PaneGroup::new(pane.clone()),
759 panes: vec![pane.clone()],
760 active_pane: pane.clone(),
761 status_bar,
762 client: params.client.clone(),
763 remote_entity_subscription: None,
764 user_store: params.user_store.clone(),
765 fs: params.fs.clone(),
766 left_sidebar: Sidebar::new(Side::Left),
767 right_sidebar: Sidebar::new(Side::Right),
768 project: params.project.clone(),
769 leader_state: Default::default(),
770 follower_states_by_leader: Default::default(),
771 last_leaders_by_pane: Default::default(),
772 _observe_current_user,
773 };
774 this.project_remote_id_changed(this.project.read(cx).remote_id(), cx);
775 this
776 }
777
778 pub fn weak_handle(&self) -> WeakViewHandle<Self> {
779 self.weak_self.clone()
780 }
781
782 pub fn left_sidebar_mut(&mut self) -> &mut Sidebar {
783 &mut self.left_sidebar
784 }
785
786 pub fn right_sidebar_mut(&mut self) -> &mut Sidebar {
787 &mut self.right_sidebar
788 }
789
790 pub fn status_bar(&self) -> &ViewHandle<StatusBar> {
791 &self.status_bar
792 }
793
794 pub fn project(&self) -> &ModelHandle<Project> {
795 &self.project
796 }
797
798 pub fn worktrees<'a>(
799 &self,
800 cx: &'a AppContext,
801 ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
802 self.project.read(cx).worktrees(cx)
803 }
804
805 pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
806 paths.iter().all(|path| self.contains_path(&path, cx))
807 }
808
809 pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
810 for worktree in self.worktrees(cx) {
811 let worktree = worktree.read(cx).as_local();
812 if worktree.map_or(false, |w| w.contains_abs_path(path)) {
813 return true;
814 }
815 }
816 false
817 }
818
819 pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
820 let futures = self
821 .worktrees(cx)
822 .filter_map(|worktree| worktree.read(cx).as_local())
823 .map(|worktree| worktree.scan_complete())
824 .collect::<Vec<_>>();
825 async move {
826 for future in futures {
827 future.await;
828 }
829 }
830 }
831
832 pub fn open_paths(
833 &mut self,
834 abs_paths: &[PathBuf],
835 cx: &mut ViewContext<Self>,
836 ) -> Task<Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>> {
837 let entries = abs_paths
838 .iter()
839 .cloned()
840 .map(|path| self.project_path_for_path(&path, cx))
841 .collect::<Vec<_>>();
842
843 let fs = self.fs.clone();
844 let tasks = abs_paths
845 .iter()
846 .cloned()
847 .zip(entries.into_iter())
848 .map(|(abs_path, project_path)| {
849 cx.spawn(|this, mut cx| {
850 let fs = fs.clone();
851 async move {
852 let project_path = project_path.await.ok()?;
853 if fs.is_file(&abs_path).await {
854 Some(
855 this.update(&mut cx, |this, cx| this.open_path(project_path, cx))
856 .await,
857 )
858 } else {
859 None
860 }
861 }
862 })
863 })
864 .collect::<Vec<_>>();
865
866 cx.foreground().spawn(async move {
867 let mut items = Vec::new();
868 for task in tasks {
869 items.push(task.await);
870 }
871 items
872 })
873 }
874
875 fn project_path_for_path(
876 &self,
877 abs_path: &Path,
878 cx: &mut ViewContext<Self>,
879 ) -> Task<Result<ProjectPath>> {
880 let entry = self.project().update(cx, |project, cx| {
881 project.find_or_create_local_worktree(abs_path, true, cx)
882 });
883 cx.spawn(|_, cx| async move {
884 let (worktree, path) = entry.await?;
885 Ok(ProjectPath {
886 worktree_id: worktree.read_with(&cx, |t, _| t.id()),
887 path: path.into(),
888 })
889 })
890 }
891
892 // Returns the model that was toggled closed if it was open
893 pub fn toggle_modal<V, F>(
894 &mut self,
895 cx: &mut ViewContext<Self>,
896 add_view: F,
897 ) -> Option<ViewHandle<V>>
898 where
899 V: 'static + View,
900 F: FnOnce(&mut ViewContext<Self>, &mut Self) -> ViewHandle<V>,
901 {
902 cx.notify();
903 // Whatever modal was visible is getting clobbered. If its the same type as V, then return
904 // it. Otherwise, create a new modal and set it as active.
905 let already_open_modal = self.modal.take().and_then(|modal| modal.downcast::<V>());
906 if let Some(already_open_modal) = already_open_modal {
907 cx.focus_self();
908 Some(already_open_modal)
909 } else {
910 let modal = add_view(cx, self);
911 cx.focus(&modal);
912 self.modal = Some(modal.into());
913 None
914 }
915 }
916
917 pub fn modal(&self) -> Option<&AnyViewHandle> {
918 self.modal.as_ref()
919 }
920
921 pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
922 if self.modal.take().is_some() {
923 cx.focus(&self.active_pane);
924 cx.notify();
925 }
926 }
927
928 pub fn items<'a>(
929 &'a self,
930 cx: &'a AppContext,
931 ) -> impl 'a + Iterator<Item = &Box<dyn ItemHandle>> {
932 self.panes.iter().flat_map(|pane| pane.read(cx).items())
933 }
934
935 pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
936 self.items_of_type(cx).max_by_key(|item| item.id())
937 }
938
939 pub fn items_of_type<'a, T: Item>(
940 &'a self,
941 cx: &'a AppContext,
942 ) -> impl 'a + Iterator<Item = ViewHandle<T>> {
943 self.panes
944 .iter()
945 .flat_map(|pane| pane.read(cx).items_of_type())
946 }
947
948 pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
949 self.active_pane().read(cx).active_item()
950 }
951
952 fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
953 self.active_item(cx).and_then(|item| item.project_path(cx))
954 }
955
956 pub fn save_active_item(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
957 let project = self.project.clone();
958 if let Some(item) = self.active_item(cx) {
959 if item.can_save(cx) {
960 if item.has_conflict(cx.as_ref()) {
961 const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
962
963 let mut answer = cx.prompt(
964 PromptLevel::Warning,
965 CONFLICT_MESSAGE,
966 &["Overwrite", "Cancel"],
967 );
968 cx.spawn(|_, mut cx| async move {
969 let answer = answer.recv().await;
970 if answer == Some(0) {
971 cx.update(|cx| item.save(project, cx)).await?;
972 }
973 Ok(())
974 })
975 } else {
976 item.save(project, cx)
977 }
978 } else if item.can_save_as(cx) {
979 let worktree = self.worktrees(cx).next();
980 let start_abs_path = worktree
981 .and_then(|w| w.read(cx).as_local())
982 .map_or(Path::new(""), |w| w.abs_path())
983 .to_path_buf();
984 let mut abs_path = cx.prompt_for_new_path(&start_abs_path);
985 cx.spawn(|_, mut cx| async move {
986 if let Some(abs_path) = abs_path.recv().await.flatten() {
987 cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
988 }
989 Ok(())
990 })
991 } else {
992 Task::ready(Ok(()))
993 }
994 } else {
995 Task::ready(Ok(()))
996 }
997 }
998
999 pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
1000 let sidebar = match action.0.side {
1001 Side::Left => &mut self.left_sidebar,
1002 Side::Right => &mut self.right_sidebar,
1003 };
1004 sidebar.toggle_item(action.0.item_index);
1005 if let Some(active_item) = sidebar.active_item() {
1006 cx.focus(active_item);
1007 } else {
1008 cx.focus_self();
1009 }
1010 cx.notify();
1011 }
1012
1013 pub fn toggle_sidebar_item_focus(
1014 &mut self,
1015 action: &ToggleSidebarItemFocus,
1016 cx: &mut ViewContext<Self>,
1017 ) {
1018 let sidebar = match action.0.side {
1019 Side::Left => &mut self.left_sidebar,
1020 Side::Right => &mut self.right_sidebar,
1021 };
1022 sidebar.activate_item(action.0.item_index);
1023 if let Some(active_item) = sidebar.active_item() {
1024 if active_item.is_focused(cx) {
1025 cx.focus_self();
1026 } else {
1027 cx.focus(active_item);
1028 }
1029 }
1030 cx.notify();
1031 }
1032
1033 pub fn debug_elements(&mut self, _: &DebugElements, cx: &mut ViewContext<Self>) {
1034 match to_string_pretty(&cx.debug_elements()) {
1035 Ok(json) => {
1036 let kib = json.len() as f32 / 1024.;
1037 cx.as_mut().write_to_clipboard(ClipboardItem::new(json));
1038 log::info!(
1039 "copied {:.1} KiB of element debug JSON to the clipboard",
1040 kib
1041 );
1042 }
1043 Err(error) => {
1044 log::error!("error debugging elements: {}", error);
1045 }
1046 };
1047 }
1048
1049 fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
1050 let pane = cx.add_view(|_| Pane::new());
1051 let pane_id = pane.id();
1052 cx.observe(&pane, move |me, _, cx| {
1053 let active_entry = me.active_project_path(cx);
1054 me.project
1055 .update(cx, |project, cx| project.set_active_path(active_entry, cx));
1056 })
1057 .detach();
1058 cx.subscribe(&pane, move |me, _, event, cx| {
1059 me.handle_pane_event(pane_id, event, cx)
1060 })
1061 .detach();
1062 self.panes.push(pane.clone());
1063 self.activate_pane(pane.clone(), cx);
1064 pane
1065 }
1066
1067 pub fn add_item(&mut self, item: Box<dyn ItemHandle>, cx: &mut ViewContext<Self>) {
1068 let pane = self.active_pane().clone();
1069 Pane::add_item(self, pane, item, true, cx);
1070 }
1071
1072 pub fn open_path(
1073 &mut self,
1074 path: impl Into<ProjectPath>,
1075 cx: &mut ViewContext<Self>,
1076 ) -> Task<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>> {
1077 let pane = self.active_pane().downgrade();
1078 let task = self.load_path(path.into(), cx);
1079 cx.spawn(|this, mut cx| async move {
1080 let (project_entry_id, build_item) = task.await?;
1081 let pane = pane
1082 .upgrade(&cx)
1083 .ok_or_else(|| anyhow!("pane was closed"))?;
1084 this.update(&mut cx, |this, cx| {
1085 Ok(Pane::open_item(
1086 this,
1087 pane,
1088 project_entry_id,
1089 cx,
1090 build_item,
1091 ))
1092 })
1093 })
1094 }
1095
1096 pub(crate) fn load_path(
1097 &mut self,
1098 path: ProjectPath,
1099 cx: &mut ViewContext<Self>,
1100 ) -> Task<
1101 Result<(
1102 ProjectEntryId,
1103 impl 'static + FnOnce(&mut MutableAppContext) -> Box<dyn ItemHandle>,
1104 )>,
1105 > {
1106 let project = self.project().clone();
1107 let project_item = project.update(cx, |project, cx| project.open_path(path, cx));
1108 let window_id = cx.window_id();
1109 cx.as_mut().spawn(|mut cx| async move {
1110 let (project_entry_id, project_item) = project_item.await?;
1111 let build_item = cx.update(|cx| {
1112 cx.default_global::<ProjectItemBuilders>()
1113 .get(&project_item.model_type())
1114 .ok_or_else(|| anyhow!("no item builder for project item"))
1115 .cloned()
1116 })?;
1117 let build_item =
1118 move |cx: &mut MutableAppContext| build_item(window_id, project, project_item, cx);
1119 Ok((project_entry_id, build_item))
1120 })
1121 }
1122
1123 pub fn open_project_item<T>(
1124 &mut self,
1125 project_item: ModelHandle<T::Item>,
1126 cx: &mut ViewContext<Self>,
1127 ) -> ViewHandle<T>
1128 where
1129 T: ProjectItem,
1130 {
1131 use project::Item as _;
1132
1133 let entry_id = project_item.read(cx).entry_id(cx);
1134 if let Some(item) = entry_id
1135 .and_then(|entry_id| self.active_pane().read(cx).item_for_entry(entry_id, cx))
1136 .and_then(|item| item.downcast())
1137 {
1138 self.activate_item(&item, cx);
1139 return item;
1140 }
1141
1142 let item = cx.add_view(|cx| T::for_project_item(self.project().clone(), project_item, cx));
1143 self.add_item(Box::new(item.clone()), cx);
1144 item
1145 }
1146
1147 pub fn activate_item(&mut self, item: &dyn ItemHandle, cx: &mut ViewContext<Self>) -> bool {
1148 let result = self.panes.iter().find_map(|pane| {
1149 if let Some(ix) = pane.read(cx).index_for_item(item) {
1150 Some((pane.clone(), ix))
1151 } else {
1152 None
1153 }
1154 });
1155 if let Some((pane, ix)) = result {
1156 self.activate_pane(pane.clone(), cx);
1157 pane.update(cx, |pane, cx| pane.activate_item(ix, true, cx));
1158 true
1159 } else {
1160 false
1161 }
1162 }
1163
1164 pub fn activate_next_pane(&mut self, cx: &mut ViewContext<Self>) {
1165 let next_pane = {
1166 let panes = self.center.panes();
1167 let ix = panes
1168 .iter()
1169 .position(|pane| **pane == self.active_pane)
1170 .unwrap();
1171 let next_ix = (ix + 1) % panes.len();
1172 panes[next_ix].clone()
1173 };
1174 self.activate_pane(next_pane, cx);
1175 }
1176
1177 pub fn activate_previous_pane(&mut self, cx: &mut ViewContext<Self>) {
1178 let prev_pane = {
1179 let panes = self.center.panes();
1180 let ix = panes
1181 .iter()
1182 .position(|pane| **pane == self.active_pane)
1183 .unwrap();
1184 let prev_ix = if ix == 0 { panes.len() - 1 } else { ix - 1 };
1185 panes[prev_ix].clone()
1186 };
1187 self.activate_pane(prev_pane, cx);
1188 }
1189
1190 fn activate_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1191 if self.active_pane != pane {
1192 self.active_pane = pane.clone();
1193 self.status_bar.update(cx, |status_bar, cx| {
1194 status_bar.set_active_pane(&self.active_pane, cx);
1195 });
1196 cx.focus(&self.active_pane);
1197 cx.notify();
1198 }
1199
1200 self.update_followers(
1201 proto::update_followers::Variant::UpdateActiveView(proto::UpdateActiveView {
1202 id: self.active_item(cx).map(|item| item.id() as u64),
1203 leader_id: self.leader_for_pane(&pane).map(|id| id.0),
1204 }),
1205 cx,
1206 );
1207 }
1208
1209 fn handle_pane_event(
1210 &mut self,
1211 pane_id: usize,
1212 event: &pane::Event,
1213 cx: &mut ViewContext<Self>,
1214 ) {
1215 if let Some(pane) = self.pane(pane_id) {
1216 match event {
1217 pane::Event::Split(direction) => {
1218 self.split_pane(pane, *direction, cx);
1219 }
1220 pane::Event::Remove => {
1221 self.remove_pane(pane, cx);
1222 }
1223 pane::Event::Activate => {
1224 self.activate_pane(pane, cx);
1225 }
1226 pane::Event::ActivateItem { local } => {
1227 if *local {
1228 self.unfollow(&pane, cx);
1229 }
1230 }
1231 }
1232 } else {
1233 error!("pane {} not found", pane_id);
1234 }
1235 }
1236
1237 pub fn split_pane(
1238 &mut self,
1239 pane: ViewHandle<Pane>,
1240 direction: SplitDirection,
1241 cx: &mut ViewContext<Self>,
1242 ) -> ViewHandle<Pane> {
1243 let new_pane = self.add_pane(cx);
1244 self.activate_pane(new_pane.clone(), cx);
1245 if let Some(item) = pane.read(cx).active_item() {
1246 if let Some(clone) = item.clone_on_split(cx.as_mut()) {
1247 Pane::add_item(self, new_pane.clone(), clone, true, cx);
1248 }
1249 }
1250 self.center.split(&pane, &new_pane, direction).unwrap();
1251 cx.notify();
1252 new_pane
1253 }
1254
1255 fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1256 if self.center.remove(&pane).unwrap() {
1257 self.panes.retain(|p| p != &pane);
1258 self.activate_pane(self.panes.last().unwrap().clone(), cx);
1259 self.unfollow(&pane, cx);
1260 self.last_leaders_by_pane.remove(&pane.downgrade());
1261 cx.notify();
1262 }
1263 }
1264
1265 pub fn panes(&self) -> &[ViewHandle<Pane>] {
1266 &self.panes
1267 }
1268
1269 fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1270 self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1271 }
1272
1273 pub fn active_pane(&self) -> &ViewHandle<Pane> {
1274 &self.active_pane
1275 }
1276
1277 fn toggle_share(&mut self, _: &ToggleShare, cx: &mut ViewContext<Self>) {
1278 self.project.update(cx, |project, cx| {
1279 if project.is_local() {
1280 if project.is_shared() {
1281 project.unshare(cx);
1282 } else {
1283 project.share(cx).detach();
1284 }
1285 }
1286 });
1287 }
1288
1289 fn project_remote_id_changed(&mut self, remote_id: Option<u64>, cx: &mut ViewContext<Self>) {
1290 if let Some(remote_id) = remote_id {
1291 self.remote_entity_subscription =
1292 Some(self.client.add_view_for_remote_entity(remote_id, cx));
1293 } else {
1294 self.remote_entity_subscription.take();
1295 }
1296 }
1297
1298 fn collaborator_left(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
1299 self.leader_state.followers.remove(&peer_id);
1300 if let Some(states_by_pane) = self.follower_states_by_leader.remove(&peer_id) {
1301 for state in states_by_pane.into_values() {
1302 for item in state.items_by_leader_view_id.into_values() {
1303 if let FollowerItem::Loaded(item) = item {
1304 item.set_leader_replica_id(None, cx);
1305 }
1306 }
1307 }
1308 }
1309 cx.notify();
1310 }
1311
1312 pub fn toggle_follow(
1313 &mut self,
1314 ToggleFollow(leader_id): &ToggleFollow,
1315 cx: &mut ViewContext<Self>,
1316 ) -> Option<Task<Result<()>>> {
1317 let leader_id = *leader_id;
1318 let pane = self.active_pane().clone();
1319
1320 if let Some(prev_leader_id) = self.unfollow(&pane, cx) {
1321 if leader_id == prev_leader_id {
1322 return None;
1323 }
1324 }
1325
1326 self.last_leaders_by_pane
1327 .insert(pane.downgrade(), leader_id);
1328 self.follower_states_by_leader
1329 .entry(leader_id)
1330 .or_default()
1331 .insert(pane.clone(), Default::default());
1332 cx.notify();
1333
1334 let project_id = self.project.read(cx).remote_id()?;
1335 let request = self.client.request(proto::Follow {
1336 project_id,
1337 leader_id: leader_id.0,
1338 });
1339 Some(cx.spawn_weak(|this, mut cx| async move {
1340 let response = request.await?;
1341 if let Some(this) = this.upgrade(&cx) {
1342 this.update(&mut cx, |this, _| {
1343 let state = this
1344 .follower_states_by_leader
1345 .get_mut(&leader_id)
1346 .and_then(|states_by_pane| states_by_pane.get_mut(&pane))
1347 .ok_or_else(|| anyhow!("following interrupted"))?;
1348 state.active_view_id = response.active_view_id;
1349 Ok::<_, anyhow::Error>(())
1350 })?;
1351 Self::add_views_from_leader(this, leader_id, vec![pane], response.views, &mut cx)
1352 .await?;
1353 }
1354 Ok(())
1355 }))
1356 }
1357
1358 pub fn follow_next_collaborator(
1359 &mut self,
1360 _: &FollowNextCollaborator,
1361 cx: &mut ViewContext<Self>,
1362 ) -> Option<Task<Result<()>>> {
1363 let collaborators = self.project.read(cx).collaborators();
1364 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
1365 let mut collaborators = collaborators.keys().copied();
1366 while let Some(peer_id) = collaborators.next() {
1367 if peer_id == leader_id {
1368 break;
1369 }
1370 }
1371 collaborators.next()
1372 } else if let Some(last_leader_id) =
1373 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
1374 {
1375 if collaborators.contains_key(last_leader_id) {
1376 Some(*last_leader_id)
1377 } else {
1378 None
1379 }
1380 } else {
1381 None
1382 };
1383
1384 next_leader_id
1385 .or_else(|| collaborators.keys().copied().next())
1386 .and_then(|leader_id| self.toggle_follow(&ToggleFollow(leader_id), cx))
1387 }
1388
1389 pub fn unfollow(
1390 &mut self,
1391 pane: &ViewHandle<Pane>,
1392 cx: &mut ViewContext<Self>,
1393 ) -> Option<PeerId> {
1394 for (leader_id, states_by_pane) in &mut self.follower_states_by_leader {
1395 let leader_id = *leader_id;
1396 if let Some(state) = states_by_pane.remove(&pane) {
1397 for (_, item) in state.items_by_leader_view_id {
1398 if let FollowerItem::Loaded(item) = item {
1399 item.set_leader_replica_id(None, cx);
1400 }
1401 }
1402
1403 if states_by_pane.is_empty() {
1404 self.follower_states_by_leader.remove(&leader_id);
1405 if let Some(project_id) = self.project.read(cx).remote_id() {
1406 self.client
1407 .send(proto::Unfollow {
1408 project_id,
1409 leader_id: leader_id.0,
1410 })
1411 .log_err();
1412 }
1413 }
1414
1415 cx.notify();
1416 return Some(leader_id);
1417 }
1418 }
1419 None
1420 }
1421
1422 fn render_connection_status(&self, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1423 let theme = &cx.global::<Settings>().theme;
1424 match &*self.client.status().borrow() {
1425 client::Status::ConnectionError
1426 | client::Status::ConnectionLost
1427 | client::Status::Reauthenticating
1428 | client::Status::Reconnecting { .. }
1429 | client::Status::ReconnectionError { .. } => Some(
1430 Container::new(
1431 Align::new(
1432 ConstrainedBox::new(
1433 Svg::new("icons/offline-14.svg")
1434 .with_color(theme.workspace.titlebar.offline_icon.color)
1435 .boxed(),
1436 )
1437 .with_width(theme.workspace.titlebar.offline_icon.width)
1438 .boxed(),
1439 )
1440 .boxed(),
1441 )
1442 .with_style(theme.workspace.titlebar.offline_icon.container)
1443 .boxed(),
1444 ),
1445 client::Status::UpgradeRequired => Some(
1446 Label::new(
1447 "Please update Zed to collaborate".to_string(),
1448 theme.workspace.titlebar.outdated_warning.text.clone(),
1449 )
1450 .contained()
1451 .with_style(theme.workspace.titlebar.outdated_warning.container)
1452 .aligned()
1453 .boxed(),
1454 ),
1455 _ => None,
1456 }
1457 }
1458
1459 fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1460 ConstrainedBox::new(
1461 Container::new(
1462 Stack::new()
1463 .with_child(
1464 Align::new(
1465 Label::new("zed".into(), theme.workspace.titlebar.title.clone())
1466 .boxed(),
1467 )
1468 .boxed(),
1469 )
1470 .with_child(
1471 Align::new(
1472 Flex::row()
1473 .with_children(self.render_share_icon(theme, cx))
1474 .with_children(self.render_collaborators(theme, cx))
1475 .with_child(self.render_current_user(
1476 self.user_store.read(cx).current_user().as_ref(),
1477 self.project.read(cx).replica_id(),
1478 theme,
1479 cx,
1480 ))
1481 .with_children(self.render_connection_status(cx))
1482 .boxed(),
1483 )
1484 .right()
1485 .boxed(),
1486 )
1487 .boxed(),
1488 )
1489 .with_style(theme.workspace.titlebar.container)
1490 .boxed(),
1491 )
1492 .with_height(theme.workspace.titlebar.height)
1493 .named("titlebar")
1494 }
1495
1496 fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1497 let mut collaborators = self
1498 .project
1499 .read(cx)
1500 .collaborators()
1501 .values()
1502 .cloned()
1503 .collect::<Vec<_>>();
1504 collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1505 collaborators
1506 .into_iter()
1507 .filter_map(|collaborator| {
1508 Some(self.render_avatar(
1509 collaborator.user.avatar.clone()?,
1510 collaborator.replica_id,
1511 Some(collaborator.peer_id),
1512 theme,
1513 cx,
1514 ))
1515 })
1516 .collect()
1517 }
1518
1519 fn render_current_user(
1520 &self,
1521 user: Option<&Arc<User>>,
1522 replica_id: ReplicaId,
1523 theme: &Theme,
1524 cx: &mut RenderContext<Self>,
1525 ) -> ElementBox {
1526 if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1527 self.render_avatar(avatar, replica_id, None, theme, cx)
1528 } else {
1529 MouseEventHandler::new::<Authenticate, _, _>(0, cx, |state, _| {
1530 let style = if state.hovered {
1531 &theme.workspace.titlebar.hovered_sign_in_prompt
1532 } else {
1533 &theme.workspace.titlebar.sign_in_prompt
1534 };
1535 Label::new("Sign in".to_string(), style.text.clone())
1536 .contained()
1537 .with_style(style.container)
1538 .boxed()
1539 })
1540 .on_click(|cx| cx.dispatch_action(Authenticate))
1541 .with_cursor_style(CursorStyle::PointingHand)
1542 .aligned()
1543 .boxed()
1544 }
1545 }
1546
1547 fn render_avatar(
1548 &self,
1549 avatar: Arc<ImageData>,
1550 replica_id: ReplicaId,
1551 peer_id: Option<PeerId>,
1552 theme: &Theme,
1553 cx: &mut RenderContext<Self>,
1554 ) -> ElementBox {
1555 let replica_color = theme.editor.replica_selection_style(replica_id).cursor;
1556 let is_followed = peer_id.map_or(false, |peer_id| {
1557 self.follower_states_by_leader.contains_key(&peer_id)
1558 });
1559 let mut avatar_style = theme.workspace.titlebar.avatar;
1560 if is_followed {
1561 avatar_style.border = Border::all(1.0, replica_color);
1562 }
1563 let content = Stack::new()
1564 .with_child(
1565 Image::new(avatar)
1566 .with_style(avatar_style)
1567 .constrained()
1568 .with_width(theme.workspace.titlebar.avatar_width)
1569 .aligned()
1570 .boxed(),
1571 )
1572 .with_child(
1573 AvatarRibbon::new(replica_color)
1574 .constrained()
1575 .with_width(theme.workspace.titlebar.avatar_ribbon.width)
1576 .with_height(theme.workspace.titlebar.avatar_ribbon.height)
1577 .aligned()
1578 .bottom()
1579 .boxed(),
1580 )
1581 .constrained()
1582 .with_width(theme.workspace.right_sidebar.width)
1583 .boxed();
1584
1585 if let Some(peer_id) = peer_id {
1586 MouseEventHandler::new::<ToggleFollow, _, _>(replica_id.into(), cx, move |_, _| content)
1587 .with_cursor_style(CursorStyle::PointingHand)
1588 .on_click(move |cx| cx.dispatch_action(ToggleFollow(peer_id)))
1589 .boxed()
1590 } else {
1591 content
1592 }
1593 }
1594
1595 fn render_share_icon(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1596 if self.project().read(cx).is_local() && self.client.user_id().is_some() {
1597 let color = if self.project().read(cx).is_shared() {
1598 theme.workspace.titlebar.share_icon_active_color
1599 } else {
1600 theme.workspace.titlebar.share_icon_color
1601 };
1602 Some(
1603 MouseEventHandler::new::<ToggleShare, _, _>(0, cx, |_, _| {
1604 Align::new(
1605 Svg::new("icons/broadcast-24.svg")
1606 .with_color(color)
1607 .constrained()
1608 .with_width(24.)
1609 .boxed(),
1610 )
1611 .boxed()
1612 })
1613 .with_cursor_style(CursorStyle::PointingHand)
1614 .on_click(|cx| cx.dispatch_action(ToggleShare))
1615 .boxed(),
1616 )
1617 } else {
1618 None
1619 }
1620 }
1621
1622 fn render_disconnected_overlay(&self, cx: &AppContext) -> Option<ElementBox> {
1623 if self.project.read(cx).is_read_only() {
1624 let theme = &cx.global::<Settings>().theme;
1625 Some(
1626 EventHandler::new(
1627 Label::new(
1628 "Your connection to the remote project has been lost.".to_string(),
1629 theme.workspace.disconnected_overlay.text.clone(),
1630 )
1631 .aligned()
1632 .contained()
1633 .with_style(theme.workspace.disconnected_overlay.container)
1634 .boxed(),
1635 )
1636 .capture(|_, _, _| true)
1637 .boxed(),
1638 )
1639 } else {
1640 None
1641 }
1642 }
1643
1644 // RPC handlers
1645
1646 async fn handle_follow(
1647 this: ViewHandle<Self>,
1648 envelope: TypedEnvelope<proto::Follow>,
1649 _: Arc<Client>,
1650 mut cx: AsyncAppContext,
1651 ) -> Result<proto::FollowResponse> {
1652 this.update(&mut cx, |this, cx| {
1653 this.leader_state
1654 .followers
1655 .insert(envelope.original_sender_id()?);
1656
1657 let active_view_id = this
1658 .active_item(cx)
1659 .and_then(|i| i.to_followable_item_handle(cx))
1660 .map(|i| i.id() as u64);
1661 Ok(proto::FollowResponse {
1662 active_view_id,
1663 views: this
1664 .panes()
1665 .iter()
1666 .flat_map(|pane| {
1667 let leader_id = this.leader_for_pane(pane).map(|id| id.0);
1668 pane.read(cx).items().filter_map({
1669 let cx = &cx;
1670 move |item| {
1671 let id = item.id() as u64;
1672 let item = item.to_followable_item_handle(cx)?;
1673 let variant = item.to_state_proto(cx)?;
1674 Some(proto::View {
1675 id,
1676 leader_id,
1677 variant: Some(variant),
1678 })
1679 }
1680 })
1681 })
1682 .collect(),
1683 })
1684 })
1685 }
1686
1687 async fn handle_unfollow(
1688 this: ViewHandle<Self>,
1689 envelope: TypedEnvelope<proto::Unfollow>,
1690 _: Arc<Client>,
1691 mut cx: AsyncAppContext,
1692 ) -> Result<()> {
1693 this.update(&mut cx, |this, _| {
1694 this.leader_state
1695 .followers
1696 .remove(&envelope.original_sender_id()?);
1697 Ok(())
1698 })
1699 }
1700
1701 async fn handle_update_followers(
1702 this: ViewHandle<Self>,
1703 envelope: TypedEnvelope<proto::UpdateFollowers>,
1704 _: Arc<Client>,
1705 mut cx: AsyncAppContext,
1706 ) -> Result<()> {
1707 let leader_id = envelope.original_sender_id()?;
1708 match envelope
1709 .payload
1710 .variant
1711 .ok_or_else(|| anyhow!("invalid update"))?
1712 {
1713 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
1714 this.update(&mut cx, |this, cx| {
1715 this.update_leader_state(leader_id, cx, |state, _| {
1716 state.active_view_id = update_active_view.id;
1717 });
1718 Ok::<_, anyhow::Error>(())
1719 })
1720 }
1721 proto::update_followers::Variant::UpdateView(update_view) => {
1722 this.update(&mut cx, |this, cx| {
1723 let variant = update_view
1724 .variant
1725 .ok_or_else(|| anyhow!("missing update view variant"))?;
1726 this.update_leader_state(leader_id, cx, |state, cx| {
1727 let variant = variant.clone();
1728 match state
1729 .items_by_leader_view_id
1730 .entry(update_view.id)
1731 .or_insert(FollowerItem::Loading(Vec::new()))
1732 {
1733 FollowerItem::Loaded(item) => {
1734 item.apply_update_proto(variant, cx).log_err();
1735 }
1736 FollowerItem::Loading(updates) => updates.push(variant),
1737 }
1738 });
1739 Ok(())
1740 })
1741 }
1742 proto::update_followers::Variant::CreateView(view) => {
1743 let panes = this.read_with(&cx, |this, _| {
1744 this.follower_states_by_leader
1745 .get(&leader_id)
1746 .into_iter()
1747 .flat_map(|states_by_pane| states_by_pane.keys())
1748 .cloned()
1749 .collect()
1750 });
1751 Self::add_views_from_leader(this.clone(), leader_id, panes, vec![view], &mut cx)
1752 .await?;
1753 Ok(())
1754 }
1755 }
1756 .log_err();
1757
1758 Ok(())
1759 }
1760
1761 async fn add_views_from_leader(
1762 this: ViewHandle<Self>,
1763 leader_id: PeerId,
1764 panes: Vec<ViewHandle<Pane>>,
1765 views: Vec<proto::View>,
1766 cx: &mut AsyncAppContext,
1767 ) -> Result<()> {
1768 let project = this.read_with(cx, |this, _| this.project.clone());
1769 let replica_id = project
1770 .read_with(cx, |project, _| {
1771 project
1772 .collaborators()
1773 .get(&leader_id)
1774 .map(|c| c.replica_id)
1775 })
1776 .ok_or_else(|| anyhow!("no such collaborator {}", leader_id))?;
1777
1778 let item_builders = cx.update(|cx| {
1779 cx.default_global::<FollowableItemBuilders>()
1780 .values()
1781 .map(|b| b.0)
1782 .collect::<Vec<_>>()
1783 .clone()
1784 });
1785
1786 let mut item_tasks_by_pane = HashMap::default();
1787 for pane in panes {
1788 let mut item_tasks = Vec::new();
1789 let mut leader_view_ids = Vec::new();
1790 for view in &views {
1791 let mut variant = view.variant.clone();
1792 if variant.is_none() {
1793 Err(anyhow!("missing variant"))?;
1794 }
1795 for build_item in &item_builders {
1796 let task =
1797 cx.update(|cx| build_item(pane.clone(), project.clone(), &mut variant, cx));
1798 if let Some(task) = task {
1799 item_tasks.push(task);
1800 leader_view_ids.push(view.id);
1801 break;
1802 } else {
1803 assert!(variant.is_some());
1804 }
1805 }
1806 }
1807
1808 item_tasks_by_pane.insert(pane, (item_tasks, leader_view_ids));
1809 }
1810
1811 for (pane, (item_tasks, leader_view_ids)) in item_tasks_by_pane {
1812 let items = futures::future::try_join_all(item_tasks).await?;
1813 this.update(cx, |this, cx| {
1814 let state = this
1815 .follower_states_by_leader
1816 .get_mut(&leader_id)?
1817 .get_mut(&pane)?;
1818
1819 for (id, item) in leader_view_ids.into_iter().zip(items) {
1820 item.set_leader_replica_id(Some(replica_id), cx);
1821 match state.items_by_leader_view_id.entry(id) {
1822 hash_map::Entry::Occupied(e) => {
1823 let e = e.into_mut();
1824 if let FollowerItem::Loading(updates) = e {
1825 for update in updates.drain(..) {
1826 item.apply_update_proto(update, cx)
1827 .context("failed to apply view update")
1828 .log_err();
1829 }
1830 }
1831 *e = FollowerItem::Loaded(item);
1832 }
1833 hash_map::Entry::Vacant(e) => {
1834 e.insert(FollowerItem::Loaded(item));
1835 }
1836 }
1837 }
1838
1839 Some(())
1840 });
1841 }
1842 this.update(cx, |this, cx| this.leader_updated(leader_id, cx));
1843
1844 Ok(())
1845 }
1846
1847 fn update_followers(
1848 &self,
1849 update: proto::update_followers::Variant,
1850 cx: &AppContext,
1851 ) -> Option<()> {
1852 let project_id = self.project.read(cx).remote_id()?;
1853 if !self.leader_state.followers.is_empty() {
1854 self.client
1855 .send(proto::UpdateFollowers {
1856 project_id,
1857 follower_ids: self.leader_state.followers.iter().map(|f| f.0).collect(),
1858 variant: Some(update),
1859 })
1860 .log_err();
1861 }
1862 None
1863 }
1864
1865 pub fn leader_for_pane(&self, pane: &ViewHandle<Pane>) -> Option<PeerId> {
1866 self.follower_states_by_leader
1867 .iter()
1868 .find_map(|(leader_id, state)| {
1869 if state.contains_key(pane) {
1870 Some(*leader_id)
1871 } else {
1872 None
1873 }
1874 })
1875 }
1876
1877 fn update_leader_state(
1878 &mut self,
1879 leader_id: PeerId,
1880 cx: &mut ViewContext<Self>,
1881 mut update_fn: impl FnMut(&mut FollowerState, &mut ViewContext<Self>),
1882 ) {
1883 for (_, state) in self
1884 .follower_states_by_leader
1885 .get_mut(&leader_id)
1886 .into_iter()
1887 .flatten()
1888 {
1889 update_fn(state, cx);
1890 }
1891 self.leader_updated(leader_id, cx);
1892 }
1893
1894 fn leader_updated(&mut self, leader_id: PeerId, cx: &mut ViewContext<Self>) -> Option<()> {
1895 let mut items_to_add = Vec::new();
1896 for (pane, state) in self.follower_states_by_leader.get(&leader_id)? {
1897 if let Some(active_item) = state
1898 .active_view_id
1899 .and_then(|id| state.items_by_leader_view_id.get(&id))
1900 {
1901 if let FollowerItem::Loaded(item) = active_item {
1902 items_to_add.push((pane.clone(), item.boxed_clone()));
1903 }
1904 }
1905 }
1906
1907 for (pane, item) in items_to_add {
1908 Pane::add_item(self, pane.clone(), item.boxed_clone(), false, cx);
1909 if pane == self.active_pane {
1910 pane.update(cx, |pane, cx| pane.focus_active_item(cx));
1911 }
1912 cx.notify();
1913 }
1914 None
1915 }
1916}
1917
1918impl Entity for Workspace {
1919 type Event = ();
1920}
1921
1922impl View for Workspace {
1923 fn ui_name() -> &'static str {
1924 "Workspace"
1925 }
1926
1927 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1928 let theme = cx.global::<Settings>().theme.clone();
1929 Stack::new()
1930 .with_child(
1931 Flex::column()
1932 .with_child(self.render_titlebar(&theme, cx))
1933 .with_child(
1934 Stack::new()
1935 .with_child({
1936 let mut content = Flex::row();
1937 content.add_child(self.left_sidebar.render(&theme, cx));
1938 if let Some(element) =
1939 self.left_sidebar.render_active_item(&theme, cx)
1940 {
1941 content.add_child(Flexible::new(0.8, false, element).boxed());
1942 }
1943 content.add_child(
1944 Flex::column()
1945 .with_child(
1946 Flexible::new(
1947 1.,
1948 true,
1949 self.center.render(
1950 &theme,
1951 &self.follower_states_by_leader,
1952 self.project.read(cx).collaborators(),
1953 ),
1954 )
1955 .boxed(),
1956 )
1957 .with_child(ChildView::new(&self.status_bar).boxed())
1958 .flexible(1., true)
1959 .boxed(),
1960 );
1961 if let Some(element) =
1962 self.right_sidebar.render_active_item(&theme, cx)
1963 {
1964 content.add_child(Flexible::new(0.8, false, element).boxed());
1965 }
1966 content.add_child(self.right_sidebar.render(&theme, cx));
1967 content.boxed()
1968 })
1969 .with_children(self.modal.as_ref().map(|m| ChildView::new(m).boxed()))
1970 .flexible(1.0, true)
1971 .boxed(),
1972 )
1973 .contained()
1974 .with_background_color(theme.workspace.background)
1975 .boxed(),
1976 )
1977 .with_children(self.render_disconnected_overlay(cx))
1978 .named("workspace")
1979 }
1980
1981 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
1982 cx.focus(&self.active_pane);
1983 }
1984}
1985
1986pub trait WorkspaceHandle {
1987 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
1988}
1989
1990impl WorkspaceHandle for ViewHandle<Workspace> {
1991 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
1992 self.read(cx)
1993 .worktrees(cx)
1994 .flat_map(|worktree| {
1995 let worktree_id = worktree.read(cx).id();
1996 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
1997 worktree_id,
1998 path: f.path.clone(),
1999 })
2000 })
2001 .collect::<Vec<_>>()
2002 }
2003}
2004
2005pub struct AvatarRibbon {
2006 color: Color,
2007}
2008
2009impl AvatarRibbon {
2010 pub fn new(color: Color) -> AvatarRibbon {
2011 AvatarRibbon { color }
2012 }
2013}
2014
2015impl Element for AvatarRibbon {
2016 type LayoutState = ();
2017
2018 type PaintState = ();
2019
2020 fn layout(
2021 &mut self,
2022 constraint: gpui::SizeConstraint,
2023 _: &mut gpui::LayoutContext,
2024 ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
2025 (constraint.max, ())
2026 }
2027
2028 fn paint(
2029 &mut self,
2030 bounds: gpui::geometry::rect::RectF,
2031 _: gpui::geometry::rect::RectF,
2032 _: &mut Self::LayoutState,
2033 cx: &mut gpui::PaintContext,
2034 ) -> Self::PaintState {
2035 let mut path = PathBuilder::new();
2036 path.reset(bounds.lower_left());
2037 path.curve_to(
2038 bounds.origin() + vec2f(bounds.height(), 0.),
2039 bounds.origin(),
2040 );
2041 path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
2042 path.curve_to(bounds.lower_right(), bounds.upper_right());
2043 path.line_to(bounds.lower_left());
2044 cx.scene.push_path(path.build(self.color, None));
2045 }
2046
2047 fn dispatch_event(
2048 &mut self,
2049 _: &gpui::Event,
2050 _: gpui::geometry::rect::RectF,
2051 _: &mut Self::LayoutState,
2052 _: &mut Self::PaintState,
2053 _: &mut gpui::EventContext,
2054 ) -> bool {
2055 false
2056 }
2057
2058 fn debug(
2059 &self,
2060 bounds: gpui::geometry::rect::RectF,
2061 _: &Self::LayoutState,
2062 _: &Self::PaintState,
2063 _: &gpui::DebugContext,
2064 ) -> gpui::json::Value {
2065 json::json!({
2066 "type": "AvatarRibbon",
2067 "bounds": bounds.to_json(),
2068 "color": self.color.to_json(),
2069 })
2070 }
2071}
2072
2073impl std::fmt::Debug for OpenParams {
2074 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2075 f.debug_struct("OpenParams")
2076 .field("paths", &self.paths)
2077 .finish()
2078 }
2079}
2080
2081fn open(action: &Open, cx: &mut MutableAppContext) {
2082 let app_state = action.0.clone();
2083 let mut paths = cx.prompt_for_paths(PathPromptOptions {
2084 files: true,
2085 directories: true,
2086 multiple: true,
2087 });
2088 cx.spawn(|mut cx| async move {
2089 if let Some(paths) = paths.recv().await.flatten() {
2090 cx.update(|cx| cx.dispatch_global_action(OpenPaths(OpenParams { paths, app_state })));
2091 }
2092 })
2093 .detach();
2094}
2095
2096pub struct WorkspaceCreated(WeakViewHandle<Workspace>);
2097
2098pub fn open_paths(
2099 abs_paths: &[PathBuf],
2100 app_state: &Arc<AppState>,
2101 cx: &mut MutableAppContext,
2102) -> Task<ViewHandle<Workspace>> {
2103 log::info!("open paths {:?}", abs_paths);
2104
2105 // Open paths in existing workspace if possible
2106 let mut existing = None;
2107 for window_id in cx.window_ids().collect::<Vec<_>>() {
2108 if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
2109 if workspace_handle.update(cx, |workspace, cx| {
2110 if workspace.contains_paths(abs_paths, cx.as_ref()) {
2111 cx.activate_window(window_id);
2112 existing = Some(workspace_handle.clone());
2113 true
2114 } else {
2115 false
2116 }
2117 }) {
2118 break;
2119 }
2120 }
2121 }
2122
2123 let workspace = existing.unwrap_or_else(|| {
2124 cx.add_window((app_state.build_window_options)(), |cx| {
2125 let project = Project::local(
2126 app_state.client.clone(),
2127 app_state.user_store.clone(),
2128 app_state.languages.clone(),
2129 app_state.fs.clone(),
2130 cx,
2131 );
2132 (app_state.build_workspace)(project, &app_state, cx)
2133 })
2134 .1
2135 });
2136
2137 let task = workspace.update(cx, |workspace, cx| workspace.open_paths(abs_paths, cx));
2138 cx.spawn(|_| async move {
2139 task.await;
2140 workspace
2141 })
2142}
2143
2144pub fn join_project(
2145 project_id: u64,
2146 app_state: &Arc<AppState>,
2147 cx: &mut MutableAppContext,
2148) -> Task<Result<ViewHandle<Workspace>>> {
2149 for window_id in cx.window_ids().collect::<Vec<_>>() {
2150 if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
2151 if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
2152 return Task::ready(Ok(workspace));
2153 }
2154 }
2155 }
2156
2157 let app_state = app_state.clone();
2158 cx.spawn(|mut cx| async move {
2159 let project = Project::remote(
2160 project_id,
2161 app_state.client.clone(),
2162 app_state.user_store.clone(),
2163 app_state.languages.clone(),
2164 app_state.fs.clone(),
2165 &mut cx,
2166 )
2167 .await?;
2168 Ok(cx.update(|cx| {
2169 cx.add_window((app_state.build_window_options)(), |cx| {
2170 (app_state.build_workspace)(project, &app_state, cx)
2171 })
2172 .1
2173 }))
2174 })
2175}
2176
2177fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
2178 let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
2179 let project = Project::local(
2180 app_state.client.clone(),
2181 app_state.user_store.clone(),
2182 app_state.languages.clone(),
2183 app_state.fs.clone(),
2184 cx,
2185 );
2186 (app_state.build_workspace)(project, &app_state, cx)
2187 });
2188 cx.dispatch_action(window_id, vec![workspace.id()], &OpenNew(app_state.clone()));
2189}