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