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