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 println!("Active Pane Focused");
2480 cx.focus(&self.active_pane);
2481 }
2482 }
2483}
2484
2485pub trait WorkspaceHandle {
2486 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
2487}
2488
2489impl WorkspaceHandle for ViewHandle<Workspace> {
2490 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
2491 self.read(cx)
2492 .worktrees(cx)
2493 .flat_map(|worktree| {
2494 let worktree_id = worktree.read(cx).id();
2495 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
2496 worktree_id,
2497 path: f.path.clone(),
2498 })
2499 })
2500 .collect::<Vec<_>>()
2501 }
2502}
2503
2504pub struct AvatarRibbon {
2505 color: Color,
2506}
2507
2508impl AvatarRibbon {
2509 pub fn new(color: Color) -> AvatarRibbon {
2510 AvatarRibbon { color }
2511 }
2512}
2513
2514impl Element for AvatarRibbon {
2515 type LayoutState = ();
2516
2517 type PaintState = ();
2518
2519 fn layout(
2520 &mut self,
2521 constraint: gpui::SizeConstraint,
2522 _: &mut gpui::LayoutContext,
2523 ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
2524 (constraint.max, ())
2525 }
2526
2527 fn paint(
2528 &mut self,
2529 bounds: gpui::geometry::rect::RectF,
2530 _: gpui::geometry::rect::RectF,
2531 _: &mut Self::LayoutState,
2532 cx: &mut gpui::PaintContext,
2533 ) -> Self::PaintState {
2534 let mut path = PathBuilder::new();
2535 path.reset(bounds.lower_left());
2536 path.curve_to(
2537 bounds.origin() + vec2f(bounds.height(), 0.),
2538 bounds.origin(),
2539 );
2540 path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
2541 path.curve_to(bounds.lower_right(), bounds.upper_right());
2542 path.line_to(bounds.lower_left());
2543 cx.scene.push_path(path.build(self.color, None));
2544 }
2545
2546 fn dispatch_event(
2547 &mut self,
2548 _: &gpui::Event,
2549 _: RectF,
2550 _: RectF,
2551 _: &mut Self::LayoutState,
2552 _: &mut Self::PaintState,
2553 _: &mut gpui::EventContext,
2554 ) -> bool {
2555 false
2556 }
2557
2558 fn rect_for_text_range(
2559 &self,
2560 _: Range<usize>,
2561 _: RectF,
2562 _: RectF,
2563 _: &Self::LayoutState,
2564 _: &Self::PaintState,
2565 _: &gpui::MeasurementContext,
2566 ) -> Option<RectF> {
2567 None
2568 }
2569
2570 fn debug(
2571 &self,
2572 bounds: gpui::geometry::rect::RectF,
2573 _: &Self::LayoutState,
2574 _: &Self::PaintState,
2575 _: &gpui::DebugContext,
2576 ) -> gpui::json::Value {
2577 json::json!({
2578 "type": "AvatarRibbon",
2579 "bounds": bounds.to_json(),
2580 "color": self.color.to_json(),
2581 })
2582 }
2583}
2584
2585impl std::fmt::Debug for OpenPaths {
2586 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2587 f.debug_struct("OpenPaths")
2588 .field("paths", &self.paths)
2589 .finish()
2590 }
2591}
2592
2593fn open(_: &Open, cx: &mut MutableAppContext) {
2594 let mut paths = cx.prompt_for_paths(PathPromptOptions {
2595 files: true,
2596 directories: true,
2597 multiple: true,
2598 });
2599 cx.spawn(|mut cx| async move {
2600 if let Some(paths) = paths.recv().await.flatten() {
2601 cx.update(|cx| cx.dispatch_global_action(OpenPaths { paths }));
2602 }
2603 })
2604 .detach();
2605}
2606
2607pub struct WorkspaceCreated(WeakViewHandle<Workspace>);
2608
2609pub fn activate_workspace_for_project(
2610 cx: &mut MutableAppContext,
2611 predicate: impl Fn(&mut Project, &mut ModelContext<Project>) -> bool,
2612) -> Option<ViewHandle<Workspace>> {
2613 for window_id in cx.window_ids().collect::<Vec<_>>() {
2614 if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
2615 let project = workspace_handle.read(cx).project.clone();
2616 if project.update(cx, &predicate) {
2617 cx.activate_window(window_id);
2618 return Some(workspace_handle);
2619 }
2620 }
2621 }
2622 None
2623}
2624
2625pub fn open_paths(
2626 abs_paths: &[PathBuf],
2627 app_state: &Arc<AppState>,
2628 cx: &mut MutableAppContext,
2629) -> Task<(
2630 ViewHandle<Workspace>,
2631 Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>,
2632)> {
2633 log::info!("open paths {:?}", abs_paths);
2634
2635 // Open paths in existing workspace if possible
2636 let existing =
2637 activate_workspace_for_project(cx, |project, cx| project.contains_paths(abs_paths, cx));
2638
2639 let app_state = app_state.clone();
2640 let abs_paths = abs_paths.to_vec();
2641 cx.spawn(|mut cx| async move {
2642 let mut new_project = None;
2643 let workspace = if let Some(existing) = existing {
2644 existing
2645 } else {
2646 let contains_directory =
2647 futures::future::join_all(abs_paths.iter().map(|path| app_state.fs.is_file(path)))
2648 .await
2649 .contains(&false);
2650
2651 cx.add_window((app_state.build_window_options)(), |cx| {
2652 let project = Project::local(
2653 false,
2654 app_state.client.clone(),
2655 app_state.user_store.clone(),
2656 app_state.project_store.clone(),
2657 app_state.languages.clone(),
2658 app_state.fs.clone(),
2659 cx,
2660 );
2661 new_project = Some(project.clone());
2662 let mut workspace = Workspace::new(project, cx);
2663 (app_state.initialize_workspace)(&mut workspace, &app_state, cx);
2664 if contains_directory {
2665 workspace.toggle_sidebar(Side::Left, cx);
2666 }
2667 workspace
2668 })
2669 .1
2670 };
2671
2672 let items = workspace
2673 .update(&mut cx, |workspace, cx| {
2674 workspace.open_paths(abs_paths, true, cx)
2675 })
2676 .await;
2677
2678 if let Some(project) = new_project {
2679 project
2680 .update(&mut cx, |project, cx| project.restore_state(cx))
2681 .await
2682 .log_err();
2683 }
2684
2685 (workspace, items)
2686 })
2687}
2688
2689pub fn join_project(
2690 contact: Arc<Contact>,
2691 project_index: usize,
2692 app_state: &Arc<AppState>,
2693 cx: &mut MutableAppContext,
2694) {
2695 let project_id = contact.projects[project_index].id;
2696
2697 for window_id in cx.window_ids().collect::<Vec<_>>() {
2698 if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
2699 if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
2700 cx.activate_window(window_id);
2701 return;
2702 }
2703 }
2704 }
2705
2706 cx.add_window((app_state.build_window_options)(), |cx| {
2707 WaitingRoom::new(contact, project_index, app_state.clone(), cx)
2708 });
2709}
2710
2711fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
2712 let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
2713 let mut workspace = Workspace::new(
2714 Project::local(
2715 false,
2716 app_state.client.clone(),
2717 app_state.user_store.clone(),
2718 app_state.project_store.clone(),
2719 app_state.languages.clone(),
2720 app_state.fs.clone(),
2721 cx,
2722 ),
2723 cx,
2724 );
2725 (app_state.initialize_workspace)(&mut workspace, app_state, cx);
2726 workspace
2727 });
2728 cx.dispatch_action_at(window_id, workspace.id(), NewFile);
2729}
2730
2731#[cfg(test)]
2732mod tests {
2733 use std::cell::Cell;
2734
2735 use super::*;
2736 use gpui::{executor::Deterministic, ModelHandle, TestAppContext, ViewContext};
2737 use project::{FakeFs, Project, ProjectEntryId};
2738 use serde_json::json;
2739
2740 #[gpui::test]
2741 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
2742 cx.foreground().forbid_parking();
2743 Settings::test_async(cx);
2744
2745 let fs = FakeFs::new(cx.background());
2746 let project = Project::test(fs, [], cx).await;
2747 let (_, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2748
2749 // Adding an item with no ambiguity renders the tab without detail.
2750 let item1 = cx.add_view(&workspace, |_| {
2751 let mut item = TestItem::new();
2752 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
2753 item
2754 });
2755 workspace.update(cx, |workspace, cx| {
2756 workspace.add_item(Box::new(item1.clone()), cx);
2757 });
2758 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), None));
2759
2760 // Adding an item that creates ambiguity increases the level of detail on
2761 // both tabs.
2762 let item2 = cx.add_view(&workspace, |_| {
2763 let mut item = TestItem::new();
2764 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
2765 item
2766 });
2767 workspace.update(cx, |workspace, cx| {
2768 workspace.add_item(Box::new(item2.clone()), cx);
2769 });
2770 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2771 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2772
2773 // Adding an item that creates ambiguity increases the level of detail only
2774 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
2775 // we stop at the highest detail available.
2776 let item3 = cx.add_view(&workspace, |_| {
2777 let mut item = TestItem::new();
2778 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
2779 item
2780 });
2781 workspace.update(cx, |workspace, cx| {
2782 workspace.add_item(Box::new(item3.clone()), cx);
2783 });
2784 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2785 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
2786 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
2787 }
2788
2789 #[gpui::test]
2790 async fn test_tracking_active_path(cx: &mut TestAppContext) {
2791 cx.foreground().forbid_parking();
2792 Settings::test_async(cx);
2793 let fs = FakeFs::new(cx.background());
2794 fs.insert_tree(
2795 "/root1",
2796 json!({
2797 "one.txt": "",
2798 "two.txt": "",
2799 }),
2800 )
2801 .await;
2802 fs.insert_tree(
2803 "/root2",
2804 json!({
2805 "three.txt": "",
2806 }),
2807 )
2808 .await;
2809
2810 let project = Project::test(fs, ["root1".as_ref()], cx).await;
2811 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2812 let worktree_id = project.read_with(cx, |project, cx| {
2813 project.worktrees(cx).next().unwrap().read(cx).id()
2814 });
2815
2816 let item1 = cx.add_view(&workspace, |_| {
2817 let mut item = TestItem::new();
2818 item.project_path = Some((worktree_id, "one.txt").into());
2819 item
2820 });
2821 let item2 = cx.add_view(&workspace, |_| {
2822 let mut item = TestItem::new();
2823 item.project_path = Some((worktree_id, "two.txt").into());
2824 item
2825 });
2826
2827 // Add an item to an empty pane
2828 workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item1), cx));
2829 project.read_with(cx, |project, cx| {
2830 assert_eq!(
2831 project.active_entry(),
2832 project
2833 .entry_for_path(&(worktree_id, "one.txt").into(), cx)
2834 .map(|e| e.id)
2835 );
2836 });
2837 assert_eq!(
2838 cx.current_window_title(window_id).as_deref(),
2839 Some("one.txt — root1")
2840 );
2841
2842 // Add a second item to a non-empty pane
2843 workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item2), cx));
2844 assert_eq!(
2845 cx.current_window_title(window_id).as_deref(),
2846 Some("two.txt — root1")
2847 );
2848 project.read_with(cx, |project, cx| {
2849 assert_eq!(
2850 project.active_entry(),
2851 project
2852 .entry_for_path(&(worktree_id, "two.txt").into(), cx)
2853 .map(|e| e.id)
2854 );
2855 });
2856
2857 // Close the active item
2858 workspace
2859 .update(cx, |workspace, cx| {
2860 Pane::close_active_item(workspace, &Default::default(), cx).unwrap()
2861 })
2862 .await
2863 .unwrap();
2864 assert_eq!(
2865 cx.current_window_title(window_id).as_deref(),
2866 Some("one.txt — root1")
2867 );
2868 project.read_with(cx, |project, cx| {
2869 assert_eq!(
2870 project.active_entry(),
2871 project
2872 .entry_for_path(&(worktree_id, "one.txt").into(), cx)
2873 .map(|e| e.id)
2874 );
2875 });
2876
2877 // Add a project folder
2878 project
2879 .update(cx, |project, cx| {
2880 project.find_or_create_local_worktree("/root2", true, cx)
2881 })
2882 .await
2883 .unwrap();
2884 assert_eq!(
2885 cx.current_window_title(window_id).as_deref(),
2886 Some("one.txt — root1, root2")
2887 );
2888
2889 // Remove a project folder
2890 project.update(cx, |project, cx| {
2891 project.remove_worktree(worktree_id, cx);
2892 });
2893 assert_eq!(
2894 cx.current_window_title(window_id).as_deref(),
2895 Some("one.txt — root2")
2896 );
2897 }
2898
2899 #[gpui::test]
2900 async fn test_close_window(cx: &mut TestAppContext) {
2901 cx.foreground().forbid_parking();
2902 Settings::test_async(cx);
2903 let fs = FakeFs::new(cx.background());
2904 fs.insert_tree("/root", json!({ "one": "" })).await;
2905
2906 let project = Project::test(fs, ["root".as_ref()], cx).await;
2907 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2908
2909 // When there are no dirty items, there's nothing to do.
2910 let item1 = cx.add_view(&workspace, |_| TestItem::new());
2911 workspace.update(cx, |w, cx| w.add_item(Box::new(item1.clone()), cx));
2912 let task = workspace.update(cx, |w, cx| w.prepare_to_close(cx));
2913 assert_eq!(task.await.unwrap(), true);
2914
2915 // When there are dirty untitled items, prompt to save each one. If the user
2916 // cancels any prompt, then abort.
2917 let item2 = cx.add_view(&workspace, |_| {
2918 let mut item = TestItem::new();
2919 item.is_dirty = true;
2920 item
2921 });
2922 let item3 = cx.add_view(&workspace, |_| {
2923 let mut item = TestItem::new();
2924 item.is_dirty = true;
2925 item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
2926 item
2927 });
2928 workspace.update(cx, |w, cx| {
2929 w.add_item(Box::new(item2.clone()), cx);
2930 w.add_item(Box::new(item3.clone()), cx);
2931 });
2932 let task = workspace.update(cx, |w, cx| w.prepare_to_close(cx));
2933 cx.foreground().run_until_parked();
2934 cx.simulate_prompt_answer(window_id, 2 /* cancel */);
2935 cx.foreground().run_until_parked();
2936 assert!(!cx.has_pending_prompt(window_id));
2937 assert_eq!(task.await.unwrap(), false);
2938 }
2939
2940 #[gpui::test]
2941 async fn test_close_pane_items(cx: &mut TestAppContext) {
2942 cx.foreground().forbid_parking();
2943 Settings::test_async(cx);
2944 let fs = FakeFs::new(cx.background());
2945
2946 let project = Project::test(fs, None, cx).await;
2947 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
2948
2949 let item1 = cx.add_view(&workspace, |_| {
2950 let mut item = TestItem::new();
2951 item.is_dirty = true;
2952 item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
2953 item
2954 });
2955 let item2 = cx.add_view(&workspace, |_| {
2956 let mut item = TestItem::new();
2957 item.is_dirty = true;
2958 item.has_conflict = true;
2959 item.project_entry_ids = vec![ProjectEntryId::from_proto(2)];
2960 item
2961 });
2962 let item3 = cx.add_view(&workspace, |_| {
2963 let mut item = TestItem::new();
2964 item.is_dirty = true;
2965 item.has_conflict = true;
2966 item.project_entry_ids = vec![ProjectEntryId::from_proto(3)];
2967 item
2968 });
2969 let item4 = cx.add_view(&workspace, |_| {
2970 let mut item = TestItem::new();
2971 item.is_dirty = true;
2972 item
2973 });
2974 let pane = workspace.update(cx, |workspace, cx| {
2975 workspace.add_item(Box::new(item1.clone()), cx);
2976 workspace.add_item(Box::new(item2.clone()), cx);
2977 workspace.add_item(Box::new(item3.clone()), cx);
2978 workspace.add_item(Box::new(item4.clone()), cx);
2979 workspace.active_pane().clone()
2980 });
2981
2982 let close_items = workspace.update(cx, |workspace, cx| {
2983 pane.update(cx, |pane, cx| {
2984 pane.activate_item(1, true, true, false, cx);
2985 assert_eq!(pane.active_item().unwrap().id(), item2.id());
2986 });
2987
2988 let item1_id = item1.id();
2989 let item3_id = item3.id();
2990 let item4_id = item4.id();
2991 Pane::close_items(workspace, pane.clone(), cx, move |id| {
2992 [item1_id, item3_id, item4_id].contains(&id)
2993 })
2994 });
2995
2996 cx.foreground().run_until_parked();
2997 pane.read_with(cx, |pane, _| {
2998 assert_eq!(pane.items().count(), 4);
2999 assert_eq!(pane.active_item().unwrap().id(), item1.id());
3000 });
3001
3002 cx.simulate_prompt_answer(window_id, 0);
3003 cx.foreground().run_until_parked();
3004 pane.read_with(cx, |pane, cx| {
3005 assert_eq!(item1.read(cx).save_count, 1);
3006 assert_eq!(item1.read(cx).save_as_count, 0);
3007 assert_eq!(item1.read(cx).reload_count, 0);
3008 assert_eq!(pane.items().count(), 3);
3009 assert_eq!(pane.active_item().unwrap().id(), item3.id());
3010 });
3011
3012 cx.simulate_prompt_answer(window_id, 1);
3013 cx.foreground().run_until_parked();
3014 pane.read_with(cx, |pane, cx| {
3015 assert_eq!(item3.read(cx).save_count, 0);
3016 assert_eq!(item3.read(cx).save_as_count, 0);
3017 assert_eq!(item3.read(cx).reload_count, 1);
3018 assert_eq!(pane.items().count(), 2);
3019 assert_eq!(pane.active_item().unwrap().id(), item4.id());
3020 });
3021
3022 cx.simulate_prompt_answer(window_id, 0);
3023 cx.foreground().run_until_parked();
3024 cx.simulate_new_path_selection(|_| Some(Default::default()));
3025 close_items.await.unwrap();
3026 pane.read_with(cx, |pane, cx| {
3027 assert_eq!(item4.read(cx).save_count, 0);
3028 assert_eq!(item4.read(cx).save_as_count, 1);
3029 assert_eq!(item4.read(cx).reload_count, 0);
3030 assert_eq!(pane.items().count(), 1);
3031 assert_eq!(pane.active_item().unwrap().id(), item2.id());
3032 });
3033 }
3034
3035 #[gpui::test]
3036 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
3037 cx.foreground().forbid_parking();
3038 Settings::test_async(cx);
3039 let fs = FakeFs::new(cx.background());
3040
3041 let project = Project::test(fs, [], cx).await;
3042 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
3043
3044 // Create several workspace items with single project entries, and two
3045 // workspace items with multiple project entries.
3046 let single_entry_items = (0..=4)
3047 .map(|project_entry_id| {
3048 let mut item = TestItem::new();
3049 item.is_dirty = true;
3050 item.project_entry_ids = vec![ProjectEntryId::from_proto(project_entry_id)];
3051 item.is_singleton = true;
3052 item
3053 })
3054 .collect::<Vec<_>>();
3055 let item_2_3 = {
3056 let mut item = TestItem::new();
3057 item.is_dirty = true;
3058 item.is_singleton = false;
3059 item.project_entry_ids =
3060 vec![ProjectEntryId::from_proto(2), ProjectEntryId::from_proto(3)];
3061 item
3062 };
3063 let item_3_4 = {
3064 let mut item = TestItem::new();
3065 item.is_dirty = true;
3066 item.is_singleton = false;
3067 item.project_entry_ids =
3068 vec![ProjectEntryId::from_proto(3), ProjectEntryId::from_proto(4)];
3069 item
3070 };
3071
3072 // Create two panes that contain the following project entries:
3073 // left pane:
3074 // multi-entry items: (2, 3)
3075 // single-entry items: 0, 1, 2, 3, 4
3076 // right pane:
3077 // single-entry items: 1
3078 // multi-entry items: (3, 4)
3079 let left_pane = workspace.update(cx, |workspace, cx| {
3080 let left_pane = workspace.active_pane().clone();
3081 workspace.add_item(Box::new(cx.add_view(|_| item_2_3.clone())), cx);
3082 for item in &single_entry_items {
3083 workspace.add_item(Box::new(cx.add_view(|_| item.clone())), cx);
3084 }
3085 left_pane.update(cx, |pane, cx| {
3086 pane.activate_item(2, true, true, false, cx);
3087 });
3088
3089 workspace
3090 .split_pane(left_pane.clone(), SplitDirection::Right, cx)
3091 .unwrap();
3092 workspace.add_item(Box::new(cx.add_view(|_| item_3_4.clone())), cx);
3093
3094 left_pane
3095 });
3096
3097 // When closing all of the items in the left pane, we should be prompted twice:
3098 // once for project entry 0, and once for project entry 2. After those two
3099 // prompts, the task should complete.
3100 let close = workspace.update(cx, |workspace, cx| {
3101 cx.focus(left_pane.clone());
3102 Pane::close_items(workspace, left_pane.clone(), cx, |_| true)
3103 });
3104
3105 cx.foreground().run_until_parked();
3106 left_pane.read_with(cx, |pane, cx| {
3107 assert_eq!(
3108 pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
3109 &[ProjectEntryId::from_proto(0)]
3110 );
3111 });
3112 cx.simulate_prompt_answer(window_id, 0);
3113
3114 cx.foreground().run_until_parked();
3115 left_pane.read_with(cx, |pane, cx| {
3116 assert_eq!(
3117 pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
3118 &[ProjectEntryId::from_proto(2)]
3119 );
3120 });
3121 cx.simulate_prompt_answer(window_id, 0);
3122
3123 cx.foreground().run_until_parked();
3124 close.await.unwrap();
3125 left_pane.read_with(cx, |pane, _| {
3126 assert_eq!(pane.items().count(), 0);
3127 });
3128 }
3129
3130 #[gpui::test]
3131 async fn test_autosave(deterministic: Arc<Deterministic>, cx: &mut gpui::TestAppContext) {
3132 deterministic.forbid_parking();
3133
3134 Settings::test_async(cx);
3135 let fs = FakeFs::new(cx.background());
3136
3137 let project = Project::test(fs, [], cx).await;
3138 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
3139
3140 let item = cx.add_view(&workspace, |_| {
3141 let mut item = TestItem::new();
3142 item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3143 item
3144 });
3145 let item_id = item.id();
3146 workspace.update(cx, |workspace, cx| {
3147 workspace.add_item(Box::new(item.clone()), cx);
3148 });
3149
3150 // Autosave on window change.
3151 item.update(cx, |item, cx| {
3152 cx.update_global(|settings: &mut Settings, _| {
3153 settings.autosave = Autosave::OnWindowChange;
3154 });
3155 item.is_dirty = true;
3156 });
3157
3158 // Deactivating the window saves the file.
3159 cx.simulate_window_activation(None);
3160 deterministic.run_until_parked();
3161 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
3162
3163 // Autosave on focus change.
3164 item.update(cx, |item, cx| {
3165 cx.focus_self();
3166 cx.update_global(|settings: &mut Settings, _| {
3167 settings.autosave = Autosave::OnFocusChange;
3168 });
3169 item.is_dirty = true;
3170 });
3171
3172 // Blurring the item saves the file.
3173 item.update(cx, |_, cx| cx.blur());
3174 deterministic.run_until_parked();
3175 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
3176
3177 // Deactivating the window still saves the file.
3178 cx.simulate_window_activation(Some(window_id));
3179 item.update(cx, |item, cx| {
3180 cx.focus_self();
3181 item.is_dirty = true;
3182 });
3183 cx.simulate_window_activation(None);
3184
3185 deterministic.run_until_parked();
3186 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
3187
3188 // Autosave after delay.
3189 item.update(cx, |item, cx| {
3190 cx.update_global(|settings: &mut Settings, _| {
3191 settings.autosave = Autosave::AfterDelay { milliseconds: 500 };
3192 });
3193 item.is_dirty = true;
3194 cx.emit(TestItemEvent::Edit);
3195 });
3196
3197 // Delay hasn't fully expired, so the file is still dirty and unsaved.
3198 deterministic.advance_clock(Duration::from_millis(250));
3199 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
3200
3201 // After delay expires, the file is saved.
3202 deterministic.advance_clock(Duration::from_millis(250));
3203 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
3204
3205 // Autosave on focus change, ensuring closing the tab counts as such.
3206 item.update(cx, |item, cx| {
3207 cx.update_global(|settings: &mut Settings, _| {
3208 settings.autosave = Autosave::OnFocusChange;
3209 });
3210 item.is_dirty = true;
3211 });
3212
3213 workspace
3214 .update(cx, |workspace, cx| {
3215 let pane = workspace.active_pane().clone();
3216 Pane::close_items(workspace, pane, cx, move |id| id == item_id)
3217 })
3218 .await
3219 .unwrap();
3220 assert!(!cx.has_pending_prompt(window_id));
3221 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3222
3223 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
3224 workspace.update(cx, |workspace, cx| {
3225 workspace.add_item(Box::new(item.clone()), cx);
3226 });
3227 item.update(cx, |item, cx| {
3228 item.project_entry_ids = Default::default();
3229 item.is_dirty = true;
3230 cx.blur();
3231 });
3232 deterministic.run_until_parked();
3233 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3234
3235 // Ensure autosave is prevented for deleted files also when closing the buffer.
3236 let _close_items = workspace.update(cx, |workspace, cx| {
3237 let pane = workspace.active_pane().clone();
3238 Pane::close_items(workspace, pane, cx, move |id| id == item_id)
3239 });
3240 deterministic.run_until_parked();
3241 assert!(cx.has_pending_prompt(window_id));
3242 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3243 }
3244
3245 #[gpui::test]
3246 async fn test_pane_navigation(
3247 deterministic: Arc<Deterministic>,
3248 cx: &mut gpui::TestAppContext,
3249 ) {
3250 deterministic.forbid_parking();
3251 Settings::test_async(cx);
3252 let fs = FakeFs::new(cx.background());
3253
3254 let project = Project::test(fs, [], cx).await;
3255 let (_, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
3256
3257 let item = cx.add_view(&workspace, |_| {
3258 let mut item = TestItem::new();
3259 item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3260 item
3261 });
3262 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
3263 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
3264 let toolbar_notify_count = Rc::new(RefCell::new(0));
3265
3266 workspace.update(cx, |workspace, cx| {
3267 workspace.add_item(Box::new(item.clone()), cx);
3268 let toolbar_notification_count = toolbar_notify_count.clone();
3269 cx.observe(&toolbar, move |_, _, _| {
3270 *toolbar_notification_count.borrow_mut() += 1
3271 })
3272 .detach();
3273 });
3274
3275 pane.read_with(cx, |pane, _| {
3276 assert!(!pane.can_navigate_backward());
3277 assert!(!pane.can_navigate_forward());
3278 });
3279
3280 item.update(cx, |item, cx| {
3281 item.set_state("one".to_string(), cx);
3282 });
3283
3284 // Toolbar must be notified to re-render the navigation buttons
3285 assert_eq!(*toolbar_notify_count.borrow(), 1);
3286
3287 pane.read_with(cx, |pane, _| {
3288 assert!(pane.can_navigate_backward());
3289 assert!(!pane.can_navigate_forward());
3290 });
3291
3292 workspace
3293 .update(cx, |workspace, cx| {
3294 Pane::go_back(workspace, Some(pane.clone()), cx)
3295 })
3296 .await;
3297
3298 assert_eq!(*toolbar_notify_count.borrow(), 3);
3299 pane.read_with(cx, |pane, _| {
3300 assert!(!pane.can_navigate_backward());
3301 assert!(pane.can_navigate_forward());
3302 });
3303 }
3304
3305 struct TestItem {
3306 state: String,
3307 save_count: usize,
3308 save_as_count: usize,
3309 reload_count: usize,
3310 is_dirty: bool,
3311 is_singleton: bool,
3312 has_conflict: bool,
3313 project_entry_ids: Vec<ProjectEntryId>,
3314 project_path: Option<ProjectPath>,
3315 nav_history: Option<ItemNavHistory>,
3316 tab_descriptions: Option<Vec<&'static str>>,
3317 tab_detail: Cell<Option<usize>>,
3318 }
3319
3320 enum TestItemEvent {
3321 Edit,
3322 }
3323
3324 impl Clone for TestItem {
3325 fn clone(&self) -> Self {
3326 Self {
3327 state: self.state.clone(),
3328 save_count: self.save_count,
3329 save_as_count: self.save_as_count,
3330 reload_count: self.reload_count,
3331 is_dirty: self.is_dirty,
3332 is_singleton: self.is_singleton,
3333 has_conflict: self.has_conflict,
3334 project_entry_ids: self.project_entry_ids.clone(),
3335 project_path: self.project_path.clone(),
3336 nav_history: None,
3337 tab_descriptions: None,
3338 tab_detail: Default::default(),
3339 }
3340 }
3341 }
3342
3343 impl TestItem {
3344 fn new() -> Self {
3345 Self {
3346 state: String::new(),
3347 save_count: 0,
3348 save_as_count: 0,
3349 reload_count: 0,
3350 is_dirty: false,
3351 has_conflict: false,
3352 project_entry_ids: Vec::new(),
3353 project_path: None,
3354 is_singleton: true,
3355 nav_history: None,
3356 tab_descriptions: None,
3357 tab_detail: Default::default(),
3358 }
3359 }
3360
3361 fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
3362 self.push_to_nav_history(cx);
3363 self.state = state;
3364 }
3365
3366 fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
3367 if let Some(history) = &mut self.nav_history {
3368 history.push(Some(Box::new(self.state.clone())), cx);
3369 }
3370 }
3371 }
3372
3373 impl Entity for TestItem {
3374 type Event = TestItemEvent;
3375 }
3376
3377 impl View for TestItem {
3378 fn ui_name() -> &'static str {
3379 "TestItem"
3380 }
3381
3382 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3383 Empty::new().boxed()
3384 }
3385 }
3386
3387 impl Item for TestItem {
3388 fn tab_description<'a>(&'a self, detail: usize, _: &'a AppContext) -> Option<Cow<'a, str>> {
3389 self.tab_descriptions.as_ref().and_then(|descriptions| {
3390 let description = *descriptions.get(detail).or(descriptions.last())?;
3391 Some(description.into())
3392 })
3393 }
3394
3395 fn tab_content(&self, detail: Option<usize>, _: &theme::Tab, _: &AppContext) -> ElementBox {
3396 self.tab_detail.set(detail);
3397 Empty::new().boxed()
3398 }
3399
3400 fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
3401 self.project_path.clone()
3402 }
3403
3404 fn project_entry_ids(&self, _: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
3405 self.project_entry_ids.iter().copied().collect()
3406 }
3407
3408 fn is_singleton(&self, _: &AppContext) -> bool {
3409 self.is_singleton
3410 }
3411
3412 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
3413 self.nav_history = Some(history);
3414 }
3415
3416 fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
3417 let state = *state.downcast::<String>().unwrap_or_default();
3418 if state != self.state {
3419 self.state = state;
3420 true
3421 } else {
3422 false
3423 }
3424 }
3425
3426 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
3427 self.push_to_nav_history(cx);
3428 }
3429
3430 fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
3431 where
3432 Self: Sized,
3433 {
3434 Some(self.clone())
3435 }
3436
3437 fn is_dirty(&self, _: &AppContext) -> bool {
3438 self.is_dirty
3439 }
3440
3441 fn has_conflict(&self, _: &AppContext) -> bool {
3442 self.has_conflict
3443 }
3444
3445 fn can_save(&self, _: &AppContext) -> bool {
3446 self.project_entry_ids.len() > 0
3447 }
3448
3449 fn save(
3450 &mut self,
3451 _: ModelHandle<Project>,
3452 _: &mut ViewContext<Self>,
3453 ) -> Task<anyhow::Result<()>> {
3454 self.save_count += 1;
3455 self.is_dirty = false;
3456 Task::ready(Ok(()))
3457 }
3458
3459 fn save_as(
3460 &mut self,
3461 _: ModelHandle<Project>,
3462 _: std::path::PathBuf,
3463 _: &mut ViewContext<Self>,
3464 ) -> Task<anyhow::Result<()>> {
3465 self.save_as_count += 1;
3466 self.is_dirty = false;
3467 Task::ready(Ok(()))
3468 }
3469
3470 fn reload(
3471 &mut self,
3472 _: ModelHandle<Project>,
3473 _: &mut ViewContext<Self>,
3474 ) -> Task<anyhow::Result<()>> {
3475 self.reload_count += 1;
3476 self.is_dirty = false;
3477 Task::ready(Ok(()))
3478 }
3479
3480 fn should_update_tab_on_event(_: &Self::Event) -> bool {
3481 true
3482 }
3483
3484 fn is_edit_event(event: &Self::Event) -> bool {
3485 matches!(event, TestItemEvent::Edit)
3486 }
3487 }
3488}