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