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