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<(TypeId, usize, 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 id: usize,
1012 cx: &mut ViewContext<Self>,
1013 build_notification: impl FnOnce(&mut ViewContext<Self>) -> ViewHandle<V>,
1014 ) {
1015 let type_id = TypeId::of::<V>();
1016 if self
1017 .notifications
1018 .iter()
1019 .all(|(existing_type_id, existing_id, _)| {
1020 (*existing_type_id, *existing_id) != (type_id, id)
1021 })
1022 {
1023 let notification = build_notification(cx);
1024 cx.subscribe(¬ification, move |this, handle, event, cx| {
1025 if handle.read(cx).should_dismiss_notification_on_event(event) {
1026 this.dismiss_notification(type_id, id, cx);
1027 }
1028 })
1029 .detach();
1030 self.notifications
1031 .push((type_id, id, Box::new(notification)));
1032 cx.notify();
1033 }
1034 }
1035
1036 fn dismiss_notification(&mut self, type_id: TypeId, id: usize, cx: &mut ViewContext<Self>) {
1037 self.notifications
1038 .retain(|(existing_type_id, existing_id, _)| {
1039 if (*existing_type_id, *existing_id) == (type_id, id) {
1040 cx.notify();
1041 false
1042 } else {
1043 true
1044 }
1045 });
1046 }
1047
1048 pub fn items<'a>(
1049 &'a self,
1050 cx: &'a AppContext,
1051 ) -> impl 'a + Iterator<Item = &Box<dyn ItemHandle>> {
1052 self.panes.iter().flat_map(|pane| pane.read(cx).items())
1053 }
1054
1055 pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
1056 self.items_of_type(cx).max_by_key(|item| item.id())
1057 }
1058
1059 pub fn items_of_type<'a, T: Item>(
1060 &'a self,
1061 cx: &'a AppContext,
1062 ) -> impl 'a + Iterator<Item = ViewHandle<T>> {
1063 self.panes
1064 .iter()
1065 .flat_map(|pane| pane.read(cx).items_of_type())
1066 }
1067
1068 pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
1069 self.active_pane().read(cx).active_item()
1070 }
1071
1072 fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
1073 self.active_item(cx).and_then(|item| item.project_path(cx))
1074 }
1075
1076 pub fn save_active_item(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
1077 let project = self.project.clone();
1078 if let Some(item) = self.active_item(cx) {
1079 if item.can_save(cx) {
1080 if item.has_conflict(cx.as_ref()) {
1081 const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1082
1083 let mut answer = cx.prompt(
1084 PromptLevel::Warning,
1085 CONFLICT_MESSAGE,
1086 &["Overwrite", "Cancel"],
1087 );
1088 cx.spawn(|_, mut cx| async move {
1089 let answer = answer.recv().await;
1090 if answer == Some(0) {
1091 cx.update(|cx| item.save(project, cx)).await?;
1092 }
1093 Ok(())
1094 })
1095 } else {
1096 item.save(project, cx)
1097 }
1098 } else if item.can_save_as(cx) {
1099 let worktree = self.worktrees(cx).next();
1100 let start_abs_path = worktree
1101 .and_then(|w| w.read(cx).as_local())
1102 .map_or(Path::new(""), |w| w.abs_path())
1103 .to_path_buf();
1104 let mut abs_path = cx.prompt_for_new_path(&start_abs_path);
1105 cx.spawn(|_, mut cx| async move {
1106 if let Some(abs_path) = abs_path.recv().await.flatten() {
1107 cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
1108 }
1109 Ok(())
1110 })
1111 } else {
1112 Task::ready(Ok(()))
1113 }
1114 } else {
1115 Task::ready(Ok(()))
1116 }
1117 }
1118
1119 pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
1120 let sidebar = match action.side {
1121 Side::Left => &mut self.left_sidebar,
1122 Side::Right => &mut self.right_sidebar,
1123 };
1124 let active_item = sidebar.update(cx, |sidebar, cx| {
1125 sidebar.toggle_item(action.item_index, cx);
1126 sidebar.active_item().map(|item| item.to_any())
1127 });
1128 if let Some(active_item) = active_item {
1129 cx.focus(active_item);
1130 } else {
1131 cx.focus_self();
1132 }
1133 cx.notify();
1134 }
1135
1136 pub fn toggle_sidebar_item_focus(
1137 &mut self,
1138 action: &ToggleSidebarItemFocus,
1139 cx: &mut ViewContext<Self>,
1140 ) {
1141 let sidebar = match action.side {
1142 Side::Left => &mut self.left_sidebar,
1143 Side::Right => &mut self.right_sidebar,
1144 };
1145 let active_item = sidebar.update(cx, |sidebar, cx| {
1146 sidebar.activate_item(action.item_index, cx);
1147 sidebar.active_item().cloned()
1148 });
1149 if let Some(active_item) = active_item {
1150 if active_item.is_focused(cx) {
1151 cx.focus_self();
1152 } else {
1153 cx.focus(active_item.to_any());
1154 }
1155 }
1156 cx.notify();
1157 }
1158
1159 fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
1160 let pane = cx.add_view(|cx| Pane::new(cx));
1161 let pane_id = pane.id();
1162 cx.observe(&pane, move |me, _, cx| {
1163 let active_entry = me.active_project_path(cx);
1164 me.project
1165 .update(cx, |project, cx| project.set_active_path(active_entry, cx));
1166 })
1167 .detach();
1168 cx.subscribe(&pane, move |me, _, event, cx| {
1169 me.handle_pane_event(pane_id, event, cx)
1170 })
1171 .detach();
1172 self.panes.push(pane.clone());
1173 self.activate_pane(pane.clone(), cx);
1174 cx.emit(Event::PaneAdded(pane.clone()));
1175 pane
1176 }
1177
1178 pub fn add_item(&mut self, item: Box<dyn ItemHandle>, cx: &mut ViewContext<Self>) {
1179 let pane = self.active_pane().clone();
1180 Pane::add_item(self, pane, item, true, true, cx);
1181 }
1182
1183 pub fn open_path(
1184 &mut self,
1185 path: impl Into<ProjectPath>,
1186 focus_item: bool,
1187 cx: &mut ViewContext<Self>,
1188 ) -> Task<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>> {
1189 let pane = self.active_pane().downgrade();
1190 let task = self.load_path(path.into(), cx);
1191 cx.spawn(|this, mut cx| async move {
1192 let (project_entry_id, build_item) = task.await?;
1193 let pane = pane
1194 .upgrade(&cx)
1195 .ok_or_else(|| anyhow!("pane was closed"))?;
1196 this.update(&mut cx, |this, cx| {
1197 Ok(Pane::open_item(
1198 this,
1199 pane,
1200 project_entry_id,
1201 focus_item,
1202 cx,
1203 build_item,
1204 ))
1205 })
1206 })
1207 }
1208
1209 pub(crate) fn load_path(
1210 &mut self,
1211 path: ProjectPath,
1212 cx: &mut ViewContext<Self>,
1213 ) -> Task<
1214 Result<(
1215 ProjectEntryId,
1216 impl 'static + FnOnce(&mut MutableAppContext) -> Box<dyn ItemHandle>,
1217 )>,
1218 > {
1219 let project = self.project().clone();
1220 let project_item = project.update(cx, |project, cx| project.open_path(path, cx));
1221 let window_id = cx.window_id();
1222 cx.as_mut().spawn(|mut cx| async move {
1223 let (project_entry_id, project_item) = project_item.await?;
1224 let build_item = cx.update(|cx| {
1225 cx.default_global::<ProjectItemBuilders>()
1226 .get(&project_item.model_type())
1227 .ok_or_else(|| anyhow!("no item builder for project item"))
1228 .cloned()
1229 })?;
1230 let build_item =
1231 move |cx: &mut MutableAppContext| build_item(window_id, project, project_item, cx);
1232 Ok((project_entry_id, build_item))
1233 })
1234 }
1235
1236 pub fn open_project_item<T>(
1237 &mut self,
1238 project_item: ModelHandle<T::Item>,
1239 cx: &mut ViewContext<Self>,
1240 ) -> ViewHandle<T>
1241 where
1242 T: ProjectItem,
1243 {
1244 use project::Item as _;
1245
1246 let entry_id = project_item.read(cx).entry_id(cx);
1247 if let Some(item) = entry_id
1248 .and_then(|entry_id| self.active_pane().read(cx).item_for_entry(entry_id, cx))
1249 .and_then(|item| item.downcast())
1250 {
1251 self.activate_item(&item, cx);
1252 return item;
1253 }
1254
1255 let item = cx.add_view(|cx| T::for_project_item(self.project().clone(), project_item, cx));
1256 self.add_item(Box::new(item.clone()), cx);
1257 item
1258 }
1259
1260 pub fn activate_item(&mut self, item: &dyn ItemHandle, cx: &mut ViewContext<Self>) -> bool {
1261 let result = self.panes.iter().find_map(|pane| {
1262 if let Some(ix) = pane.read(cx).index_for_item(item) {
1263 Some((pane.clone(), ix))
1264 } else {
1265 None
1266 }
1267 });
1268 if let Some((pane, ix)) = result {
1269 self.activate_pane(pane.clone(), cx);
1270 pane.update(cx, |pane, cx| pane.activate_item(ix, true, true, cx));
1271 true
1272 } else {
1273 false
1274 }
1275 }
1276
1277 pub fn activate_next_pane(&mut self, cx: &mut ViewContext<Self>) {
1278 let next_pane = {
1279 let panes = self.center.panes();
1280 let ix = panes
1281 .iter()
1282 .position(|pane| **pane == self.active_pane)
1283 .unwrap();
1284 let next_ix = (ix + 1) % panes.len();
1285 panes[next_ix].clone()
1286 };
1287 self.activate_pane(next_pane, cx);
1288 }
1289
1290 pub fn activate_previous_pane(&mut self, cx: &mut ViewContext<Self>) {
1291 let prev_pane = {
1292 let panes = self.center.panes();
1293 let ix = panes
1294 .iter()
1295 .position(|pane| **pane == self.active_pane)
1296 .unwrap();
1297 let prev_ix = if ix == 0 { panes.len() - 1 } else { ix - 1 };
1298 panes[prev_ix].clone()
1299 };
1300 self.activate_pane(prev_pane, cx);
1301 }
1302
1303 fn activate_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1304 if self.active_pane != pane {
1305 self.active_pane = pane.clone();
1306 self.status_bar.update(cx, |status_bar, cx| {
1307 status_bar.set_active_pane(&self.active_pane, cx);
1308 });
1309 cx.focus(&self.active_pane);
1310 cx.notify();
1311 }
1312
1313 self.update_followers(
1314 proto::update_followers::Variant::UpdateActiveView(proto::UpdateActiveView {
1315 id: self.active_item(cx).map(|item| item.id() as u64),
1316 leader_id: self.leader_for_pane(&pane).map(|id| id.0),
1317 }),
1318 cx,
1319 );
1320 }
1321
1322 fn handle_pane_event(
1323 &mut self,
1324 pane_id: usize,
1325 event: &pane::Event,
1326 cx: &mut ViewContext<Self>,
1327 ) {
1328 if let Some(pane) = self.pane(pane_id) {
1329 match event {
1330 pane::Event::Split(direction) => {
1331 self.split_pane(pane, *direction, cx);
1332 }
1333 pane::Event::Remove => {
1334 self.remove_pane(pane, cx);
1335 }
1336 pane::Event::Activate => {
1337 self.activate_pane(pane, cx);
1338 }
1339 pane::Event::ActivateItem { local } => {
1340 if *local {
1341 self.unfollow(&pane, cx);
1342 }
1343 }
1344 }
1345 } else {
1346 error!("pane {} not found", pane_id);
1347 }
1348 }
1349
1350 pub fn split_pane(
1351 &mut self,
1352 pane: ViewHandle<Pane>,
1353 direction: SplitDirection,
1354 cx: &mut ViewContext<Self>,
1355 ) -> ViewHandle<Pane> {
1356 let new_pane = self.add_pane(cx);
1357 self.activate_pane(new_pane.clone(), cx);
1358 if let Some(item) = pane.read(cx).active_item() {
1359 if let Some(clone) = item.clone_on_split(cx.as_mut()) {
1360 Pane::add_item(self, new_pane.clone(), clone, true, true, cx);
1361 }
1362 }
1363 self.center.split(&pane, &new_pane, direction).unwrap();
1364 cx.notify();
1365 new_pane
1366 }
1367
1368 fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1369 if self.center.remove(&pane).unwrap() {
1370 self.panes.retain(|p| p != &pane);
1371 self.activate_pane(self.panes.last().unwrap().clone(), cx);
1372 self.unfollow(&pane, cx);
1373 self.last_leaders_by_pane.remove(&pane.downgrade());
1374 cx.notify();
1375 }
1376 }
1377
1378 pub fn panes(&self) -> &[ViewHandle<Pane>] {
1379 &self.panes
1380 }
1381
1382 fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1383 self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1384 }
1385
1386 pub fn active_pane(&self) -> &ViewHandle<Pane> {
1387 &self.active_pane
1388 }
1389
1390 fn project_remote_id_changed(&mut self, remote_id: Option<u64>, cx: &mut ViewContext<Self>) {
1391 if let Some(remote_id) = remote_id {
1392 self.remote_entity_subscription =
1393 Some(self.client.add_view_for_remote_entity(remote_id, cx));
1394 } else {
1395 self.remote_entity_subscription.take();
1396 }
1397 }
1398
1399 fn collaborator_left(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
1400 self.leader_state.followers.remove(&peer_id);
1401 if let Some(states_by_pane) = self.follower_states_by_leader.remove(&peer_id) {
1402 for state in states_by_pane.into_values() {
1403 for item in state.items_by_leader_view_id.into_values() {
1404 if let FollowerItem::Loaded(item) = item {
1405 item.set_leader_replica_id(None, cx);
1406 }
1407 }
1408 }
1409 }
1410 cx.notify();
1411 }
1412
1413 pub fn toggle_follow(
1414 &mut self,
1415 ToggleFollow(leader_id): &ToggleFollow,
1416 cx: &mut ViewContext<Self>,
1417 ) -> Option<Task<Result<()>>> {
1418 let leader_id = *leader_id;
1419 let pane = self.active_pane().clone();
1420
1421 if let Some(prev_leader_id) = self.unfollow(&pane, cx) {
1422 if leader_id == prev_leader_id {
1423 return None;
1424 }
1425 }
1426
1427 self.last_leaders_by_pane
1428 .insert(pane.downgrade(), leader_id);
1429 self.follower_states_by_leader
1430 .entry(leader_id)
1431 .or_default()
1432 .insert(pane.clone(), Default::default());
1433 cx.notify();
1434
1435 let project_id = self.project.read(cx).remote_id()?;
1436 let request = self.client.request(proto::Follow {
1437 project_id,
1438 leader_id: leader_id.0,
1439 });
1440 Some(cx.spawn_weak(|this, mut cx| async move {
1441 let response = request.await?;
1442 if let Some(this) = this.upgrade(&cx) {
1443 this.update(&mut cx, |this, _| {
1444 let state = this
1445 .follower_states_by_leader
1446 .get_mut(&leader_id)
1447 .and_then(|states_by_pane| states_by_pane.get_mut(&pane))
1448 .ok_or_else(|| anyhow!("following interrupted"))?;
1449 state.active_view_id = response.active_view_id;
1450 Ok::<_, anyhow::Error>(())
1451 })?;
1452 Self::add_views_from_leader(this, leader_id, vec![pane], response.views, &mut cx)
1453 .await?;
1454 }
1455 Ok(())
1456 }))
1457 }
1458
1459 pub fn follow_next_collaborator(
1460 &mut self,
1461 _: &FollowNextCollaborator,
1462 cx: &mut ViewContext<Self>,
1463 ) -> Option<Task<Result<()>>> {
1464 let collaborators = self.project.read(cx).collaborators();
1465 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
1466 let mut collaborators = collaborators.keys().copied();
1467 while let Some(peer_id) = collaborators.next() {
1468 if peer_id == leader_id {
1469 break;
1470 }
1471 }
1472 collaborators.next()
1473 } else if let Some(last_leader_id) =
1474 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
1475 {
1476 if collaborators.contains_key(last_leader_id) {
1477 Some(*last_leader_id)
1478 } else {
1479 None
1480 }
1481 } else {
1482 None
1483 };
1484
1485 next_leader_id
1486 .or_else(|| collaborators.keys().copied().next())
1487 .and_then(|leader_id| self.toggle_follow(&ToggleFollow(leader_id), cx))
1488 }
1489
1490 pub fn unfollow(
1491 &mut self,
1492 pane: &ViewHandle<Pane>,
1493 cx: &mut ViewContext<Self>,
1494 ) -> Option<PeerId> {
1495 for (leader_id, states_by_pane) in &mut self.follower_states_by_leader {
1496 let leader_id = *leader_id;
1497 if let Some(state) = states_by_pane.remove(&pane) {
1498 for (_, item) in state.items_by_leader_view_id {
1499 if let FollowerItem::Loaded(item) = item {
1500 item.set_leader_replica_id(None, cx);
1501 }
1502 }
1503
1504 if states_by_pane.is_empty() {
1505 self.follower_states_by_leader.remove(&leader_id);
1506 if let Some(project_id) = self.project.read(cx).remote_id() {
1507 self.client
1508 .send(proto::Unfollow {
1509 project_id,
1510 leader_id: leader_id.0,
1511 })
1512 .log_err();
1513 }
1514 }
1515
1516 cx.notify();
1517 return Some(leader_id);
1518 }
1519 }
1520 None
1521 }
1522
1523 fn render_connection_status(&self, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1524 let theme = &cx.global::<Settings>().theme;
1525 match &*self.client.status().borrow() {
1526 client::Status::ConnectionError
1527 | client::Status::ConnectionLost
1528 | client::Status::Reauthenticating
1529 | client::Status::Reconnecting { .. }
1530 | client::Status::ReconnectionError { .. } => Some(
1531 Container::new(
1532 Align::new(
1533 ConstrainedBox::new(
1534 Svg::new("icons/offline-14.svg")
1535 .with_color(theme.workspace.titlebar.offline_icon.color)
1536 .boxed(),
1537 )
1538 .with_width(theme.workspace.titlebar.offline_icon.width)
1539 .boxed(),
1540 )
1541 .boxed(),
1542 )
1543 .with_style(theme.workspace.titlebar.offline_icon.container)
1544 .boxed(),
1545 ),
1546 client::Status::UpgradeRequired => Some(
1547 Label::new(
1548 "Please update Zed to collaborate".to_string(),
1549 theme.workspace.titlebar.outdated_warning.text.clone(),
1550 )
1551 .contained()
1552 .with_style(theme.workspace.titlebar.outdated_warning.container)
1553 .aligned()
1554 .boxed(),
1555 ),
1556 _ => None,
1557 }
1558 }
1559
1560 fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1561 let mut worktree_root_names = String::new();
1562 {
1563 let mut worktrees = self.project.read(cx).visible_worktrees(cx).peekable();
1564 while let Some(worktree) = worktrees.next() {
1565 worktree_root_names.push_str(worktree.read(cx).root_name());
1566 if worktrees.peek().is_some() {
1567 worktree_root_names.push_str(", ");
1568 }
1569 }
1570 }
1571
1572 ConstrainedBox::new(
1573 Container::new(
1574 Stack::new()
1575 .with_child(
1576 Label::new(worktree_root_names, theme.workspace.titlebar.title.clone())
1577 .aligned()
1578 .left()
1579 .boxed(),
1580 )
1581 .with_child(
1582 Align::new(
1583 Flex::row()
1584 .with_children(self.render_collaborators(theme, cx))
1585 .with_children(self.render_current_user(
1586 self.user_store.read(cx).current_user().as_ref(),
1587 self.project.read(cx).replica_id(),
1588 theme,
1589 cx,
1590 ))
1591 .with_children(self.render_connection_status(cx))
1592 .boxed(),
1593 )
1594 .right()
1595 .boxed(),
1596 )
1597 .boxed(),
1598 )
1599 .with_style(theme.workspace.titlebar.container)
1600 .boxed(),
1601 )
1602 .with_height(theme.workspace.titlebar.height)
1603 .named("titlebar")
1604 }
1605
1606 fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1607 let mut collaborators = self
1608 .project
1609 .read(cx)
1610 .collaborators()
1611 .values()
1612 .cloned()
1613 .collect::<Vec<_>>();
1614 collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1615 collaborators
1616 .into_iter()
1617 .filter_map(|collaborator| {
1618 Some(self.render_avatar(
1619 collaborator.user.avatar.clone()?,
1620 collaborator.replica_id,
1621 Some(collaborator.peer_id),
1622 theme,
1623 cx,
1624 ))
1625 })
1626 .collect()
1627 }
1628
1629 fn render_current_user(
1630 &self,
1631 user: Option<&Arc<User>>,
1632 replica_id: ReplicaId,
1633 theme: &Theme,
1634 cx: &mut RenderContext<Self>,
1635 ) -> Option<ElementBox> {
1636 let status = *self.client.status().borrow();
1637 if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1638 Some(self.render_avatar(avatar, replica_id, None, theme, cx))
1639 } else if matches!(status, client::Status::UpgradeRequired) {
1640 None
1641 } else {
1642 Some(
1643 MouseEventHandler::new::<Authenticate, _, _>(0, cx, |state, _| {
1644 let style = theme
1645 .workspace
1646 .titlebar
1647 .sign_in_prompt
1648 .style_for(state, false);
1649 Label::new("Sign in".to_string(), style.text.clone())
1650 .contained()
1651 .with_style(style.container)
1652 .boxed()
1653 })
1654 .on_click(|_, cx| cx.dispatch_action(Authenticate))
1655 .with_cursor_style(CursorStyle::PointingHand)
1656 .aligned()
1657 .boxed(),
1658 )
1659 }
1660 }
1661
1662 fn render_avatar(
1663 &self,
1664 avatar: Arc<ImageData>,
1665 replica_id: ReplicaId,
1666 peer_id: Option<PeerId>,
1667 theme: &Theme,
1668 cx: &mut RenderContext<Self>,
1669 ) -> ElementBox {
1670 let replica_color = theme.editor.replica_selection_style(replica_id).cursor;
1671 let is_followed = peer_id.map_or(false, |peer_id| {
1672 self.follower_states_by_leader.contains_key(&peer_id)
1673 });
1674 let mut avatar_style = theme.workspace.titlebar.avatar;
1675 if is_followed {
1676 avatar_style.border = Border::all(1.0, replica_color);
1677 }
1678 let content = Stack::new()
1679 .with_child(
1680 Image::new(avatar)
1681 .with_style(avatar_style)
1682 .constrained()
1683 .with_width(theme.workspace.titlebar.avatar_width)
1684 .aligned()
1685 .boxed(),
1686 )
1687 .with_child(
1688 AvatarRibbon::new(replica_color)
1689 .constrained()
1690 .with_width(theme.workspace.titlebar.avatar_ribbon.width)
1691 .with_height(theme.workspace.titlebar.avatar_ribbon.height)
1692 .aligned()
1693 .bottom()
1694 .boxed(),
1695 )
1696 .constrained()
1697 .with_width(theme.workspace.titlebar.avatar_width)
1698 .contained()
1699 .with_margin_left(theme.workspace.titlebar.avatar_margin)
1700 .boxed();
1701
1702 if let Some(peer_id) = peer_id {
1703 MouseEventHandler::new::<ToggleFollow, _, _>(replica_id.into(), cx, move |_, _| content)
1704 .with_cursor_style(CursorStyle::PointingHand)
1705 .on_click(move |_, cx| cx.dispatch_action(ToggleFollow(peer_id)))
1706 .boxed()
1707 } else {
1708 content
1709 }
1710 }
1711
1712 fn render_disconnected_overlay(&self, cx: &AppContext) -> Option<ElementBox> {
1713 if self.project.read(cx).is_read_only() {
1714 let theme = &cx.global::<Settings>().theme;
1715 Some(
1716 EventHandler::new(
1717 Label::new(
1718 "Your connection to the remote project has been lost.".to_string(),
1719 theme.workspace.disconnected_overlay.text.clone(),
1720 )
1721 .aligned()
1722 .contained()
1723 .with_style(theme.workspace.disconnected_overlay.container)
1724 .boxed(),
1725 )
1726 .capture(|_, _, _| true)
1727 .boxed(),
1728 )
1729 } else {
1730 None
1731 }
1732 }
1733
1734 fn render_notifications(&self, theme: &theme::Workspace) -> Option<ElementBox> {
1735 if self.notifications.is_empty() {
1736 None
1737 } else {
1738 Some(
1739 Flex::column()
1740 .with_children(self.notifications.iter().map(|(_, _, notification)| {
1741 ChildView::new(notification.as_ref())
1742 .contained()
1743 .with_style(theme.notification)
1744 .boxed()
1745 }))
1746 .constrained()
1747 .with_width(theme.notifications.width)
1748 .contained()
1749 .with_style(theme.notifications.container)
1750 .aligned()
1751 .bottom()
1752 .right()
1753 .boxed(),
1754 )
1755 }
1756 }
1757
1758 // RPC handlers
1759
1760 async fn handle_follow(
1761 this: ViewHandle<Self>,
1762 envelope: TypedEnvelope<proto::Follow>,
1763 _: Arc<Client>,
1764 mut cx: AsyncAppContext,
1765 ) -> Result<proto::FollowResponse> {
1766 this.update(&mut cx, |this, cx| {
1767 this.leader_state
1768 .followers
1769 .insert(envelope.original_sender_id()?);
1770
1771 let active_view_id = this
1772 .active_item(cx)
1773 .and_then(|i| i.to_followable_item_handle(cx))
1774 .map(|i| i.id() as u64);
1775 Ok(proto::FollowResponse {
1776 active_view_id,
1777 views: this
1778 .panes()
1779 .iter()
1780 .flat_map(|pane| {
1781 let leader_id = this.leader_for_pane(pane).map(|id| id.0);
1782 pane.read(cx).items().filter_map({
1783 let cx = &cx;
1784 move |item| {
1785 let id = item.id() as u64;
1786 let item = item.to_followable_item_handle(cx)?;
1787 let variant = item.to_state_proto(cx)?;
1788 Some(proto::View {
1789 id,
1790 leader_id,
1791 variant: Some(variant),
1792 })
1793 }
1794 })
1795 })
1796 .collect(),
1797 })
1798 })
1799 }
1800
1801 async fn handle_unfollow(
1802 this: ViewHandle<Self>,
1803 envelope: TypedEnvelope<proto::Unfollow>,
1804 _: Arc<Client>,
1805 mut cx: AsyncAppContext,
1806 ) -> Result<()> {
1807 this.update(&mut cx, |this, _| {
1808 this.leader_state
1809 .followers
1810 .remove(&envelope.original_sender_id()?);
1811 Ok(())
1812 })
1813 }
1814
1815 async fn handle_update_followers(
1816 this: ViewHandle<Self>,
1817 envelope: TypedEnvelope<proto::UpdateFollowers>,
1818 _: Arc<Client>,
1819 mut cx: AsyncAppContext,
1820 ) -> Result<()> {
1821 let leader_id = envelope.original_sender_id()?;
1822 match envelope
1823 .payload
1824 .variant
1825 .ok_or_else(|| anyhow!("invalid update"))?
1826 {
1827 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
1828 this.update(&mut cx, |this, cx| {
1829 this.update_leader_state(leader_id, cx, |state, _| {
1830 state.active_view_id = update_active_view.id;
1831 });
1832 Ok::<_, anyhow::Error>(())
1833 })
1834 }
1835 proto::update_followers::Variant::UpdateView(update_view) => {
1836 this.update(&mut cx, |this, cx| {
1837 let variant = update_view
1838 .variant
1839 .ok_or_else(|| anyhow!("missing update view variant"))?;
1840 this.update_leader_state(leader_id, cx, |state, cx| {
1841 let variant = variant.clone();
1842 match state
1843 .items_by_leader_view_id
1844 .entry(update_view.id)
1845 .or_insert(FollowerItem::Loading(Vec::new()))
1846 {
1847 FollowerItem::Loaded(item) => {
1848 item.apply_update_proto(variant, cx).log_err();
1849 }
1850 FollowerItem::Loading(updates) => updates.push(variant),
1851 }
1852 });
1853 Ok(())
1854 })
1855 }
1856 proto::update_followers::Variant::CreateView(view) => {
1857 let panes = this.read_with(&cx, |this, _| {
1858 this.follower_states_by_leader
1859 .get(&leader_id)
1860 .into_iter()
1861 .flat_map(|states_by_pane| states_by_pane.keys())
1862 .cloned()
1863 .collect()
1864 });
1865 Self::add_views_from_leader(this.clone(), leader_id, panes, vec![view], &mut cx)
1866 .await?;
1867 Ok(())
1868 }
1869 }
1870 .log_err();
1871
1872 Ok(())
1873 }
1874
1875 async fn add_views_from_leader(
1876 this: ViewHandle<Self>,
1877 leader_id: PeerId,
1878 panes: Vec<ViewHandle<Pane>>,
1879 views: Vec<proto::View>,
1880 cx: &mut AsyncAppContext,
1881 ) -> Result<()> {
1882 let project = this.read_with(cx, |this, _| this.project.clone());
1883 let replica_id = project
1884 .read_with(cx, |project, _| {
1885 project
1886 .collaborators()
1887 .get(&leader_id)
1888 .map(|c| c.replica_id)
1889 })
1890 .ok_or_else(|| anyhow!("no such collaborator {}", leader_id))?;
1891
1892 let item_builders = cx.update(|cx| {
1893 cx.default_global::<FollowableItemBuilders>()
1894 .values()
1895 .map(|b| b.0)
1896 .collect::<Vec<_>>()
1897 .clone()
1898 });
1899
1900 let mut item_tasks_by_pane = HashMap::default();
1901 for pane in panes {
1902 let mut item_tasks = Vec::new();
1903 let mut leader_view_ids = Vec::new();
1904 for view in &views {
1905 let mut variant = view.variant.clone();
1906 if variant.is_none() {
1907 Err(anyhow!("missing variant"))?;
1908 }
1909 for build_item in &item_builders {
1910 let task =
1911 cx.update(|cx| build_item(pane.clone(), project.clone(), &mut variant, cx));
1912 if let Some(task) = task {
1913 item_tasks.push(task);
1914 leader_view_ids.push(view.id);
1915 break;
1916 } else {
1917 assert!(variant.is_some());
1918 }
1919 }
1920 }
1921
1922 item_tasks_by_pane.insert(pane, (item_tasks, leader_view_ids));
1923 }
1924
1925 for (pane, (item_tasks, leader_view_ids)) in item_tasks_by_pane {
1926 let items = futures::future::try_join_all(item_tasks).await?;
1927 this.update(cx, |this, cx| {
1928 let state = this
1929 .follower_states_by_leader
1930 .get_mut(&leader_id)?
1931 .get_mut(&pane)?;
1932
1933 for (id, item) in leader_view_ids.into_iter().zip(items) {
1934 item.set_leader_replica_id(Some(replica_id), cx);
1935 match state.items_by_leader_view_id.entry(id) {
1936 hash_map::Entry::Occupied(e) => {
1937 let e = e.into_mut();
1938 if let FollowerItem::Loading(updates) = e {
1939 for update in updates.drain(..) {
1940 item.apply_update_proto(update, cx)
1941 .context("failed to apply view update")
1942 .log_err();
1943 }
1944 }
1945 *e = FollowerItem::Loaded(item);
1946 }
1947 hash_map::Entry::Vacant(e) => {
1948 e.insert(FollowerItem::Loaded(item));
1949 }
1950 }
1951 }
1952
1953 Some(())
1954 });
1955 }
1956 this.update(cx, |this, cx| this.leader_updated(leader_id, cx));
1957
1958 Ok(())
1959 }
1960
1961 fn update_followers(
1962 &self,
1963 update: proto::update_followers::Variant,
1964 cx: &AppContext,
1965 ) -> Option<()> {
1966 let project_id = self.project.read(cx).remote_id()?;
1967 if !self.leader_state.followers.is_empty() {
1968 self.client
1969 .send(proto::UpdateFollowers {
1970 project_id,
1971 follower_ids: self.leader_state.followers.iter().map(|f| f.0).collect(),
1972 variant: Some(update),
1973 })
1974 .log_err();
1975 }
1976 None
1977 }
1978
1979 pub fn leader_for_pane(&self, pane: &ViewHandle<Pane>) -> Option<PeerId> {
1980 self.follower_states_by_leader
1981 .iter()
1982 .find_map(|(leader_id, state)| {
1983 if state.contains_key(pane) {
1984 Some(*leader_id)
1985 } else {
1986 None
1987 }
1988 })
1989 }
1990
1991 fn update_leader_state(
1992 &mut self,
1993 leader_id: PeerId,
1994 cx: &mut ViewContext<Self>,
1995 mut update_fn: impl FnMut(&mut FollowerState, &mut ViewContext<Self>),
1996 ) {
1997 for (_, state) in self
1998 .follower_states_by_leader
1999 .get_mut(&leader_id)
2000 .into_iter()
2001 .flatten()
2002 {
2003 update_fn(state, cx);
2004 }
2005 self.leader_updated(leader_id, cx);
2006 }
2007
2008 fn leader_updated(&mut self, leader_id: PeerId, cx: &mut ViewContext<Self>) -> Option<()> {
2009 let mut items_to_add = Vec::new();
2010 for (pane, state) in self.follower_states_by_leader.get(&leader_id)? {
2011 if let Some(active_item) = state
2012 .active_view_id
2013 .and_then(|id| state.items_by_leader_view_id.get(&id))
2014 {
2015 if let FollowerItem::Loaded(item) = active_item {
2016 items_to_add.push((pane.clone(), item.boxed_clone()));
2017 }
2018 }
2019 }
2020
2021 for (pane, item) in items_to_add {
2022 Pane::add_item(self, pane.clone(), item.boxed_clone(), false, false, cx);
2023 if pane == self.active_pane {
2024 pane.update(cx, |pane, cx| pane.focus_active_item(cx));
2025 }
2026 cx.notify();
2027 }
2028 None
2029 }
2030}
2031
2032impl Entity for Workspace {
2033 type Event = Event;
2034}
2035
2036impl View for Workspace {
2037 fn ui_name() -> &'static str {
2038 "Workspace"
2039 }
2040
2041 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
2042 let theme = cx.global::<Settings>().theme.clone();
2043 Stack::new()
2044 .with_child(
2045 Flex::column()
2046 .with_child(self.render_titlebar(&theme, cx))
2047 .with_child(
2048 Stack::new()
2049 .with_child({
2050 Flex::row()
2051 .with_children(
2052 if self.left_sidebar.read(cx).active_item().is_some() {
2053 Some(
2054 ChildView::new(&self.left_sidebar)
2055 .flex(0.8, false)
2056 .boxed(),
2057 )
2058 } else {
2059 None
2060 },
2061 )
2062 .with_child(
2063 FlexItem::new(self.center.render(
2064 &theme,
2065 &self.follower_states_by_leader,
2066 self.project.read(cx).collaborators(),
2067 ))
2068 .flex(1., true)
2069 .boxed(),
2070 )
2071 .with_children(
2072 if self.right_sidebar.read(cx).active_item().is_some() {
2073 Some(
2074 ChildView::new(&self.right_sidebar)
2075 .flex(0.8, false)
2076 .boxed(),
2077 )
2078 } else {
2079 None
2080 },
2081 )
2082 .boxed()
2083 })
2084 .with_children(self.modal.as_ref().map(|m| {
2085 ChildView::new(m)
2086 .contained()
2087 .with_style(theme.workspace.modal)
2088 .aligned()
2089 .top()
2090 .boxed()
2091 }))
2092 .with_children(self.render_notifications(&theme.workspace))
2093 .flex(1.0, true)
2094 .boxed(),
2095 )
2096 .with_child(ChildView::new(&self.status_bar).boxed())
2097 .contained()
2098 .with_background_color(theme.workspace.background)
2099 .boxed(),
2100 )
2101 .with_children(self.render_disconnected_overlay(cx))
2102 .named("workspace")
2103 }
2104
2105 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
2106 cx.focus(&self.active_pane);
2107 }
2108}
2109
2110pub trait WorkspaceHandle {
2111 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
2112}
2113
2114impl WorkspaceHandle for ViewHandle<Workspace> {
2115 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
2116 self.read(cx)
2117 .worktrees(cx)
2118 .flat_map(|worktree| {
2119 let worktree_id = worktree.read(cx).id();
2120 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
2121 worktree_id,
2122 path: f.path.clone(),
2123 })
2124 })
2125 .collect::<Vec<_>>()
2126 }
2127}
2128
2129pub struct AvatarRibbon {
2130 color: Color,
2131}
2132
2133impl AvatarRibbon {
2134 pub fn new(color: Color) -> AvatarRibbon {
2135 AvatarRibbon { color }
2136 }
2137}
2138
2139impl Element for AvatarRibbon {
2140 type LayoutState = ();
2141
2142 type PaintState = ();
2143
2144 fn layout(
2145 &mut self,
2146 constraint: gpui::SizeConstraint,
2147 _: &mut gpui::LayoutContext,
2148 ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
2149 (constraint.max, ())
2150 }
2151
2152 fn paint(
2153 &mut self,
2154 bounds: gpui::geometry::rect::RectF,
2155 _: gpui::geometry::rect::RectF,
2156 _: &mut Self::LayoutState,
2157 cx: &mut gpui::PaintContext,
2158 ) -> Self::PaintState {
2159 let mut path = PathBuilder::new();
2160 path.reset(bounds.lower_left());
2161 path.curve_to(
2162 bounds.origin() + vec2f(bounds.height(), 0.),
2163 bounds.origin(),
2164 );
2165 path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
2166 path.curve_to(bounds.lower_right(), bounds.upper_right());
2167 path.line_to(bounds.lower_left());
2168 cx.scene.push_path(path.build(self.color, None));
2169 }
2170
2171 fn dispatch_event(
2172 &mut self,
2173 _: &gpui::Event,
2174 _: RectF,
2175 _: RectF,
2176 _: &mut Self::LayoutState,
2177 _: &mut Self::PaintState,
2178 _: &mut gpui::EventContext,
2179 ) -> bool {
2180 false
2181 }
2182
2183 fn debug(
2184 &self,
2185 bounds: gpui::geometry::rect::RectF,
2186 _: &Self::LayoutState,
2187 _: &Self::PaintState,
2188 _: &gpui::DebugContext,
2189 ) -> gpui::json::Value {
2190 json::json!({
2191 "type": "AvatarRibbon",
2192 "bounds": bounds.to_json(),
2193 "color": self.color.to_json(),
2194 })
2195 }
2196}
2197
2198impl std::fmt::Debug for OpenPaths {
2199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2200 f.debug_struct("OpenPaths")
2201 .field("paths", &self.paths)
2202 .finish()
2203 }
2204}
2205
2206fn open(action: &Open, cx: &mut MutableAppContext) {
2207 let app_state = action.0.clone();
2208 let mut paths = cx.prompt_for_paths(PathPromptOptions {
2209 files: true,
2210 directories: true,
2211 multiple: true,
2212 });
2213 cx.spawn(|mut cx| async move {
2214 if let Some(paths) = paths.recv().await.flatten() {
2215 cx.update(|cx| cx.dispatch_global_action(OpenPaths { paths, app_state }));
2216 }
2217 })
2218 .detach();
2219}
2220
2221pub struct WorkspaceCreated(WeakViewHandle<Workspace>);
2222
2223pub fn open_paths(
2224 abs_paths: &[PathBuf],
2225 app_state: &Arc<AppState>,
2226 cx: &mut MutableAppContext,
2227) -> Task<(
2228 ViewHandle<Workspace>,
2229 Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>,
2230)> {
2231 log::info!("open paths {:?}", abs_paths);
2232
2233 // Open paths in existing workspace if possible
2234 let mut existing = None;
2235 for window_id in cx.window_ids().collect::<Vec<_>>() {
2236 if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
2237 if workspace_handle.update(cx, |workspace, cx| {
2238 if workspace.contains_paths(abs_paths, cx.as_ref()) {
2239 cx.activate_window(window_id);
2240 existing = Some(workspace_handle.clone());
2241 true
2242 } else {
2243 false
2244 }
2245 }) {
2246 break;
2247 }
2248 }
2249 }
2250
2251 let app_state = app_state.clone();
2252 let abs_paths = abs_paths.to_vec();
2253 cx.spawn(|mut cx| async move {
2254 let workspace = if let Some(existing) = existing {
2255 existing
2256 } else {
2257 let contains_directory =
2258 futures::future::join_all(abs_paths.iter().map(|path| app_state.fs.is_file(path)))
2259 .await
2260 .contains(&false);
2261
2262 cx.add_window((app_state.build_window_options)(), |cx| {
2263 let project = Project::local(
2264 app_state.client.clone(),
2265 app_state.user_store.clone(),
2266 app_state.languages.clone(),
2267 app_state.fs.clone(),
2268 cx,
2269 );
2270 let mut workspace = (app_state.build_workspace)(project, &app_state, cx);
2271 if contains_directory {
2272 workspace.toggle_sidebar_item(
2273 &ToggleSidebarItem {
2274 side: Side::Left,
2275 item_index: 0,
2276 },
2277 cx,
2278 );
2279 }
2280 workspace
2281 })
2282 .1
2283 };
2284
2285 let items = workspace
2286 .update(&mut cx, |workspace, cx| workspace.open_paths(abs_paths, cx))
2287 .await;
2288 (workspace, items)
2289 })
2290}
2291
2292pub fn join_project(
2293 contact: Arc<Contact>,
2294 project_index: usize,
2295 app_state: &Arc<AppState>,
2296 cx: &mut MutableAppContext,
2297) {
2298 let project_id = contact.projects[project_index].id;
2299
2300 for window_id in cx.window_ids().collect::<Vec<_>>() {
2301 if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
2302 if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
2303 cx.activate_window(window_id);
2304 return;
2305 }
2306 }
2307 }
2308
2309 cx.add_window((app_state.build_window_options)(), |cx| {
2310 WaitingRoom::new(contact, project_index, app_state.clone(), cx)
2311 });
2312}
2313
2314fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
2315 let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
2316 let project = Project::local(
2317 app_state.client.clone(),
2318 app_state.user_store.clone(),
2319 app_state.languages.clone(),
2320 app_state.fs.clone(),
2321 cx,
2322 );
2323 (app_state.build_workspace)(project, &app_state, cx)
2324 });
2325 cx.dispatch_action(window_id, vec![workspace.id()], &OpenNew(app_state.clone()));
2326}