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