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