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