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