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