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