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