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