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