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