1/// NOTE: Focus only 'takes' after an update has flushed_effects.
2///
3/// This may cause issues when you're trying to write tests that use workspace focus to add items at
4/// specific locations.
5pub mod dock;
6pub mod pane;
7pub mod pane_group;
8pub mod searchable;
9pub mod sidebar;
10mod status_bar;
11mod toolbar;
12
13use anyhow::{anyhow, Context, Result};
14use call::ActiveCall;
15use client::{proto, Client, PeerId, TypedEnvelope, UserStore};
16use collections::{hash_map, HashMap, HashSet};
17use dock::{DefaultItemFactory, Dock, ToggleDockButton};
18use drag_and_drop::DragAndDrop;
19use fs::{self, Fs};
20use futures::{channel::oneshot, FutureExt, StreamExt};
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::{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 = fs::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<WeakViewHandle<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 active_call: Option<ModelHandle<ActiveCall>>,
984 _observe_current_user: Task<()>,
985 _active_call_observation: Option<gpui::Subscription>,
986}
987
988#[derive(Default)]
989struct LeaderState {
990 followers: HashSet<PeerId>,
991}
992
993type FollowerStatesByLeader = HashMap<PeerId, HashMap<ViewHandle<Pane>, FollowerState>>;
994
995#[derive(Default)]
996struct FollowerState {
997 active_view_id: Option<u64>,
998 items_by_leader_view_id: HashMap<u64, FollowerItem>,
999}
1000
1001#[derive(Debug)]
1002enum FollowerItem {
1003 Loading(Vec<proto::update_view::Variant>),
1004 Loaded(Box<dyn FollowableItemHandle>),
1005}
1006
1007impl Workspace {
1008 pub fn new(
1009 project: ModelHandle<Project>,
1010 dock_default_factory: DefaultItemFactory,
1011 cx: &mut ViewContext<Self>,
1012 ) -> Self {
1013 cx.observe_fullscreen(|_, _, cx| cx.notify()).detach();
1014
1015 cx.observe_window_activation(Self::on_window_activation_changed)
1016 .detach();
1017 cx.observe(&project, |_, _, cx| cx.notify()).detach();
1018 cx.subscribe(&project, move |this, _, event, cx| {
1019 match event {
1020 project::Event::RemoteIdChanged(remote_id) => {
1021 this.project_remote_id_changed(*remote_id, cx);
1022 }
1023 project::Event::CollaboratorLeft(peer_id) => {
1024 this.collaborator_left(*peer_id, cx);
1025 }
1026 project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded => {
1027 this.update_window_title(cx);
1028 }
1029 project::Event::DisconnectedFromHost => {
1030 this.update_window_edited(cx);
1031 cx.blur();
1032 }
1033 _ => {}
1034 }
1035 cx.notify()
1036 })
1037 .detach();
1038
1039 let center_pane = cx.add_view(|cx| Pane::new(None, cx));
1040 let pane_id = center_pane.id();
1041 cx.subscribe(¢er_pane, move |this, _, event, cx| {
1042 this.handle_pane_event(pane_id, event, cx)
1043 })
1044 .detach();
1045 cx.focus(¢er_pane);
1046 cx.emit(Event::PaneAdded(center_pane.clone()));
1047
1048 let fs = project.read(cx).fs().clone();
1049 let user_store = project.read(cx).user_store();
1050 let client = project.read(cx).client();
1051 let mut current_user = user_store.read(cx).watch_current_user();
1052 let mut connection_status = client.status();
1053 let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
1054 current_user.recv().await;
1055 connection_status.recv().await;
1056 let mut stream =
1057 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1058
1059 while stream.recv().await.is_some() {
1060 cx.update(|cx| {
1061 if let Some(this) = this.upgrade(cx) {
1062 this.update(cx, |_, cx| cx.notify());
1063 }
1064 })
1065 }
1066 });
1067
1068 let handle = cx.handle();
1069 let weak_handle = cx.weak_handle();
1070
1071 cx.emit_global(WorkspaceCreated(weak_handle.clone()));
1072
1073 let dock = Dock::new(cx, dock_default_factory);
1074 let dock_pane = dock.pane().clone();
1075
1076 let left_sidebar = cx.add_view(|_| Sidebar::new(SidebarSide::Left));
1077 let right_sidebar = cx.add_view(|_| Sidebar::new(SidebarSide::Right));
1078 let left_sidebar_buttons = cx.add_view(|cx| SidebarButtons::new(left_sidebar.clone(), cx));
1079 let toggle_dock = cx.add_view(|cx| ToggleDockButton::new(handle, cx));
1080 let right_sidebar_buttons =
1081 cx.add_view(|cx| SidebarButtons::new(right_sidebar.clone(), cx));
1082 let status_bar = cx.add_view(|cx| {
1083 let mut status_bar = StatusBar::new(¢er_pane.clone(), cx);
1084 status_bar.add_left_item(left_sidebar_buttons, cx);
1085 status_bar.add_right_item(right_sidebar_buttons, cx);
1086 status_bar.add_right_item(toggle_dock, cx);
1087 status_bar
1088 });
1089
1090 cx.update_default_global::<DragAndDrop<Workspace>, _, _>(|drag_and_drop, _| {
1091 drag_and_drop.register_container(weak_handle.clone());
1092 });
1093
1094 let mut active_call = None;
1095 let mut active_call_observation = None;
1096 if cx.has_global::<ModelHandle<ActiveCall>>() {
1097 let call = cx.global::<ModelHandle<ActiveCall>>().clone();
1098 active_call_observation = Some(cx.observe(&call, |_, _, cx| cx.notify()));
1099 active_call = Some(call);
1100 }
1101
1102 let mut this = Workspace {
1103 modal: None,
1104 weak_self: weak_handle,
1105 center: PaneGroup::new(center_pane.clone()),
1106 dock,
1107 // When removing an item, the last element remaining in this array
1108 // is used to find where focus should fallback to. As such, the order
1109 // of these two variables is important.
1110 panes: vec![dock_pane, center_pane.clone()],
1111 panes_by_item: Default::default(),
1112 active_pane: center_pane.clone(),
1113 last_active_center_pane: Some(center_pane.downgrade()),
1114 status_bar,
1115 titlebar_item: None,
1116 notifications: Default::default(),
1117 client,
1118 remote_entity_subscription: None,
1119 user_store,
1120 fs,
1121 left_sidebar,
1122 right_sidebar,
1123 project,
1124 leader_state: Default::default(),
1125 follower_states_by_leader: Default::default(),
1126 last_leaders_by_pane: Default::default(),
1127 window_edited: false,
1128 active_call,
1129 _observe_current_user,
1130 _active_call_observation: active_call_observation,
1131 };
1132 this.project_remote_id_changed(this.project.read(cx).remote_id(), cx);
1133 cx.defer(|this, cx| this.update_window_title(cx));
1134
1135 this
1136 }
1137
1138 pub fn weak_handle(&self) -> WeakViewHandle<Self> {
1139 self.weak_self.clone()
1140 }
1141
1142 pub fn left_sidebar(&self) -> &ViewHandle<Sidebar> {
1143 &self.left_sidebar
1144 }
1145
1146 pub fn right_sidebar(&self) -> &ViewHandle<Sidebar> {
1147 &self.right_sidebar
1148 }
1149
1150 pub fn status_bar(&self) -> &ViewHandle<StatusBar> {
1151 &self.status_bar
1152 }
1153
1154 pub fn user_store(&self) -> &ModelHandle<UserStore> {
1155 &self.user_store
1156 }
1157
1158 pub fn project(&self) -> &ModelHandle<Project> {
1159 &self.project
1160 }
1161
1162 pub fn client(&self) -> &Arc<Client> {
1163 &self.client
1164 }
1165
1166 pub fn set_titlebar_item(
1167 &mut self,
1168 item: impl Into<AnyViewHandle>,
1169 cx: &mut ViewContext<Self>,
1170 ) {
1171 self.titlebar_item = Some(item.into());
1172 cx.notify();
1173 }
1174
1175 pub fn titlebar_item(&self) -> Option<AnyViewHandle> {
1176 self.titlebar_item.clone()
1177 }
1178
1179 /// Call the given callback with a workspace whose project is local.
1180 ///
1181 /// If the given workspace has a local project, then it will be passed
1182 /// to the callback. Otherwise, a new empty window will be created.
1183 pub fn with_local_workspace<T, F>(
1184 &mut self,
1185 cx: &mut ViewContext<Self>,
1186 app_state: Arc<AppState>,
1187 callback: F,
1188 ) -> T
1189 where
1190 T: 'static,
1191 F: FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,
1192 {
1193 if self.project.read(cx).is_local() {
1194 callback(self, cx)
1195 } else {
1196 let (_, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
1197 let mut workspace = Workspace::new(
1198 Project::local(
1199 app_state.client.clone(),
1200 app_state.user_store.clone(),
1201 app_state.project_store.clone(),
1202 app_state.languages.clone(),
1203 app_state.fs.clone(),
1204 cx,
1205 ),
1206 app_state.default_item_factory,
1207 cx,
1208 );
1209 (app_state.initialize_workspace)(&mut workspace, &app_state, cx);
1210 workspace
1211 });
1212 workspace.update(cx, callback)
1213 }
1214 }
1215
1216 pub fn worktrees<'a>(
1217 &self,
1218 cx: &'a AppContext,
1219 ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
1220 self.project.read(cx).worktrees(cx)
1221 }
1222
1223 pub fn visible_worktrees<'a>(
1224 &self,
1225 cx: &'a AppContext,
1226 ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
1227 self.project.read(cx).visible_worktrees(cx)
1228 }
1229
1230 pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
1231 let futures = self
1232 .worktrees(cx)
1233 .filter_map(|worktree| worktree.read(cx).as_local())
1234 .map(|worktree| worktree.scan_complete())
1235 .collect::<Vec<_>>();
1236 async move {
1237 for future in futures {
1238 future.await;
1239 }
1240 }
1241 }
1242
1243 pub fn close(
1244 &mut self,
1245 _: &CloseWindow,
1246 cx: &mut ViewContext<Self>,
1247 ) -> Option<Task<Result<()>>> {
1248 let prepare = self.prepare_to_close(false, cx);
1249 Some(cx.spawn(|this, mut cx| async move {
1250 if prepare.await? {
1251 this.update(&mut cx, |_, cx| {
1252 let window_id = cx.window_id();
1253 cx.remove_window(window_id);
1254 });
1255 }
1256 Ok(())
1257 }))
1258 }
1259
1260 pub fn prepare_to_close(
1261 &mut self,
1262 quitting: bool,
1263 cx: &mut ViewContext<Self>,
1264 ) -> Task<Result<bool>> {
1265 let active_call = self.active_call.clone();
1266 let window_id = cx.window_id();
1267 let workspace_count = cx
1268 .window_ids()
1269 .flat_map(|window_id| cx.root_view::<Workspace>(window_id))
1270 .count();
1271 cx.spawn(|this, mut cx| async move {
1272 if let Some(active_call) = active_call {
1273 if !quitting
1274 && workspace_count == 1
1275 && active_call.read_with(&cx, |call, _| call.room().is_some())
1276 {
1277 let answer = cx
1278 .prompt(
1279 window_id,
1280 PromptLevel::Warning,
1281 "Do you want to leave the current call?",
1282 &["Close window and hang up", "Cancel"],
1283 )
1284 .next()
1285 .await;
1286 if answer == Some(1) {
1287 return anyhow::Ok(false);
1288 } else {
1289 active_call.update(&mut cx, |call, cx| call.hang_up(cx))?;
1290 }
1291 }
1292 }
1293
1294 Ok(this
1295 .update(&mut cx, |this, cx| this.save_all_internal(true, cx))
1296 .await?)
1297 })
1298 }
1299
1300 fn save_all(&mut self, _: &SaveAll, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
1301 let save_all = self.save_all_internal(false, cx);
1302 Some(cx.foreground().spawn(async move {
1303 save_all.await?;
1304 Ok(())
1305 }))
1306 }
1307
1308 fn save_all_internal(
1309 &mut self,
1310 should_prompt_to_save: bool,
1311 cx: &mut ViewContext<Self>,
1312 ) -> Task<Result<bool>> {
1313 if self.project.read(cx).is_read_only() {
1314 return Task::ready(Ok(true));
1315 }
1316
1317 let dirty_items = self
1318 .panes
1319 .iter()
1320 .flat_map(|pane| {
1321 pane.read(cx).items().filter_map(|item| {
1322 if item.is_dirty(cx) {
1323 Some((pane.clone(), item.boxed_clone()))
1324 } else {
1325 None
1326 }
1327 })
1328 })
1329 .collect::<Vec<_>>();
1330
1331 let project = self.project.clone();
1332 cx.spawn_weak(|_, mut cx| async move {
1333 for (pane, item) in dirty_items {
1334 let (singleton, project_entry_ids) =
1335 cx.read(|cx| (item.is_singleton(cx), item.project_entry_ids(cx)));
1336 if singleton || !project_entry_ids.is_empty() {
1337 if let Some(ix) =
1338 pane.read_with(&cx, |pane, _| pane.index_for_item(item.as_ref()))
1339 {
1340 if !Pane::save_item(
1341 project.clone(),
1342 &pane,
1343 ix,
1344 &*item,
1345 should_prompt_to_save,
1346 &mut cx,
1347 )
1348 .await?
1349 {
1350 return Ok(false);
1351 }
1352 }
1353 }
1354 }
1355 Ok(true)
1356 })
1357 }
1358
1359 #[allow(clippy::type_complexity)]
1360 pub fn open_paths(
1361 &mut self,
1362 mut abs_paths: Vec<PathBuf>,
1363 visible: bool,
1364 cx: &mut ViewContext<Self>,
1365 ) -> Task<Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>> {
1366 let fs = self.fs.clone();
1367
1368 // Sort the paths to ensure we add worktrees for parents before their children.
1369 abs_paths.sort_unstable();
1370 cx.spawn(|this, mut cx| async move {
1371 let mut project_paths = Vec::new();
1372 for path in &abs_paths {
1373 project_paths.push(
1374 this.update(&mut cx, |this, cx| {
1375 this.project_path_for_path(path, visible, cx)
1376 })
1377 .await
1378 .log_err(),
1379 );
1380 }
1381
1382 let tasks = abs_paths
1383 .iter()
1384 .cloned()
1385 .zip(project_paths.into_iter())
1386 .map(|(abs_path, project_path)| {
1387 let this = this.clone();
1388 cx.spawn(|mut cx| {
1389 let fs = fs.clone();
1390 async move {
1391 let (_worktree, project_path) = project_path?;
1392 if fs.is_file(&abs_path).await {
1393 Some(
1394 this.update(&mut cx, |this, cx| {
1395 this.open_path(project_path, true, cx)
1396 })
1397 .await,
1398 )
1399 } else {
1400 None
1401 }
1402 }
1403 })
1404 })
1405 .collect::<Vec<_>>();
1406
1407 futures::future::join_all(tasks).await
1408 })
1409 }
1410
1411 fn add_folder_to_project(&mut self, _: &AddFolderToProject, cx: &mut ViewContext<Self>) {
1412 let mut paths = cx.prompt_for_paths(PathPromptOptions {
1413 files: false,
1414 directories: true,
1415 multiple: true,
1416 });
1417 cx.spawn(|this, mut cx| async move {
1418 if let Some(paths) = paths.recv().await.flatten() {
1419 let results = this
1420 .update(&mut cx, |this, cx| this.open_paths(paths, true, cx))
1421 .await;
1422 for result in results.into_iter().flatten() {
1423 result.log_err();
1424 }
1425 }
1426 })
1427 .detach();
1428 }
1429
1430 fn remove_folder_from_project(
1431 &mut self,
1432 RemoveWorktreeFromProject(worktree_id): &RemoveWorktreeFromProject,
1433 cx: &mut ViewContext<Self>,
1434 ) {
1435 self.project
1436 .update(cx, |project, cx| project.remove_worktree(*worktree_id, cx));
1437 }
1438
1439 fn project_path_for_path(
1440 &self,
1441 abs_path: &Path,
1442 visible: bool,
1443 cx: &mut ViewContext<Self>,
1444 ) -> Task<Result<(ModelHandle<Worktree>, ProjectPath)>> {
1445 let entry = self.project().update(cx, |project, cx| {
1446 project.find_or_create_local_worktree(abs_path, visible, cx)
1447 });
1448 cx.spawn(|_, cx| async move {
1449 let (worktree, path) = entry.await?;
1450 let worktree_id = worktree.read_with(&cx, |t, _| t.id());
1451 Ok((
1452 worktree,
1453 ProjectPath {
1454 worktree_id,
1455 path: path.into(),
1456 },
1457 ))
1458 })
1459 }
1460
1461 /// Returns the modal that was toggled closed if it was open.
1462 pub fn toggle_modal<V, F>(
1463 &mut self,
1464 cx: &mut ViewContext<Self>,
1465 add_view: F,
1466 ) -> Option<ViewHandle<V>>
1467 where
1468 V: 'static + View,
1469 F: FnOnce(&mut Self, &mut ViewContext<Self>) -> ViewHandle<V>,
1470 {
1471 cx.notify();
1472 // Whatever modal was visible is getting clobbered. If its the same type as V, then return
1473 // it. Otherwise, create a new modal and set it as active.
1474 let already_open_modal = self.modal.take().and_then(|modal| modal.downcast::<V>());
1475 if let Some(already_open_modal) = already_open_modal {
1476 cx.focus_self();
1477 Some(already_open_modal)
1478 } else {
1479 let modal = add_view(self, cx);
1480 cx.focus(&modal);
1481 self.modal = Some(modal.into());
1482 None
1483 }
1484 }
1485
1486 pub fn modal<V: 'static + View>(&self) -> Option<ViewHandle<V>> {
1487 self.modal
1488 .as_ref()
1489 .and_then(|modal| modal.clone().downcast::<V>())
1490 }
1491
1492 pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
1493 if self.modal.take().is_some() {
1494 cx.focus(&self.active_pane);
1495 cx.notify();
1496 }
1497 }
1498
1499 pub fn show_notification<V: Notification>(
1500 &mut self,
1501 id: usize,
1502 cx: &mut ViewContext<Self>,
1503 build_notification: impl FnOnce(&mut ViewContext<Self>) -> ViewHandle<V>,
1504 ) {
1505 let type_id = TypeId::of::<V>();
1506 if self
1507 .notifications
1508 .iter()
1509 .all(|(existing_type_id, existing_id, _)| {
1510 (*existing_type_id, *existing_id) != (type_id, id)
1511 })
1512 {
1513 let notification = build_notification(cx);
1514 cx.subscribe(¬ification, move |this, handle, event, cx| {
1515 if handle.read(cx).should_dismiss_notification_on_event(event) {
1516 this.dismiss_notification(type_id, id, cx);
1517 }
1518 })
1519 .detach();
1520 self.notifications
1521 .push((type_id, id, Box::new(notification)));
1522 cx.notify();
1523 }
1524 }
1525
1526 fn dismiss_notification(&mut self, type_id: TypeId, id: usize, cx: &mut ViewContext<Self>) {
1527 self.notifications
1528 .retain(|(existing_type_id, existing_id, _)| {
1529 if (*existing_type_id, *existing_id) == (type_id, id) {
1530 cx.notify();
1531 false
1532 } else {
1533 true
1534 }
1535 });
1536 }
1537
1538 pub fn items<'a>(
1539 &'a self,
1540 cx: &'a AppContext,
1541 ) -> impl 'a + Iterator<Item = &Box<dyn ItemHandle>> {
1542 self.panes.iter().flat_map(|pane| pane.read(cx).items())
1543 }
1544
1545 pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
1546 self.items_of_type(cx).max_by_key(|item| item.id())
1547 }
1548
1549 pub fn items_of_type<'a, T: Item>(
1550 &'a self,
1551 cx: &'a AppContext,
1552 ) -> impl 'a + Iterator<Item = ViewHandle<T>> {
1553 self.panes
1554 .iter()
1555 .flat_map(|pane| pane.read(cx).items_of_type())
1556 }
1557
1558 pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
1559 self.active_pane().read(cx).active_item()
1560 }
1561
1562 fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
1563 self.active_item(cx).and_then(|item| item.project_path(cx))
1564 }
1565
1566 pub fn save_active_item(
1567 &mut self,
1568 force_name_change: bool,
1569 cx: &mut ViewContext<Self>,
1570 ) -> Task<Result<()>> {
1571 let project = self.project.clone();
1572 if let Some(item) = self.active_item(cx) {
1573 if !force_name_change && item.can_save(cx) {
1574 if item.has_conflict(cx.as_ref()) {
1575 const CONFLICT_MESSAGE: &str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1576
1577 let mut answer = cx.prompt(
1578 PromptLevel::Warning,
1579 CONFLICT_MESSAGE,
1580 &["Overwrite", "Cancel"],
1581 );
1582 cx.spawn(|_, mut cx| async move {
1583 let answer = answer.recv().await;
1584 if answer == Some(0) {
1585 cx.update(|cx| item.save(project, cx)).await?;
1586 }
1587 Ok(())
1588 })
1589 } else {
1590 item.save(project, cx)
1591 }
1592 } else if item.is_singleton(cx) {
1593 let worktree = self.worktrees(cx).next();
1594 let start_abs_path = worktree
1595 .and_then(|w| w.read(cx).as_local())
1596 .map_or(Path::new(""), |w| w.abs_path())
1597 .to_path_buf();
1598 let mut abs_path = cx.prompt_for_new_path(&start_abs_path);
1599 cx.spawn(|_, mut cx| async move {
1600 if let Some(abs_path) = abs_path.recv().await.flatten() {
1601 cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
1602 }
1603 Ok(())
1604 })
1605 } else {
1606 Task::ready(Ok(()))
1607 }
1608 } else {
1609 Task::ready(Ok(()))
1610 }
1611 }
1612
1613 pub fn toggle_sidebar(&mut self, sidebar_side: SidebarSide, cx: &mut ViewContext<Self>) {
1614 let sidebar = match sidebar_side {
1615 SidebarSide::Left => &mut self.left_sidebar,
1616 SidebarSide::Right => &mut self.right_sidebar,
1617 };
1618 let open = sidebar.update(cx, |sidebar, cx| {
1619 let open = !sidebar.is_open();
1620 sidebar.set_open(open, cx);
1621 open
1622 });
1623
1624 if open {
1625 Dock::hide_on_sidebar_shown(self, sidebar_side, cx);
1626 }
1627
1628 cx.focus_self();
1629 cx.notify();
1630 }
1631
1632 pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
1633 let sidebar = match action.sidebar_side {
1634 SidebarSide::Left => &mut self.left_sidebar,
1635 SidebarSide::Right => &mut self.right_sidebar,
1636 };
1637 let active_item = sidebar.update(cx, move |sidebar, cx| {
1638 if sidebar.is_open() && sidebar.active_item_ix() == action.item_index {
1639 sidebar.set_open(false, cx);
1640 None
1641 } else {
1642 sidebar.set_open(true, cx);
1643 sidebar.activate_item(action.item_index, cx);
1644 sidebar.active_item().cloned()
1645 }
1646 });
1647
1648 if let Some(active_item) = active_item {
1649 Dock::hide_on_sidebar_shown(self, action.sidebar_side, cx);
1650
1651 if active_item.is_focused(cx) {
1652 cx.focus_self();
1653 } else {
1654 cx.focus(active_item.to_any());
1655 }
1656 } else {
1657 cx.focus_self();
1658 }
1659 cx.notify();
1660 }
1661
1662 pub fn toggle_sidebar_item_focus(
1663 &mut self,
1664 sidebar_side: SidebarSide,
1665 item_index: usize,
1666 cx: &mut ViewContext<Self>,
1667 ) {
1668 let sidebar = match sidebar_side {
1669 SidebarSide::Left => &mut self.left_sidebar,
1670 SidebarSide::Right => &mut self.right_sidebar,
1671 };
1672 let active_item = sidebar.update(cx, |sidebar, cx| {
1673 sidebar.set_open(true, cx);
1674 sidebar.activate_item(item_index, cx);
1675 sidebar.active_item().cloned()
1676 });
1677 if let Some(active_item) = active_item {
1678 Dock::hide_on_sidebar_shown(self, sidebar_side, cx);
1679
1680 if active_item.is_focused(cx) {
1681 cx.focus_self();
1682 } else {
1683 cx.focus(active_item.to_any());
1684 }
1685 }
1686 cx.notify();
1687 }
1688
1689 pub fn focus_center(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
1690 cx.focus_self();
1691 cx.notify();
1692 }
1693
1694 fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
1695 let pane = cx.add_view(|cx| Pane::new(None, cx));
1696 let pane_id = pane.id();
1697 cx.subscribe(&pane, move |this, _, event, cx| {
1698 this.handle_pane_event(pane_id, event, cx)
1699 })
1700 .detach();
1701 self.panes.push(pane.clone());
1702 cx.focus(pane.clone());
1703 cx.emit(Event::PaneAdded(pane.clone()));
1704 pane
1705 }
1706
1707 pub fn add_item(&mut self, item: Box<dyn ItemHandle>, cx: &mut ViewContext<Self>) {
1708 let active_pane = self.active_pane().clone();
1709 Pane::add_item(self, &active_pane, item, true, true, None, cx);
1710 }
1711
1712 pub fn open_path(
1713 &mut self,
1714 path: impl Into<ProjectPath>,
1715 focus_item: bool,
1716 cx: &mut ViewContext<Self>,
1717 ) -> Task<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>> {
1718 let pane = self.active_pane().downgrade();
1719 let task = self.load_path(path.into(), cx);
1720 cx.spawn(|this, mut cx| async move {
1721 let (project_entry_id, build_item) = task.await?;
1722 let pane = pane
1723 .upgrade(&cx)
1724 .ok_or_else(|| anyhow!("pane was closed"))?;
1725 this.update(&mut cx, |this, cx| {
1726 Ok(Pane::open_item(
1727 this,
1728 pane,
1729 project_entry_id,
1730 focus_item,
1731 cx,
1732 build_item,
1733 ))
1734 })
1735 })
1736 }
1737
1738 pub(crate) fn load_path(
1739 &mut self,
1740 path: ProjectPath,
1741 cx: &mut ViewContext<Self>,
1742 ) -> Task<
1743 Result<(
1744 ProjectEntryId,
1745 impl 'static + FnOnce(&mut ViewContext<Pane>) -> Box<dyn ItemHandle>,
1746 )>,
1747 > {
1748 let project = self.project().clone();
1749 let project_item = project.update(cx, |project, cx| project.open_path(path, cx));
1750 cx.as_mut().spawn(|mut cx| async move {
1751 let (project_entry_id, project_item) = project_item.await?;
1752 let build_item = cx.update(|cx| {
1753 cx.default_global::<ProjectItemBuilders>()
1754 .get(&project_item.model_type())
1755 .ok_or_else(|| anyhow!("no item builder for project item"))
1756 .cloned()
1757 })?;
1758 let build_item =
1759 move |cx: &mut ViewContext<Pane>| build_item(project, project_item, cx);
1760 Ok((project_entry_id, build_item))
1761 })
1762 }
1763
1764 pub fn open_project_item<T>(
1765 &mut self,
1766 project_item: ModelHandle<T::Item>,
1767 cx: &mut ViewContext<Self>,
1768 ) -> ViewHandle<T>
1769 where
1770 T: ProjectItem,
1771 {
1772 use project::Item as _;
1773
1774 let entry_id = project_item.read(cx).entry_id(cx);
1775 if let Some(item) = entry_id
1776 .and_then(|entry_id| self.active_pane().read(cx).item_for_entry(entry_id, cx))
1777 .and_then(|item| item.downcast())
1778 {
1779 self.activate_item(&item, cx);
1780 return item;
1781 }
1782
1783 let item = cx.add_view(|cx| T::for_project_item(self.project().clone(), project_item, cx));
1784 self.add_item(Box::new(item.clone()), cx);
1785 item
1786 }
1787
1788 pub fn activate_item(&mut self, item: &dyn ItemHandle, cx: &mut ViewContext<Self>) -> bool {
1789 let result = self.panes.iter().find_map(|pane| {
1790 pane.read(cx)
1791 .index_for_item(item)
1792 .map(|ix| (pane.clone(), ix))
1793 });
1794 if let Some((pane, ix)) = result {
1795 pane.update(cx, |pane, cx| pane.activate_item(ix, true, true, cx));
1796 true
1797 } else {
1798 false
1799 }
1800 }
1801
1802 fn activate_pane_at_index(&mut self, action: &ActivatePane, cx: &mut ViewContext<Self>) {
1803 let panes = self.center.panes();
1804 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
1805 cx.focus(pane);
1806 } else {
1807 self.split_pane(self.active_pane.clone(), SplitDirection::Right, cx);
1808 }
1809 }
1810
1811 pub fn activate_next_pane(&mut self, cx: &mut ViewContext<Self>) {
1812 let next_pane = {
1813 let panes = self.center.panes();
1814 let ix = panes
1815 .iter()
1816 .position(|pane| **pane == self.active_pane)
1817 .unwrap();
1818 let next_ix = (ix + 1) % panes.len();
1819 panes[next_ix].clone()
1820 };
1821 cx.focus(next_pane);
1822 }
1823
1824 pub fn activate_previous_pane(&mut self, cx: &mut ViewContext<Self>) {
1825 let prev_pane = {
1826 let panes = self.center.panes();
1827 let ix = panes
1828 .iter()
1829 .position(|pane| **pane == self.active_pane)
1830 .unwrap();
1831 let prev_ix = if ix == 0 { panes.len() - 1 } else { ix - 1 };
1832 panes[prev_ix].clone()
1833 };
1834 cx.focus(prev_pane);
1835 }
1836
1837 fn handle_pane_focused(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1838 if self.active_pane != pane {
1839 self.active_pane
1840 .update(cx, |pane, cx| pane.set_active(false, cx));
1841 self.active_pane = pane.clone();
1842 self.active_pane
1843 .update(cx, |pane, cx| pane.set_active(true, cx));
1844 self.status_bar.update(cx, |status_bar, cx| {
1845 status_bar.set_active_pane(&self.active_pane, cx);
1846 });
1847 self.active_item_path_changed(cx);
1848
1849 if &pane == self.dock_pane() {
1850 Dock::show(self, cx);
1851 } else {
1852 self.last_active_center_pane = Some(pane.downgrade());
1853 if self.dock.is_anchored_at(DockAnchor::Expanded) {
1854 Dock::hide(self, cx);
1855 }
1856 }
1857 cx.notify();
1858 }
1859
1860 self.update_followers(
1861 proto::update_followers::Variant::UpdateActiveView(proto::UpdateActiveView {
1862 id: self.active_item(cx).map(|item| item.id() as u64),
1863 leader_id: self.leader_for_pane(&pane).map(|id| id.0),
1864 }),
1865 cx,
1866 );
1867 }
1868
1869 fn handle_pane_event(
1870 &mut self,
1871 pane_id: usize,
1872 event: &pane::Event,
1873 cx: &mut ViewContext<Self>,
1874 ) {
1875 if let Some(pane) = self.pane(pane_id) {
1876 let is_dock = &pane == self.dock.pane();
1877 match event {
1878 pane::Event::Split(direction) if !is_dock => {
1879 self.split_pane(pane, *direction, cx);
1880 }
1881 pane::Event::Remove if !is_dock => self.remove_pane(pane, cx),
1882 pane::Event::Remove if is_dock => Dock::hide(self, cx),
1883 pane::Event::ActivateItem { local } => {
1884 if *local {
1885 self.unfollow(&pane, cx);
1886 }
1887 if &pane == self.active_pane() {
1888 self.active_item_path_changed(cx);
1889 }
1890 }
1891 pane::Event::ChangeItemTitle => {
1892 if pane == self.active_pane {
1893 self.active_item_path_changed(cx);
1894 }
1895 self.update_window_edited(cx);
1896 }
1897 pane::Event::RemoveItem { item_id } => {
1898 self.update_window_edited(cx);
1899 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(*item_id) {
1900 if entry.get().id() == pane.id() {
1901 entry.remove();
1902 }
1903 }
1904 }
1905 _ => {}
1906 }
1907 } else if self.dock.visible_pane().is_none() {
1908 error!("pane {} not found", pane_id);
1909 }
1910 }
1911
1912 pub fn split_pane(
1913 &mut self,
1914 pane: ViewHandle<Pane>,
1915 direction: SplitDirection,
1916 cx: &mut ViewContext<Self>,
1917 ) -> Option<ViewHandle<Pane>> {
1918 if &pane == self.dock_pane() {
1919 warn!("Can't split dock pane.");
1920 return None;
1921 }
1922
1923 pane.read(cx).active_item().map(|item| {
1924 let new_pane = self.add_pane(cx);
1925 if let Some(clone) = item.clone_on_split(cx.as_mut()) {
1926 Pane::add_item(self, &new_pane, clone, true, true, None, cx);
1927 }
1928 self.center.split(&pane, &new_pane, direction).unwrap();
1929 cx.notify();
1930 new_pane
1931 })
1932 }
1933
1934 fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1935 if self.center.remove(&pane).unwrap() {
1936 self.panes.retain(|p| p != &pane);
1937 cx.focus(self.panes.last().unwrap().clone());
1938 self.unfollow(&pane, cx);
1939 self.last_leaders_by_pane.remove(&pane.downgrade());
1940 for removed_item in pane.read(cx).items() {
1941 self.panes_by_item.remove(&removed_item.id());
1942 }
1943 if self.last_active_center_pane == Some(pane.downgrade()) {
1944 self.last_active_center_pane = None;
1945 }
1946
1947 cx.notify();
1948 } else {
1949 self.active_item_path_changed(cx);
1950 }
1951 }
1952
1953 pub fn panes(&self) -> &[ViewHandle<Pane>] {
1954 &self.panes
1955 }
1956
1957 fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1958 self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1959 }
1960
1961 pub fn active_pane(&self) -> &ViewHandle<Pane> {
1962 &self.active_pane
1963 }
1964
1965 pub fn dock_pane(&self) -> &ViewHandle<Pane> {
1966 self.dock.pane()
1967 }
1968
1969 fn project_remote_id_changed(&mut self, remote_id: Option<u64>, cx: &mut ViewContext<Self>) {
1970 if let Some(remote_id) = remote_id {
1971 self.remote_entity_subscription =
1972 Some(self.client.add_view_for_remote_entity(remote_id, cx));
1973 } else {
1974 self.remote_entity_subscription.take();
1975 }
1976 }
1977
1978 fn collaborator_left(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
1979 self.leader_state.followers.remove(&peer_id);
1980 if let Some(states_by_pane) = self.follower_states_by_leader.remove(&peer_id) {
1981 for state in states_by_pane.into_values() {
1982 for item in state.items_by_leader_view_id.into_values() {
1983 if let FollowerItem::Loaded(item) = item {
1984 item.set_leader_replica_id(None, cx);
1985 }
1986 }
1987 }
1988 }
1989 cx.notify();
1990 }
1991
1992 pub fn toggle_follow(
1993 &mut self,
1994 ToggleFollow(leader_id): &ToggleFollow,
1995 cx: &mut ViewContext<Self>,
1996 ) -> Option<Task<Result<()>>> {
1997 let leader_id = *leader_id;
1998 let pane = self.active_pane().clone();
1999
2000 if let Some(prev_leader_id) = self.unfollow(&pane, cx) {
2001 if leader_id == prev_leader_id {
2002 return None;
2003 }
2004 }
2005
2006 self.last_leaders_by_pane
2007 .insert(pane.downgrade(), leader_id);
2008 self.follower_states_by_leader
2009 .entry(leader_id)
2010 .or_default()
2011 .insert(pane.clone(), Default::default());
2012 cx.notify();
2013
2014 let project_id = self.project.read(cx).remote_id()?;
2015 let request = self.client.request(proto::Follow {
2016 project_id,
2017 leader_id: leader_id.0,
2018 });
2019 Some(cx.spawn_weak(|this, mut cx| async move {
2020 let response = request.await?;
2021 if let Some(this) = this.upgrade(&cx) {
2022 this.update(&mut cx, |this, _| {
2023 let state = this
2024 .follower_states_by_leader
2025 .get_mut(&leader_id)
2026 .and_then(|states_by_pane| states_by_pane.get_mut(&pane))
2027 .ok_or_else(|| anyhow!("following interrupted"))?;
2028 state.active_view_id = response.active_view_id;
2029 Ok::<_, anyhow::Error>(())
2030 })?;
2031 Self::add_views_from_leader(this, leader_id, vec![pane], response.views, &mut cx)
2032 .await?;
2033 }
2034 Ok(())
2035 }))
2036 }
2037
2038 pub fn follow_next_collaborator(
2039 &mut self,
2040 _: &FollowNextCollaborator,
2041 cx: &mut ViewContext<Self>,
2042 ) -> Option<Task<Result<()>>> {
2043 let collaborators = self.project.read(cx).collaborators();
2044 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
2045 let mut collaborators = collaborators.keys().copied();
2046 for peer_id in collaborators.by_ref() {
2047 if peer_id == leader_id {
2048 break;
2049 }
2050 }
2051 collaborators.next()
2052 } else if let Some(last_leader_id) =
2053 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
2054 {
2055 if collaborators.contains_key(last_leader_id) {
2056 Some(*last_leader_id)
2057 } else {
2058 None
2059 }
2060 } else {
2061 None
2062 };
2063
2064 next_leader_id
2065 .or_else(|| collaborators.keys().copied().next())
2066 .and_then(|leader_id| self.toggle_follow(&ToggleFollow(leader_id), cx))
2067 }
2068
2069 pub fn unfollow(
2070 &mut self,
2071 pane: &ViewHandle<Pane>,
2072 cx: &mut ViewContext<Self>,
2073 ) -> Option<PeerId> {
2074 for (leader_id, states_by_pane) in &mut self.follower_states_by_leader {
2075 let leader_id = *leader_id;
2076 if let Some(state) = states_by_pane.remove(pane) {
2077 for (_, item) in state.items_by_leader_view_id {
2078 if let FollowerItem::Loaded(item) = item {
2079 item.set_leader_replica_id(None, cx);
2080 }
2081 }
2082
2083 if states_by_pane.is_empty() {
2084 self.follower_states_by_leader.remove(&leader_id);
2085 if let Some(project_id) = self.project.read(cx).remote_id() {
2086 self.client
2087 .send(proto::Unfollow {
2088 project_id,
2089 leader_id: leader_id.0,
2090 })
2091 .log_err();
2092 }
2093 }
2094
2095 cx.notify();
2096 return Some(leader_id);
2097 }
2098 }
2099 None
2100 }
2101
2102 pub fn is_following(&self, peer_id: PeerId) -> bool {
2103 self.follower_states_by_leader.contains_key(&peer_id)
2104 }
2105
2106 fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
2107 let project = &self.project.read(cx);
2108 let mut worktree_root_names = String::new();
2109 for (i, name) in project.worktree_root_names(cx).enumerate() {
2110 if i > 0 {
2111 worktree_root_names.push_str(", ");
2112 }
2113 worktree_root_names.push_str(name);
2114 }
2115
2116 // TODO: There should be a better system in place for this
2117 // (https://github.com/zed-industries/zed/issues/1290)
2118 let is_fullscreen = cx.window_is_fullscreen(cx.window_id());
2119 let container_theme = if is_fullscreen {
2120 let mut container_theme = theme.workspace.titlebar.container;
2121 container_theme.padding.left = container_theme.padding.right;
2122 container_theme
2123 } else {
2124 theme.workspace.titlebar.container
2125 };
2126
2127 enum TitleBar {}
2128 ConstrainedBox::new(
2129 MouseEventHandler::<TitleBar>::new(0, cx, |_, _| {
2130 Container::new(
2131 Stack::new()
2132 .with_child(
2133 Label::new(worktree_root_names, theme.workspace.titlebar.title.clone())
2134 .aligned()
2135 .left()
2136 .boxed(),
2137 )
2138 .with_children(
2139 self.titlebar_item
2140 .as_ref()
2141 .map(|item| ChildView::new(item).aligned().right().boxed()),
2142 )
2143 .boxed(),
2144 )
2145 .with_style(container_theme)
2146 .boxed()
2147 })
2148 .on_click(MouseButton::Left, |event, cx| {
2149 if event.click_count == 2 {
2150 cx.zoom_window(cx.window_id());
2151 }
2152 })
2153 .boxed(),
2154 )
2155 .with_height(theme.workspace.titlebar.height)
2156 .named("titlebar")
2157 }
2158
2159 fn active_item_path_changed(&mut self, cx: &mut ViewContext<Self>) {
2160 let active_entry = self.active_project_path(cx);
2161 self.project
2162 .update(cx, |project, cx| project.set_active_path(active_entry, cx));
2163 self.update_window_title(cx);
2164 }
2165
2166 fn update_window_title(&mut self, cx: &mut ViewContext<Self>) {
2167 let mut title = String::new();
2168 let project = self.project().read(cx);
2169 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
2170 let filename = path
2171 .path
2172 .file_name()
2173 .map(|s| s.to_string_lossy())
2174 .or_else(|| {
2175 Some(Cow::Borrowed(
2176 project
2177 .worktree_for_id(path.worktree_id, cx)?
2178 .read(cx)
2179 .root_name(),
2180 ))
2181 });
2182 if let Some(filename) = filename {
2183 title.push_str(filename.as_ref());
2184 title.push_str(" — ");
2185 }
2186 }
2187 for (i, name) in project.worktree_root_names(cx).enumerate() {
2188 if i > 0 {
2189 title.push_str(", ");
2190 }
2191 title.push_str(name);
2192 }
2193 if title.is_empty() {
2194 title = "empty project".to_string();
2195 }
2196 cx.set_window_title(&title);
2197 }
2198
2199 fn update_window_edited(&mut self, cx: &mut ViewContext<Self>) {
2200 let is_edited = !self.project.read(cx).is_read_only()
2201 && self
2202 .items(cx)
2203 .any(|item| item.has_conflict(cx) || item.is_dirty(cx));
2204 if is_edited != self.window_edited {
2205 self.window_edited = is_edited;
2206 cx.set_window_edited(self.window_edited)
2207 }
2208 }
2209
2210 fn render_disconnected_overlay(&self, cx: &mut RenderContext<Workspace>) -> Option<ElementBox> {
2211 if self.project.read(cx).is_read_only() {
2212 enum DisconnectedOverlay {}
2213 Some(
2214 MouseEventHandler::<DisconnectedOverlay>::new(0, cx, |_, cx| {
2215 let theme = &cx.global::<Settings>().theme;
2216 Label::new(
2217 "Your connection to the remote project has been lost.".to_string(),
2218 theme.workspace.disconnected_overlay.text.clone(),
2219 )
2220 .aligned()
2221 .contained()
2222 .with_style(theme.workspace.disconnected_overlay.container)
2223 .boxed()
2224 })
2225 .with_cursor_style(CursorStyle::Arrow)
2226 .capture_all()
2227 .boxed(),
2228 )
2229 } else {
2230 None
2231 }
2232 }
2233
2234 fn render_notifications(&self, theme: &theme::Workspace) -> Option<ElementBox> {
2235 if self.notifications.is_empty() {
2236 None
2237 } else {
2238 Some(
2239 Flex::column()
2240 .with_children(self.notifications.iter().map(|(_, _, notification)| {
2241 ChildView::new(notification.as_ref())
2242 .contained()
2243 .with_style(theme.notification)
2244 .boxed()
2245 }))
2246 .constrained()
2247 .with_width(theme.notifications.width)
2248 .contained()
2249 .with_style(theme.notifications.container)
2250 .aligned()
2251 .bottom()
2252 .right()
2253 .boxed(),
2254 )
2255 }
2256 }
2257
2258 // RPC handlers
2259
2260 async fn handle_follow(
2261 this: ViewHandle<Self>,
2262 envelope: TypedEnvelope<proto::Follow>,
2263 _: Arc<Client>,
2264 mut cx: AsyncAppContext,
2265 ) -> Result<proto::FollowResponse> {
2266 this.update(&mut cx, |this, cx| {
2267 this.leader_state
2268 .followers
2269 .insert(envelope.original_sender_id()?);
2270
2271 let active_view_id = this
2272 .active_item(cx)
2273 .and_then(|i| i.to_followable_item_handle(cx))
2274 .map(|i| i.id() as u64);
2275 Ok(proto::FollowResponse {
2276 active_view_id,
2277 views: this
2278 .panes()
2279 .iter()
2280 .flat_map(|pane| {
2281 let leader_id = this.leader_for_pane(pane).map(|id| id.0);
2282 pane.read(cx).items().filter_map({
2283 let cx = &cx;
2284 move |item| {
2285 let id = item.id() as u64;
2286 let item = item.to_followable_item_handle(cx)?;
2287 let variant = item.to_state_proto(cx)?;
2288 Some(proto::View {
2289 id,
2290 leader_id,
2291 variant: Some(variant),
2292 })
2293 }
2294 })
2295 })
2296 .collect(),
2297 })
2298 })
2299 }
2300
2301 async fn handle_unfollow(
2302 this: ViewHandle<Self>,
2303 envelope: TypedEnvelope<proto::Unfollow>,
2304 _: Arc<Client>,
2305 mut cx: AsyncAppContext,
2306 ) -> Result<()> {
2307 this.update(&mut cx, |this, _| {
2308 this.leader_state
2309 .followers
2310 .remove(&envelope.original_sender_id()?);
2311 Ok(())
2312 })
2313 }
2314
2315 async fn handle_update_followers(
2316 this: ViewHandle<Self>,
2317 envelope: TypedEnvelope<proto::UpdateFollowers>,
2318 _: Arc<Client>,
2319 mut cx: AsyncAppContext,
2320 ) -> Result<()> {
2321 let leader_id = envelope.original_sender_id()?;
2322 match envelope
2323 .payload
2324 .variant
2325 .ok_or_else(|| anyhow!("invalid update"))?
2326 {
2327 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
2328 this.update(&mut cx, |this, cx| {
2329 this.update_leader_state(leader_id, cx, |state, _| {
2330 state.active_view_id = update_active_view.id;
2331 });
2332 Ok::<_, anyhow::Error>(())
2333 })
2334 }
2335 proto::update_followers::Variant::UpdateView(update_view) => {
2336 this.update(&mut cx, |this, cx| {
2337 let variant = update_view
2338 .variant
2339 .ok_or_else(|| anyhow!("missing update view variant"))?;
2340 this.update_leader_state(leader_id, cx, |state, cx| {
2341 let variant = variant.clone();
2342 match state
2343 .items_by_leader_view_id
2344 .entry(update_view.id)
2345 .or_insert(FollowerItem::Loading(Vec::new()))
2346 {
2347 FollowerItem::Loaded(item) => {
2348 item.apply_update_proto(variant, cx).log_err();
2349 }
2350 FollowerItem::Loading(updates) => updates.push(variant),
2351 }
2352 });
2353 Ok(())
2354 })
2355 }
2356 proto::update_followers::Variant::CreateView(view) => {
2357 let panes = this.read_with(&cx, |this, _| {
2358 this.follower_states_by_leader
2359 .get(&leader_id)
2360 .into_iter()
2361 .flat_map(|states_by_pane| states_by_pane.keys())
2362 .cloned()
2363 .collect()
2364 });
2365 Self::add_views_from_leader(this.clone(), leader_id, panes, vec![view], &mut cx)
2366 .await?;
2367 Ok(())
2368 }
2369 }
2370 .log_err();
2371
2372 Ok(())
2373 }
2374
2375 async fn add_views_from_leader(
2376 this: ViewHandle<Self>,
2377 leader_id: PeerId,
2378 panes: Vec<ViewHandle<Pane>>,
2379 views: Vec<proto::View>,
2380 cx: &mut AsyncAppContext,
2381 ) -> Result<()> {
2382 let project = this.read_with(cx, |this, _| this.project.clone());
2383 let replica_id = project
2384 .read_with(cx, |project, _| {
2385 project
2386 .collaborators()
2387 .get(&leader_id)
2388 .map(|c| c.replica_id)
2389 })
2390 .ok_or_else(|| anyhow!("no such collaborator {}", leader_id))?;
2391
2392 let item_builders = cx.update(|cx| {
2393 cx.default_global::<FollowableItemBuilders>()
2394 .values()
2395 .map(|b| b.0)
2396 .collect::<Vec<_>>()
2397 });
2398
2399 let mut item_tasks_by_pane = HashMap::default();
2400 for pane in panes {
2401 let mut item_tasks = Vec::new();
2402 let mut leader_view_ids = Vec::new();
2403 for view in &views {
2404 let mut variant = view.variant.clone();
2405 if variant.is_none() {
2406 Err(anyhow!("missing variant"))?;
2407 }
2408 for build_item in &item_builders {
2409 let task =
2410 cx.update(|cx| build_item(pane.clone(), project.clone(), &mut variant, cx));
2411 if let Some(task) = task {
2412 item_tasks.push(task);
2413 leader_view_ids.push(view.id);
2414 break;
2415 } else {
2416 assert!(variant.is_some());
2417 }
2418 }
2419 }
2420
2421 item_tasks_by_pane.insert(pane, (item_tasks, leader_view_ids));
2422 }
2423
2424 for (pane, (item_tasks, leader_view_ids)) in item_tasks_by_pane {
2425 let items = futures::future::try_join_all(item_tasks).await?;
2426 this.update(cx, |this, cx| {
2427 let state = this
2428 .follower_states_by_leader
2429 .get_mut(&leader_id)?
2430 .get_mut(&pane)?;
2431
2432 for (id, item) in leader_view_ids.into_iter().zip(items) {
2433 item.set_leader_replica_id(Some(replica_id), cx);
2434 match state.items_by_leader_view_id.entry(id) {
2435 hash_map::Entry::Occupied(e) => {
2436 let e = e.into_mut();
2437 if let FollowerItem::Loading(updates) = e {
2438 for update in updates.drain(..) {
2439 item.apply_update_proto(update, cx)
2440 .context("failed to apply view update")
2441 .log_err();
2442 }
2443 }
2444 *e = FollowerItem::Loaded(item);
2445 }
2446 hash_map::Entry::Vacant(e) => {
2447 e.insert(FollowerItem::Loaded(item));
2448 }
2449 }
2450 }
2451
2452 Some(())
2453 });
2454 }
2455 this.update(cx, |this, cx| this.leader_updated(leader_id, cx));
2456
2457 Ok(())
2458 }
2459
2460 fn update_followers(
2461 &self,
2462 update: proto::update_followers::Variant,
2463 cx: &AppContext,
2464 ) -> Option<()> {
2465 let project_id = self.project.read(cx).remote_id()?;
2466 if !self.leader_state.followers.is_empty() {
2467 self.client
2468 .send(proto::UpdateFollowers {
2469 project_id,
2470 follower_ids: self.leader_state.followers.iter().map(|f| f.0).collect(),
2471 variant: Some(update),
2472 })
2473 .log_err();
2474 }
2475 None
2476 }
2477
2478 pub fn leader_for_pane(&self, pane: &ViewHandle<Pane>) -> Option<PeerId> {
2479 self.follower_states_by_leader
2480 .iter()
2481 .find_map(|(leader_id, state)| {
2482 if state.contains_key(pane) {
2483 Some(*leader_id)
2484 } else {
2485 None
2486 }
2487 })
2488 }
2489
2490 fn update_leader_state(
2491 &mut self,
2492 leader_id: PeerId,
2493 cx: &mut ViewContext<Self>,
2494 mut update_fn: impl FnMut(&mut FollowerState, &mut ViewContext<Self>),
2495 ) {
2496 for (_, state) in self
2497 .follower_states_by_leader
2498 .get_mut(&leader_id)
2499 .into_iter()
2500 .flatten()
2501 {
2502 update_fn(state, cx);
2503 }
2504 self.leader_updated(leader_id, cx);
2505 }
2506
2507 fn leader_updated(&mut self, leader_id: PeerId, cx: &mut ViewContext<Self>) -> Option<()> {
2508 let mut items_to_add = Vec::new();
2509 for (pane, state) in self.follower_states_by_leader.get(&leader_id)? {
2510 if let Some(FollowerItem::Loaded(item)) = state
2511 .active_view_id
2512 .and_then(|id| state.items_by_leader_view_id.get(&id))
2513 {
2514 items_to_add.push((pane.clone(), item.boxed_clone()));
2515 }
2516 }
2517
2518 for (pane, item) in items_to_add {
2519 Pane::add_item(self, &pane, item.boxed_clone(), false, false, None, cx);
2520 if pane == self.active_pane {
2521 pane.update(cx, |pane, cx| pane.focus_active_item(cx));
2522 }
2523 cx.notify();
2524 }
2525 None
2526 }
2527
2528 pub fn on_window_activation_changed(&mut self, active: bool, cx: &mut ViewContext<Self>) {
2529 if !active {
2530 for pane in &self.panes {
2531 pane.update(cx, |pane, cx| {
2532 if let Some(item) = pane.active_item() {
2533 item.workspace_deactivated(cx);
2534 }
2535 if matches!(
2536 cx.global::<Settings>().autosave,
2537 Autosave::OnWindowChange | Autosave::OnFocusChange
2538 ) {
2539 for item in pane.items() {
2540 Pane::autosave_item(item.as_ref(), self.project.clone(), cx)
2541 .detach_and_log_err(cx);
2542 }
2543 }
2544 });
2545 }
2546 }
2547 }
2548}
2549
2550impl Entity for Workspace {
2551 type Event = Event;
2552}
2553
2554impl View for Workspace {
2555 fn ui_name() -> &'static str {
2556 "Workspace"
2557 }
2558
2559 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
2560 let theme = cx.global::<Settings>().theme.clone();
2561 Stack::new()
2562 .with_child(
2563 Flex::column()
2564 .with_child(self.render_titlebar(&theme, cx))
2565 .with_child(
2566 Stack::new()
2567 .with_child({
2568 let project = self.project.clone();
2569 Flex::row()
2570 .with_children(
2571 if self.left_sidebar.read(cx).active_item().is_some() {
2572 Some(
2573 ChildView::new(&self.left_sidebar)
2574 .flex(0.8, false)
2575 .boxed(),
2576 )
2577 } else {
2578 None
2579 },
2580 )
2581 .with_child(
2582 FlexItem::new(
2583 Flex::column()
2584 .with_child(
2585 FlexItem::new(self.center.render(
2586 &project,
2587 &theme,
2588 &self.follower_states_by_leader,
2589 self.active_call.as_ref(),
2590 cx,
2591 ))
2592 .flex(1., true)
2593 .boxed(),
2594 )
2595 .with_children(self.dock.render(
2596 &theme,
2597 DockAnchor::Bottom,
2598 cx,
2599 ))
2600 .boxed(),
2601 )
2602 .flex(1., true)
2603 .boxed(),
2604 )
2605 .with_children(self.dock.render(&theme, DockAnchor::Right, cx))
2606 .with_children(
2607 if self.right_sidebar.read(cx).active_item().is_some() {
2608 Some(
2609 ChildView::new(&self.right_sidebar)
2610 .flex(0.8, false)
2611 .boxed(),
2612 )
2613 } else {
2614 None
2615 },
2616 )
2617 .boxed()
2618 })
2619 .with_child(
2620 Overlay::new(
2621 Stack::new()
2622 .with_children(self.dock.render(
2623 &theme,
2624 DockAnchor::Expanded,
2625 cx,
2626 ))
2627 .with_children(self.modal.as_ref().map(|m| {
2628 ChildView::new(m)
2629 .contained()
2630 .with_style(theme.workspace.modal)
2631 .aligned()
2632 .top()
2633 .boxed()
2634 }))
2635 .with_children(self.render_notifications(&theme.workspace))
2636 .boxed(),
2637 )
2638 .boxed(),
2639 )
2640 .flex(1.0, true)
2641 .boxed(),
2642 )
2643 .with_child(ChildView::new(&self.status_bar).boxed())
2644 .contained()
2645 .with_background_color(theme.workspace.background)
2646 .boxed(),
2647 )
2648 .with_children(DragAndDrop::render(cx))
2649 .with_children(self.render_disconnected_overlay(cx))
2650 .named("workspace")
2651 }
2652
2653 fn on_focus_in(&mut self, view: AnyViewHandle, cx: &mut ViewContext<Self>) {
2654 if cx.is_self_focused() {
2655 cx.focus(&self.active_pane);
2656 } else {
2657 for pane in self.panes() {
2658 let view = view.clone();
2659 if pane.update(cx, |_, cx| cx.is_child(view)) {
2660 self.handle_pane_focused(pane.clone(), cx);
2661 break;
2662 }
2663 }
2664 }
2665 }
2666
2667 fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
2668 let mut keymap = Self::default_keymap_context();
2669 if self.active_pane() == self.dock_pane() {
2670 keymap.set.insert("Dock".into());
2671 }
2672 keymap
2673 }
2674}
2675
2676pub trait WorkspaceHandle {
2677 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
2678}
2679
2680impl WorkspaceHandle for ViewHandle<Workspace> {
2681 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
2682 self.read(cx)
2683 .worktrees(cx)
2684 .flat_map(|worktree| {
2685 let worktree_id = worktree.read(cx).id();
2686 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
2687 worktree_id,
2688 path: f.path.clone(),
2689 })
2690 })
2691 .collect::<Vec<_>>()
2692 }
2693}
2694
2695impl std::fmt::Debug for OpenPaths {
2696 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2697 f.debug_struct("OpenPaths")
2698 .field("paths", &self.paths)
2699 .finish()
2700 }
2701}
2702
2703fn open(_: &Open, cx: &mut MutableAppContext) {
2704 let mut paths = cx.prompt_for_paths(PathPromptOptions {
2705 files: true,
2706 directories: true,
2707 multiple: true,
2708 });
2709 cx.spawn(|mut cx| async move {
2710 if let Some(paths) = paths.recv().await.flatten() {
2711 cx.update(|cx| cx.dispatch_global_action(OpenPaths { paths }));
2712 }
2713 })
2714 .detach();
2715}
2716
2717pub struct WorkspaceCreated(WeakViewHandle<Workspace>);
2718
2719pub fn activate_workspace_for_project(
2720 cx: &mut MutableAppContext,
2721 predicate: impl Fn(&mut Project, &mut ModelContext<Project>) -> bool,
2722) -> Option<ViewHandle<Workspace>> {
2723 for window_id in cx.window_ids().collect::<Vec<_>>() {
2724 if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
2725 let project = workspace_handle.read(cx).project.clone();
2726 if project.update(cx, &predicate) {
2727 cx.activate_window(window_id);
2728 return Some(workspace_handle);
2729 }
2730 }
2731 }
2732 None
2733}
2734
2735#[allow(clippy::type_complexity)]
2736pub fn open_paths(
2737 abs_paths: &[PathBuf],
2738 app_state: &Arc<AppState>,
2739 cx: &mut MutableAppContext,
2740) -> Task<(
2741 ViewHandle<Workspace>,
2742 Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>,
2743)> {
2744 log::info!("open paths {:?}", abs_paths);
2745
2746 // Open paths in existing workspace if possible
2747 let existing =
2748 activate_workspace_for_project(cx, |project, cx| project.contains_paths(abs_paths, cx));
2749
2750 let app_state = app_state.clone();
2751 let abs_paths = abs_paths.to_vec();
2752 cx.spawn(|mut cx| async move {
2753 let mut new_project = None;
2754 let workspace = if let Some(existing) = existing {
2755 existing
2756 } else {
2757 let contains_directory =
2758 futures::future::join_all(abs_paths.iter().map(|path| app_state.fs.is_file(path)))
2759 .await
2760 .contains(&false);
2761
2762 cx.add_window((app_state.build_window_options)(), |cx| {
2763 let project = Project::local(
2764 app_state.client.clone(),
2765 app_state.user_store.clone(),
2766 app_state.project_store.clone(),
2767 app_state.languages.clone(),
2768 app_state.fs.clone(),
2769 cx,
2770 );
2771 new_project = Some(project.clone());
2772 let mut workspace = Workspace::new(project, app_state.default_item_factory, cx);
2773 (app_state.initialize_workspace)(&mut workspace, &app_state, cx);
2774 if contains_directory {
2775 workspace.toggle_sidebar(SidebarSide::Left, cx);
2776 }
2777 workspace
2778 })
2779 .1
2780 };
2781
2782 let items = workspace
2783 .update(&mut cx, |workspace, cx| {
2784 workspace.open_paths(abs_paths, true, cx)
2785 })
2786 .await;
2787
2788 (workspace, items)
2789 })
2790}
2791
2792fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
2793 let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
2794 let mut workspace = Workspace::new(
2795 Project::local(
2796 app_state.client.clone(),
2797 app_state.user_store.clone(),
2798 app_state.project_store.clone(),
2799 app_state.languages.clone(),
2800 app_state.fs.clone(),
2801 cx,
2802 ),
2803 app_state.default_item_factory,
2804 cx,
2805 );
2806 (app_state.initialize_workspace)(&mut workspace, app_state, cx);
2807 workspace
2808 });
2809 cx.dispatch_action_at(window_id, workspace.id(), NewFile);
2810}
2811
2812#[cfg(test)]
2813mod tests {
2814 use std::cell::Cell;
2815
2816 use crate::sidebar::SidebarItem;
2817
2818 use super::*;
2819 use fs::FakeFs;
2820 use gpui::{executor::Deterministic, ModelHandle, TestAppContext, ViewContext};
2821 use project::{Project, ProjectEntryId};
2822 use serde_json::json;
2823
2824 pub fn default_item_factory(
2825 _workspace: &mut Workspace,
2826 _cx: &mut ViewContext<Workspace>,
2827 ) -> Box<dyn ItemHandle> {
2828 unimplemented!();
2829 }
2830
2831 #[gpui::test]
2832 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
2833 cx.foreground().forbid_parking();
2834 Settings::test_async(cx);
2835
2836 let fs = FakeFs::new(cx.background());
2837 let project = Project::test(fs, [], cx).await;
2838 let (_, workspace) =
2839 cx.add_window(|cx| Workspace::new(project.clone(), default_item_factory, cx));
2840
2841 // Adding an item with no ambiguity renders the tab without detail.
2842 let item1 = cx.add_view(&workspace, |_| {
2843 let mut item = TestItem::new();
2844 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
2845 item
2846 });
2847 workspace.update(cx, |workspace, cx| {
2848 workspace.add_item(Box::new(item1.clone()), cx);
2849 });
2850 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), None));
2851
2852 // Adding an item that creates ambiguity increases the level of detail on
2853 // both tabs.
2854 let item2 = cx.add_view(&workspace, |_| {
2855 let mut item = TestItem::new();
2856 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
2857 item
2858 });
2859 workspace.update(cx, |workspace, cx| {
2860 workspace.add_item(Box::new(item2.clone()), cx);
2861 });
2862 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2863 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2864
2865 // Adding an item that creates ambiguity increases the level of detail only
2866 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
2867 // we stop at the highest detail available.
2868 let item3 = cx.add_view(&workspace, |_| {
2869 let mut item = TestItem::new();
2870 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
2871 item
2872 });
2873 workspace.update(cx, |workspace, cx| {
2874 workspace.add_item(Box::new(item3.clone()), cx);
2875 });
2876 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2877 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
2878 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
2879 }
2880
2881 #[gpui::test]
2882 async fn test_tracking_active_path(cx: &mut TestAppContext) {
2883 cx.foreground().forbid_parking();
2884 Settings::test_async(cx);
2885 let fs = FakeFs::new(cx.background());
2886 fs.insert_tree(
2887 "/root1",
2888 json!({
2889 "one.txt": "",
2890 "two.txt": "",
2891 }),
2892 )
2893 .await;
2894 fs.insert_tree(
2895 "/root2",
2896 json!({
2897 "three.txt": "",
2898 }),
2899 )
2900 .await;
2901
2902 let project = Project::test(fs, ["root1".as_ref()], cx).await;
2903 let (window_id, workspace) =
2904 cx.add_window(|cx| Workspace::new(project.clone(), default_item_factory, cx));
2905 let worktree_id = project.read_with(cx, |project, cx| {
2906 project.worktrees(cx).next().unwrap().read(cx).id()
2907 });
2908
2909 let item1 = cx.add_view(&workspace, |_| {
2910 let mut item = TestItem::new();
2911 item.project_path = Some((worktree_id, "one.txt").into());
2912 item
2913 });
2914 let item2 = cx.add_view(&workspace, |_| {
2915 let mut item = TestItem::new();
2916 item.project_path = Some((worktree_id, "two.txt").into());
2917 item
2918 });
2919
2920 // Add an item to an empty pane
2921 workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item1), cx));
2922 project.read_with(cx, |project, cx| {
2923 assert_eq!(
2924 project.active_entry(),
2925 project
2926 .entry_for_path(&(worktree_id, "one.txt").into(), cx)
2927 .map(|e| e.id)
2928 );
2929 });
2930 assert_eq!(
2931 cx.current_window_title(window_id).as_deref(),
2932 Some("one.txt — root1")
2933 );
2934
2935 // Add a second item to a non-empty pane
2936 workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item2), cx));
2937 assert_eq!(
2938 cx.current_window_title(window_id).as_deref(),
2939 Some("two.txt — root1")
2940 );
2941 project.read_with(cx, |project, cx| {
2942 assert_eq!(
2943 project.active_entry(),
2944 project
2945 .entry_for_path(&(worktree_id, "two.txt").into(), cx)
2946 .map(|e| e.id)
2947 );
2948 });
2949
2950 // Close the active item
2951 workspace
2952 .update(cx, |workspace, cx| {
2953 Pane::close_active_item(workspace, &Default::default(), cx).unwrap()
2954 })
2955 .await
2956 .unwrap();
2957 assert_eq!(
2958 cx.current_window_title(window_id).as_deref(),
2959 Some("one.txt — root1")
2960 );
2961 project.read_with(cx, |project, cx| {
2962 assert_eq!(
2963 project.active_entry(),
2964 project
2965 .entry_for_path(&(worktree_id, "one.txt").into(), cx)
2966 .map(|e| e.id)
2967 );
2968 });
2969
2970 // Add a project folder
2971 project
2972 .update(cx, |project, cx| {
2973 project.find_or_create_local_worktree("/root2", true, cx)
2974 })
2975 .await
2976 .unwrap();
2977 assert_eq!(
2978 cx.current_window_title(window_id).as_deref(),
2979 Some("one.txt — root1, root2")
2980 );
2981
2982 // Remove a project folder
2983 project.update(cx, |project, cx| {
2984 project.remove_worktree(worktree_id, cx);
2985 });
2986 assert_eq!(
2987 cx.current_window_title(window_id).as_deref(),
2988 Some("one.txt — root2")
2989 );
2990 }
2991
2992 #[gpui::test]
2993 async fn test_close_window(cx: &mut TestAppContext) {
2994 cx.foreground().forbid_parking();
2995 Settings::test_async(cx);
2996 let fs = FakeFs::new(cx.background());
2997 fs.insert_tree("/root", json!({ "one": "" })).await;
2998
2999 let project = Project::test(fs, ["root".as_ref()], cx).await;
3000 let (window_id, workspace) =
3001 cx.add_window(|cx| Workspace::new(project.clone(), default_item_factory, cx));
3002
3003 // When there are no dirty items, there's nothing to do.
3004 let item1 = cx.add_view(&workspace, |_| TestItem::new());
3005 workspace.update(cx, |w, cx| w.add_item(Box::new(item1.clone()), cx));
3006 let task = workspace.update(cx, |w, cx| w.prepare_to_close(false, cx));
3007 assert!(task.await.unwrap());
3008
3009 // When there are dirty untitled items, prompt to save each one. If the user
3010 // cancels any prompt, then abort.
3011 let item2 = cx.add_view(&workspace, |_| {
3012 let mut item = TestItem::new();
3013 item.is_dirty = true;
3014 item
3015 });
3016 let item3 = cx.add_view(&workspace, |_| {
3017 let mut item = TestItem::new();
3018 item.is_dirty = true;
3019 item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3020 item
3021 });
3022 workspace.update(cx, |w, cx| {
3023 w.add_item(Box::new(item2.clone()), cx);
3024 w.add_item(Box::new(item3.clone()), cx);
3025 });
3026 let task = workspace.update(cx, |w, cx| w.prepare_to_close(false, cx));
3027 cx.foreground().run_until_parked();
3028 cx.simulate_prompt_answer(window_id, 2 /* cancel */);
3029 cx.foreground().run_until_parked();
3030 assert!(!cx.has_pending_prompt(window_id));
3031 assert!(!task.await.unwrap());
3032 }
3033
3034 #[gpui::test]
3035 async fn test_close_pane_items(cx: &mut TestAppContext) {
3036 cx.foreground().forbid_parking();
3037 Settings::test_async(cx);
3038 let fs = FakeFs::new(cx.background());
3039
3040 let project = Project::test(fs, None, cx).await;
3041 let (window_id, workspace) =
3042 cx.add_window(|cx| Workspace::new(project, default_item_factory, cx));
3043
3044 let item1 = cx.add_view(&workspace, |_| {
3045 let mut item = TestItem::new();
3046 item.is_dirty = true;
3047 item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3048 item
3049 });
3050 let item2 = cx.add_view(&workspace, |_| {
3051 let mut item = TestItem::new();
3052 item.is_dirty = true;
3053 item.has_conflict = true;
3054 item.project_entry_ids = vec![ProjectEntryId::from_proto(2)];
3055 item
3056 });
3057 let item3 = cx.add_view(&workspace, |_| {
3058 let mut item = TestItem::new();
3059 item.is_dirty = true;
3060 item.has_conflict = true;
3061 item.project_entry_ids = vec![ProjectEntryId::from_proto(3)];
3062 item
3063 });
3064 let item4 = cx.add_view(&workspace, |_| {
3065 let mut item = TestItem::new();
3066 item.is_dirty = true;
3067 item
3068 });
3069 let pane = workspace.update(cx, |workspace, cx| {
3070 workspace.add_item(Box::new(item1.clone()), cx);
3071 workspace.add_item(Box::new(item2.clone()), cx);
3072 workspace.add_item(Box::new(item3.clone()), cx);
3073 workspace.add_item(Box::new(item4.clone()), cx);
3074 workspace.active_pane().clone()
3075 });
3076
3077 let close_items = workspace.update(cx, |workspace, cx| {
3078 pane.update(cx, |pane, cx| {
3079 pane.activate_item(1, true, true, cx);
3080 assert_eq!(pane.active_item().unwrap().id(), item2.id());
3081 });
3082
3083 let item1_id = item1.id();
3084 let item3_id = item3.id();
3085 let item4_id = item4.id();
3086 Pane::close_items(workspace, pane.clone(), cx, move |id| {
3087 [item1_id, item3_id, item4_id].contains(&id)
3088 })
3089 });
3090
3091 cx.foreground().run_until_parked();
3092 pane.read_with(cx, |pane, _| {
3093 assert_eq!(pane.items().count(), 4);
3094 assert_eq!(pane.active_item().unwrap().id(), item1.id());
3095 });
3096
3097 cx.simulate_prompt_answer(window_id, 0);
3098 cx.foreground().run_until_parked();
3099 pane.read_with(cx, |pane, cx| {
3100 assert_eq!(item1.read(cx).save_count, 1);
3101 assert_eq!(item1.read(cx).save_as_count, 0);
3102 assert_eq!(item1.read(cx).reload_count, 0);
3103 assert_eq!(pane.items().count(), 3);
3104 assert_eq!(pane.active_item().unwrap().id(), item3.id());
3105 });
3106
3107 cx.simulate_prompt_answer(window_id, 1);
3108 cx.foreground().run_until_parked();
3109 pane.read_with(cx, |pane, cx| {
3110 assert_eq!(item3.read(cx).save_count, 0);
3111 assert_eq!(item3.read(cx).save_as_count, 0);
3112 assert_eq!(item3.read(cx).reload_count, 1);
3113 assert_eq!(pane.items().count(), 2);
3114 assert_eq!(pane.active_item().unwrap().id(), item4.id());
3115 });
3116
3117 cx.simulate_prompt_answer(window_id, 0);
3118 cx.foreground().run_until_parked();
3119 cx.simulate_new_path_selection(|_| Some(Default::default()));
3120 close_items.await.unwrap();
3121 pane.read_with(cx, |pane, cx| {
3122 assert_eq!(item4.read(cx).save_count, 0);
3123 assert_eq!(item4.read(cx).save_as_count, 1);
3124 assert_eq!(item4.read(cx).reload_count, 0);
3125 assert_eq!(pane.items().count(), 1);
3126 assert_eq!(pane.active_item().unwrap().id(), item2.id());
3127 });
3128 }
3129
3130 #[gpui::test]
3131 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
3132 cx.foreground().forbid_parking();
3133 Settings::test_async(cx);
3134 let fs = FakeFs::new(cx.background());
3135
3136 let project = Project::test(fs, [], cx).await;
3137 let (window_id, workspace) =
3138 cx.add_window(|cx| Workspace::new(project, default_item_factory, cx));
3139
3140 // Create several workspace items with single project entries, and two
3141 // workspace items with multiple project entries.
3142 let single_entry_items = (0..=4)
3143 .map(|project_entry_id| {
3144 let mut item = TestItem::new();
3145 item.is_dirty = true;
3146 item.project_entry_ids = vec![ProjectEntryId::from_proto(project_entry_id)];
3147 item.is_singleton = true;
3148 item
3149 })
3150 .collect::<Vec<_>>();
3151 let item_2_3 = {
3152 let mut item = TestItem::new();
3153 item.is_dirty = true;
3154 item.is_singleton = false;
3155 item.project_entry_ids =
3156 vec![ProjectEntryId::from_proto(2), ProjectEntryId::from_proto(3)];
3157 item
3158 };
3159 let item_3_4 = {
3160 let mut item = TestItem::new();
3161 item.is_dirty = true;
3162 item.is_singleton = false;
3163 item.project_entry_ids =
3164 vec![ProjectEntryId::from_proto(3), ProjectEntryId::from_proto(4)];
3165 item
3166 };
3167
3168 // Create two panes that contain the following project entries:
3169 // left pane:
3170 // multi-entry items: (2, 3)
3171 // single-entry items: 0, 1, 2, 3, 4
3172 // right pane:
3173 // single-entry items: 1
3174 // multi-entry items: (3, 4)
3175 let left_pane = workspace.update(cx, |workspace, cx| {
3176 let left_pane = workspace.active_pane().clone();
3177 workspace.add_item(Box::new(cx.add_view(|_| item_2_3.clone())), cx);
3178 for item in &single_entry_items {
3179 workspace.add_item(Box::new(cx.add_view(|_| item.clone())), cx);
3180 }
3181 left_pane.update(cx, |pane, cx| {
3182 pane.activate_item(2, true, true, cx);
3183 });
3184
3185 workspace
3186 .split_pane(left_pane.clone(), SplitDirection::Right, cx)
3187 .unwrap();
3188
3189 left_pane
3190 });
3191
3192 //Need to cause an effect flush in order to respect new focus
3193 workspace.update(cx, |workspace, cx| {
3194 workspace.add_item(Box::new(cx.add_view(|_| item_3_4.clone())), cx);
3195 cx.focus(left_pane.clone());
3196 });
3197
3198 // When closing all of the items in the left pane, we should be prompted twice:
3199 // once for project entry 0, and once for project entry 2. After those two
3200 // prompts, the task should complete.
3201
3202 let close = workspace.update(cx, |workspace, cx| {
3203 Pane::close_items(workspace, left_pane.clone(), cx, |_| true)
3204 });
3205
3206 cx.foreground().run_until_parked();
3207 left_pane.read_with(cx, |pane, cx| {
3208 assert_eq!(
3209 pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
3210 &[ProjectEntryId::from_proto(0)]
3211 );
3212 });
3213 cx.simulate_prompt_answer(window_id, 0);
3214
3215 cx.foreground().run_until_parked();
3216 left_pane.read_with(cx, |pane, cx| {
3217 assert_eq!(
3218 pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
3219 &[ProjectEntryId::from_proto(2)]
3220 );
3221 });
3222 cx.simulate_prompt_answer(window_id, 0);
3223
3224 cx.foreground().run_until_parked();
3225 close.await.unwrap();
3226 left_pane.read_with(cx, |pane, _| {
3227 assert_eq!(pane.items().count(), 0);
3228 });
3229 }
3230
3231 #[gpui::test]
3232 async fn test_autosave(deterministic: Arc<Deterministic>, cx: &mut gpui::TestAppContext) {
3233 deterministic.forbid_parking();
3234
3235 Settings::test_async(cx);
3236 let fs = FakeFs::new(cx.background());
3237
3238 let project = Project::test(fs, [], cx).await;
3239 let (window_id, workspace) =
3240 cx.add_window(|cx| Workspace::new(project, default_item_factory, cx));
3241
3242 let item = cx.add_view(&workspace, |_| {
3243 let mut item = TestItem::new();
3244 item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3245 item
3246 });
3247 let item_id = item.id();
3248 workspace.update(cx, |workspace, cx| {
3249 workspace.add_item(Box::new(item.clone()), cx);
3250 });
3251
3252 // Autosave on window change.
3253 item.update(cx, |item, cx| {
3254 cx.update_global(|settings: &mut Settings, _| {
3255 settings.autosave = Autosave::OnWindowChange;
3256 });
3257 item.is_dirty = true;
3258 });
3259
3260 // Deactivating the window saves the file.
3261 cx.simulate_window_activation(None);
3262 deterministic.run_until_parked();
3263 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
3264
3265 // Autosave on focus change.
3266 item.update(cx, |item, cx| {
3267 cx.focus_self();
3268 cx.update_global(|settings: &mut Settings, _| {
3269 settings.autosave = Autosave::OnFocusChange;
3270 });
3271 item.is_dirty = true;
3272 });
3273
3274 // Blurring the item saves the file.
3275 item.update(cx, |_, cx| cx.blur());
3276 deterministic.run_until_parked();
3277 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
3278
3279 // Deactivating the window still saves the file.
3280 cx.simulate_window_activation(Some(window_id));
3281 item.update(cx, |item, cx| {
3282 cx.focus_self();
3283 item.is_dirty = true;
3284 });
3285 cx.simulate_window_activation(None);
3286
3287 deterministic.run_until_parked();
3288 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
3289
3290 // Autosave after delay.
3291 item.update(cx, |item, cx| {
3292 cx.update_global(|settings: &mut Settings, _| {
3293 settings.autosave = Autosave::AfterDelay { milliseconds: 500 };
3294 });
3295 item.is_dirty = true;
3296 cx.emit(TestItemEvent::Edit);
3297 });
3298
3299 // Delay hasn't fully expired, so the file is still dirty and unsaved.
3300 deterministic.advance_clock(Duration::from_millis(250));
3301 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
3302
3303 // After delay expires, the file is saved.
3304 deterministic.advance_clock(Duration::from_millis(250));
3305 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
3306
3307 // Autosave on focus change, ensuring closing the tab counts as such.
3308 item.update(cx, |item, cx| {
3309 cx.update_global(|settings: &mut Settings, _| {
3310 settings.autosave = Autosave::OnFocusChange;
3311 });
3312 item.is_dirty = true;
3313 });
3314
3315 workspace
3316 .update(cx, |workspace, cx| {
3317 let pane = workspace.active_pane().clone();
3318 Pane::close_items(workspace, pane, cx, move |id| id == item_id)
3319 })
3320 .await
3321 .unwrap();
3322 assert!(!cx.has_pending_prompt(window_id));
3323 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3324
3325 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
3326 workspace.update(cx, |workspace, cx| {
3327 workspace.add_item(Box::new(item.clone()), cx);
3328 });
3329 item.update(cx, |item, cx| {
3330 item.project_entry_ids = Default::default();
3331 item.is_dirty = true;
3332 cx.blur();
3333 });
3334 deterministic.run_until_parked();
3335 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3336
3337 // Ensure autosave is prevented for deleted files also when closing the buffer.
3338 let _close_items = workspace.update(cx, |workspace, cx| {
3339 let pane = workspace.active_pane().clone();
3340 Pane::close_items(workspace, pane, cx, move |id| id == item_id)
3341 });
3342 deterministic.run_until_parked();
3343 assert!(cx.has_pending_prompt(window_id));
3344 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3345 }
3346
3347 #[gpui::test]
3348 async fn test_pane_navigation(
3349 deterministic: Arc<Deterministic>,
3350 cx: &mut gpui::TestAppContext,
3351 ) {
3352 deterministic.forbid_parking();
3353 Settings::test_async(cx);
3354 let fs = FakeFs::new(cx.background());
3355
3356 let project = Project::test(fs, [], cx).await;
3357 let (_, workspace) = cx.add_window(|cx| Workspace::new(project, default_item_factory, cx));
3358
3359 let item = cx.add_view(&workspace, |_| {
3360 let mut item = TestItem::new();
3361 item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3362 item
3363 });
3364 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
3365 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
3366 let toolbar_notify_count = Rc::new(RefCell::new(0));
3367
3368 workspace.update(cx, |workspace, cx| {
3369 workspace.add_item(Box::new(item.clone()), cx);
3370 let toolbar_notification_count = toolbar_notify_count.clone();
3371 cx.observe(&toolbar, move |_, _, _| {
3372 *toolbar_notification_count.borrow_mut() += 1
3373 })
3374 .detach();
3375 });
3376
3377 pane.read_with(cx, |pane, _| {
3378 assert!(!pane.can_navigate_backward());
3379 assert!(!pane.can_navigate_forward());
3380 });
3381
3382 item.update(cx, |item, cx| {
3383 item.set_state("one".to_string(), cx);
3384 });
3385
3386 // Toolbar must be notified to re-render the navigation buttons
3387 assert_eq!(*toolbar_notify_count.borrow(), 1);
3388
3389 pane.read_with(cx, |pane, _| {
3390 assert!(pane.can_navigate_backward());
3391 assert!(!pane.can_navigate_forward());
3392 });
3393
3394 workspace
3395 .update(cx, |workspace, cx| {
3396 Pane::go_back(workspace, Some(pane.clone()), cx)
3397 })
3398 .await;
3399
3400 assert_eq!(*toolbar_notify_count.borrow(), 3);
3401 pane.read_with(cx, |pane, _| {
3402 assert!(!pane.can_navigate_backward());
3403 assert!(pane.can_navigate_forward());
3404 });
3405 }
3406
3407 pub struct TestItem {
3408 state: String,
3409 pub label: String,
3410 save_count: usize,
3411 save_as_count: usize,
3412 reload_count: usize,
3413 is_dirty: bool,
3414 is_singleton: bool,
3415 has_conflict: bool,
3416 project_entry_ids: Vec<ProjectEntryId>,
3417 project_path: Option<ProjectPath>,
3418 nav_history: Option<ItemNavHistory>,
3419 tab_descriptions: Option<Vec<&'static str>>,
3420 tab_detail: Cell<Option<usize>>,
3421 }
3422
3423 pub enum TestItemEvent {
3424 Edit,
3425 }
3426
3427 impl Clone for TestItem {
3428 fn clone(&self) -> Self {
3429 Self {
3430 state: self.state.clone(),
3431 label: self.label.clone(),
3432 save_count: self.save_count,
3433 save_as_count: self.save_as_count,
3434 reload_count: self.reload_count,
3435 is_dirty: self.is_dirty,
3436 is_singleton: self.is_singleton,
3437 has_conflict: self.has_conflict,
3438 project_entry_ids: self.project_entry_ids.clone(),
3439 project_path: self.project_path.clone(),
3440 nav_history: None,
3441 tab_descriptions: None,
3442 tab_detail: Default::default(),
3443 }
3444 }
3445 }
3446
3447 impl TestItem {
3448 pub fn new() -> Self {
3449 Self {
3450 state: String::new(),
3451 label: String::new(),
3452 save_count: 0,
3453 save_as_count: 0,
3454 reload_count: 0,
3455 is_dirty: false,
3456 has_conflict: false,
3457 project_entry_ids: Vec::new(),
3458 project_path: None,
3459 is_singleton: true,
3460 nav_history: None,
3461 tab_descriptions: None,
3462 tab_detail: Default::default(),
3463 }
3464 }
3465
3466 pub fn with_label(mut self, state: &str) -> Self {
3467 self.label = state.to_string();
3468 self
3469 }
3470
3471 pub fn with_singleton(mut self, singleton: bool) -> Self {
3472 self.is_singleton = singleton;
3473 self
3474 }
3475
3476 pub fn with_project_entry_ids(mut self, project_entry_ids: &[u64]) -> Self {
3477 self.project_entry_ids.extend(
3478 project_entry_ids
3479 .iter()
3480 .copied()
3481 .map(ProjectEntryId::from_proto),
3482 );
3483 self
3484 }
3485
3486 fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
3487 self.push_to_nav_history(cx);
3488 self.state = state;
3489 }
3490
3491 fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
3492 if let Some(history) = &mut self.nav_history {
3493 history.push(Some(Box::new(self.state.clone())), cx);
3494 }
3495 }
3496 }
3497
3498 impl Entity for TestItem {
3499 type Event = TestItemEvent;
3500 }
3501
3502 impl View for TestItem {
3503 fn ui_name() -> &'static str {
3504 "TestItem"
3505 }
3506
3507 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3508 Empty::new().boxed()
3509 }
3510 }
3511
3512 impl Item for TestItem {
3513 fn tab_description<'a>(&'a self, detail: usize, _: &'a AppContext) -> Option<Cow<'a, str>> {
3514 self.tab_descriptions.as_ref().and_then(|descriptions| {
3515 let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
3516 Some(description.into())
3517 })
3518 }
3519
3520 fn tab_content(&self, detail: Option<usize>, _: &theme::Tab, _: &AppContext) -> ElementBox {
3521 self.tab_detail.set(detail);
3522 Empty::new().boxed()
3523 }
3524
3525 fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
3526 self.project_path.clone()
3527 }
3528
3529 fn project_entry_ids(&self, _: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
3530 self.project_entry_ids.iter().copied().collect()
3531 }
3532
3533 fn is_singleton(&self, _: &AppContext) -> bool {
3534 self.is_singleton
3535 }
3536
3537 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
3538 self.nav_history = Some(history);
3539 }
3540
3541 fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
3542 let state = *state.downcast::<String>().unwrap_or_default();
3543 if state != self.state {
3544 self.state = state;
3545 true
3546 } else {
3547 false
3548 }
3549 }
3550
3551 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
3552 self.push_to_nav_history(cx);
3553 }
3554
3555 fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
3556 where
3557 Self: Sized,
3558 {
3559 Some(self.clone())
3560 }
3561
3562 fn is_dirty(&self, _: &AppContext) -> bool {
3563 self.is_dirty
3564 }
3565
3566 fn has_conflict(&self, _: &AppContext) -> bool {
3567 self.has_conflict
3568 }
3569
3570 fn can_save(&self, _: &AppContext) -> bool {
3571 !self.project_entry_ids.is_empty()
3572 }
3573
3574 fn save(
3575 &mut self,
3576 _: ModelHandle<Project>,
3577 _: &mut ViewContext<Self>,
3578 ) -> Task<anyhow::Result<()>> {
3579 self.save_count += 1;
3580 self.is_dirty = false;
3581 Task::ready(Ok(()))
3582 }
3583
3584 fn save_as(
3585 &mut self,
3586 _: ModelHandle<Project>,
3587 _: std::path::PathBuf,
3588 _: &mut ViewContext<Self>,
3589 ) -> Task<anyhow::Result<()>> {
3590 self.save_as_count += 1;
3591 self.is_dirty = false;
3592 Task::ready(Ok(()))
3593 }
3594
3595 fn reload(
3596 &mut self,
3597 _: ModelHandle<Project>,
3598 _: &mut ViewContext<Self>,
3599 ) -> Task<anyhow::Result<()>> {
3600 self.reload_count += 1;
3601 self.is_dirty = false;
3602 Task::ready(Ok(()))
3603 }
3604
3605 fn to_item_events(_: &Self::Event) -> Vec<ItemEvent> {
3606 vec![ItemEvent::UpdateTab, ItemEvent::Edit]
3607 }
3608 }
3609
3610 impl SidebarItem for TestItem {}
3611}