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