1pub mod pane;
2pub mod pane_group;
3pub mod sidebar;
4mod status_bar;
5mod toolbar;
6mod waiting_room;
7
8use anyhow::{anyhow, Context, Result};
9use client::{
10 proto, Authenticate, Client, Contact, PeerId, Subscription, TypedEnvelope, User, UserStore,
11};
12use clock::ReplicaId;
13use collections::{hash_map, HashMap, HashSet};
14use futures::{channel::oneshot, FutureExt};
15use gpui::{
16 actions,
17 color::Color,
18 elements::*,
19 geometry::{rect::RectF, vector::vec2f, PathBuilder},
20 impl_actions, impl_internal_actions,
21 json::{self, ToJson},
22 platform::{CursorStyle, WindowOptions},
23 AnyModelHandle, AnyViewHandle, AppContext, AsyncAppContext, Border, Entity, ImageData,
24 ModelContext, ModelHandle, MouseButton, MutableAppContext, PathPromptOptions, PromptLevel,
25 RenderContext, Task, View, ViewContext, ViewHandle, WeakViewHandle,
26};
27use language::LanguageRegistry;
28use log::error;
29pub use pane::*;
30pub use pane_group::*;
31use postage::prelude::Stream;
32use project::{fs, Fs, Project, ProjectEntryId, ProjectPath, ProjectStore, Worktree, WorktreeId};
33use serde::Deserialize;
34use settings::{Autosave, Settings};
35use sidebar::{Side, Sidebar, SidebarButtons, ToggleSidebarItem};
36use smallvec::SmallVec;
37use status_bar::StatusBar;
38pub use status_bar::StatusItemView;
39use std::{
40 any::{Any, TypeId},
41 borrow::Cow,
42 cell::RefCell,
43 fmt,
44 future::Future,
45 mem,
46 path::{Path, PathBuf},
47 rc::Rc,
48 sync::{
49 atomic::{AtomicBool, Ordering::SeqCst},
50 Arc,
51 },
52 time::Duration,
53};
54use theme::{Theme, ThemeRegistry};
55pub use toolbar::{ToolbarItemLocation, ToolbarItemView};
56use util::ResultExt;
57use waiting_room::WaitingRoom;
58
59type ProjectItemBuilders = HashMap<
60 TypeId,
61 fn(usize, ModelHandle<Project>, AnyModelHandle, &mut MutableAppContext) -> Box<dyn ItemHandle>,
62>;
63
64type FollowableItemBuilder = fn(
65 ViewHandle<Pane>,
66 ModelHandle<Project>,
67 &mut Option<proto::view::Variant>,
68 &mut MutableAppContext,
69) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>;
70type FollowableItemBuilders = HashMap<
71 TypeId,
72 (
73 FollowableItemBuilder,
74 fn(AnyViewHandle) -> Box<dyn FollowableItemHandle>,
75 ),
76>;
77
78#[derive(Clone, PartialEq)]
79pub struct RemoveWorktreeFromProject(pub WorktreeId);
80
81actions!(
82 workspace,
83 [
84 Open,
85 NewFile,
86 NewWindow,
87 CloseWindow,
88 AddFolderToProject,
89 Unfollow,
90 Save,
91 SaveAs,
92 SaveAll,
93 ActivatePreviousPane,
94 ActivateNextPane,
95 FollowNextCollaborator,
96 ToggleLeftSidebar,
97 ToggleRightSidebar,
98 ]
99);
100
101#[derive(Clone, PartialEq)]
102pub struct OpenPaths {
103 pub paths: Vec<PathBuf>,
104}
105
106#[derive(Clone, Deserialize, PartialEq)]
107pub struct ToggleProjectOnline {
108 #[serde(skip_deserializing)]
109 pub project: Option<ModelHandle<Project>>,
110}
111
112#[derive(Clone, Deserialize, PartialEq)]
113pub struct ActivatePane(pub usize);
114
115#[derive(Clone, PartialEq)]
116pub struct ToggleFollow(pub PeerId);
117
118#[derive(Clone, PartialEq)]
119pub struct JoinProject {
120 pub contact: Arc<Contact>,
121 pub project_index: usize,
122}
123
124impl_internal_actions!(
125 workspace,
126 [
127 OpenPaths,
128 ToggleFollow,
129 JoinProject,
130 RemoveWorktreeFromProject
131 ]
132);
133impl_actions!(workspace, [ToggleProjectOnline, ActivatePane]);
134
135pub fn init(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
136 pane::init(cx);
137
138 cx.add_global_action(open);
139 cx.add_global_action({
140 let app_state = Arc::downgrade(&app_state);
141 move |action: &OpenPaths, cx: &mut MutableAppContext| {
142 if let Some(app_state) = app_state.upgrade() {
143 open_paths(&action.paths, &app_state, cx).detach();
144 }
145 }
146 });
147 cx.add_global_action({
148 let app_state = Arc::downgrade(&app_state);
149 move |_: &NewFile, cx: &mut MutableAppContext| {
150 if let Some(app_state) = app_state.upgrade() {
151 open_new(&app_state, cx)
152 }
153 }
154 });
155 cx.add_global_action({
156 let app_state = Arc::downgrade(&app_state);
157 move |_: &NewWindow, cx: &mut MutableAppContext| {
158 if let Some(app_state) = app_state.upgrade() {
159 open_new(&app_state, cx)
160 }
161 }
162 });
163 cx.add_global_action({
164 let app_state = Arc::downgrade(&app_state);
165 move |action: &JoinProject, cx: &mut MutableAppContext| {
166 if let Some(app_state) = app_state.upgrade() {
167 join_project(action.contact.clone(), action.project_index, &app_state, cx);
168 }
169 }
170 });
171
172 cx.add_async_action(Workspace::toggle_follow);
173 cx.add_async_action(Workspace::follow_next_collaborator);
174 cx.add_async_action(Workspace::close);
175 cx.add_async_action(Workspace::save_all);
176 cx.add_action(Workspace::add_folder_to_project);
177 cx.add_action(Workspace::remove_folder_from_project);
178 cx.add_action(Workspace::toggle_project_online);
179 cx.add_action(
180 |workspace: &mut Workspace, _: &Unfollow, cx: &mut ViewContext<Workspace>| {
181 let pane = workspace.active_pane().clone();
182 workspace.unfollow(&pane, cx);
183 },
184 );
185 cx.add_action(
186 |workspace: &mut Workspace, _: &Save, cx: &mut ViewContext<Workspace>| {
187 workspace.save_active_item(false, cx).detach_and_log_err(cx);
188 },
189 );
190 cx.add_action(
191 |workspace: &mut Workspace, _: &SaveAs, cx: &mut ViewContext<Workspace>| {
192 workspace.save_active_item(true, cx).detach_and_log_err(cx);
193 },
194 );
195 cx.add_action(Workspace::toggle_sidebar_item);
196 cx.add_action(Workspace::focus_center);
197 cx.add_action(|workspace: &mut Workspace, _: &ActivatePreviousPane, cx| {
198 workspace.activate_previous_pane(cx)
199 });
200 cx.add_action(|workspace: &mut Workspace, _: &ActivateNextPane, cx| {
201 workspace.activate_next_pane(cx)
202 });
203 cx.add_action(|workspace: &mut Workspace, _: &ToggleLeftSidebar, cx| {
204 workspace.toggle_sidebar(Side::Left, cx);
205 });
206 cx.add_action(|workspace: &mut Workspace, _: &ToggleRightSidebar, cx| {
207 workspace.toggle_sidebar(Side::Right, cx);
208 });
209 cx.add_action(Workspace::activate_pane_at_index);
210
211 let client = &app_state.client;
212 client.add_view_request_handler(Workspace::handle_follow);
213 client.add_view_message_handler(Workspace::handle_unfollow);
214 client.add_view_message_handler(Workspace::handle_update_followers);
215}
216
217pub fn register_project_item<I: ProjectItem>(cx: &mut MutableAppContext) {
218 cx.update_default_global(|builders: &mut ProjectItemBuilders, _| {
219 builders.insert(TypeId::of::<I::Item>(), |window_id, project, model, cx| {
220 let item = model.downcast::<I::Item>().unwrap();
221 Box::new(cx.add_view(window_id, |cx| I::for_project_item(project, item, cx)))
222 });
223 });
224}
225
226pub fn register_followable_item<I: FollowableItem>(cx: &mut MutableAppContext) {
227 cx.update_default_global(|builders: &mut FollowableItemBuilders, _| {
228 builders.insert(
229 TypeId::of::<I>(),
230 (
231 |pane, project, state, cx| {
232 I::from_state_proto(pane, project, state, cx).map(|task| {
233 cx.foreground()
234 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
235 })
236 },
237 |this| Box::new(this.downcast::<I>().unwrap()),
238 ),
239 );
240 });
241}
242
243pub struct AppState {
244 pub languages: Arc<LanguageRegistry>,
245 pub themes: Arc<ThemeRegistry>,
246 pub client: Arc<client::Client>,
247 pub user_store: ModelHandle<client::UserStore>,
248 pub project_store: ModelHandle<ProjectStore>,
249 pub fs: Arc<dyn fs::Fs>,
250 pub build_window_options: fn() -> WindowOptions<'static>,
251 pub initialize_workspace: fn(&mut Workspace, &Arc<AppState>, &mut ViewContext<Workspace>),
252}
253
254pub trait Item: View {
255 fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
256 fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
257 false
258 }
259 fn tab_description<'a>(&'a self, _: usize, _: &'a AppContext) -> Option<Cow<'a, str>> {
260 None
261 }
262 fn tab_content(&self, detail: Option<usize>, style: &theme::Tab, cx: &AppContext)
263 -> ElementBox;
264 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
265 fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;
266 fn is_singleton(&self, cx: &AppContext) -> bool;
267 fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>);
268 fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
269 where
270 Self: Sized,
271 {
272 None
273 }
274 fn is_dirty(&self, _: &AppContext) -> bool {
275 false
276 }
277 fn has_conflict(&self, _: &AppContext) -> bool {
278 false
279 }
280 fn can_save(&self, cx: &AppContext) -> bool;
281 fn save(
282 &mut self,
283 project: ModelHandle<Project>,
284 cx: &mut ViewContext<Self>,
285 ) -> Task<Result<()>>;
286 fn save_as(
287 &mut self,
288 project: ModelHandle<Project>,
289 abs_path: PathBuf,
290 cx: &mut ViewContext<Self>,
291 ) -> Task<Result<()>>;
292 fn reload(
293 &mut self,
294 project: ModelHandle<Project>,
295 cx: &mut ViewContext<Self>,
296 ) -> Task<Result<()>>;
297 fn should_activate_item_on_event(_: &Self::Event) -> bool {
298 false
299 }
300 fn should_close_item_on_event(_: &Self::Event) -> bool {
301 false
302 }
303 fn should_update_tab_on_event(_: &Self::Event) -> bool {
304 false
305 }
306 fn is_edit_event(_: &Self::Event) -> bool {
307 false
308 }
309 fn act_as_type(
310 &self,
311 type_id: TypeId,
312 self_handle: &ViewHandle<Self>,
313 _: &AppContext,
314 ) -> Option<AnyViewHandle> {
315 if TypeId::of::<Self>() == type_id {
316 Some(self_handle.into())
317 } else {
318 None
319 }
320 }
321}
322
323pub trait ProjectItem: Item {
324 type Item: project::Item;
325
326 fn for_project_item(
327 project: ModelHandle<Project>,
328 item: ModelHandle<Self::Item>,
329 cx: &mut ViewContext<Self>,
330 ) -> Self;
331}
332
333pub trait FollowableItem: Item {
334 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
335 fn from_state_proto(
336 pane: ViewHandle<Pane>,
337 project: ModelHandle<Project>,
338 state: &mut Option<proto::view::Variant>,
339 cx: &mut MutableAppContext,
340 ) -> Option<Task<Result<ViewHandle<Self>>>>;
341 fn add_event_to_update_proto(
342 &self,
343 event: &Self::Event,
344 update: &mut Option<proto::update_view::Variant>,
345 cx: &AppContext,
346 ) -> bool;
347 fn apply_update_proto(
348 &mut self,
349 message: proto::update_view::Variant,
350 cx: &mut ViewContext<Self>,
351 ) -> Result<()>;
352
353 fn set_leader_replica_id(&mut self, leader_replica_id: Option<u16>, cx: &mut ViewContext<Self>);
354 fn should_unfollow_on_event(event: &Self::Event, cx: &AppContext) -> bool;
355}
356
357pub trait FollowableItemHandle: ItemHandle {
358 fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext);
359 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
360 fn add_event_to_update_proto(
361 &self,
362 event: &dyn Any,
363 update: &mut Option<proto::update_view::Variant>,
364 cx: &AppContext,
365 ) -> bool;
366 fn apply_update_proto(
367 &self,
368 message: proto::update_view::Variant,
369 cx: &mut MutableAppContext,
370 ) -> Result<()>;
371 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool;
372}
373
374impl<T: FollowableItem> FollowableItemHandle for ViewHandle<T> {
375 fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext) {
376 self.update(cx, |this, cx| {
377 this.set_leader_replica_id(leader_replica_id, cx)
378 })
379 }
380
381 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
382 self.read(cx).to_state_proto(cx)
383 }
384
385 fn add_event_to_update_proto(
386 &self,
387 event: &dyn Any,
388 update: &mut Option<proto::update_view::Variant>,
389 cx: &AppContext,
390 ) -> bool {
391 if let Some(event) = event.downcast_ref() {
392 self.read(cx).add_event_to_update_proto(event, update, cx)
393 } else {
394 false
395 }
396 }
397
398 fn apply_update_proto(
399 &self,
400 message: proto::update_view::Variant,
401 cx: &mut MutableAppContext,
402 ) -> Result<()> {
403 self.update(cx, |this, cx| this.apply_update_proto(message, cx))
404 }
405
406 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool {
407 if let Some(event) = event.downcast_ref() {
408 T::should_unfollow_on_event(event, cx)
409 } else {
410 false
411 }
412 }
413}
414
415pub trait ItemHandle: 'static + fmt::Debug {
416 fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>>;
417 fn tab_content(&self, detail: Option<usize>, style: &theme::Tab, cx: &AppContext)
418 -> ElementBox;
419 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
420 fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;
421 fn is_singleton(&self, cx: &AppContext) -> bool;
422 fn boxed_clone(&self) -> Box<dyn ItemHandle>;
423 fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>>;
424 fn added_to_pane(
425 &self,
426 workspace: &mut Workspace,
427 pane: ViewHandle<Pane>,
428 cx: &mut ViewContext<Workspace>,
429 );
430 fn deactivated(&self, cx: &mut MutableAppContext);
431 fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool;
432 fn id(&self) -> usize;
433 fn to_any(&self) -> AnyViewHandle;
434 fn is_dirty(&self, cx: &AppContext) -> bool;
435 fn has_conflict(&self, cx: &AppContext) -> bool;
436 fn can_save(&self, cx: &AppContext) -> bool;
437 fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>>;
438 fn save_as(
439 &self,
440 project: ModelHandle<Project>,
441 abs_path: PathBuf,
442 cx: &mut MutableAppContext,
443 ) -> Task<Result<()>>;
444 fn reload(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext)
445 -> Task<Result<()>>;
446 fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle>;
447 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
448 fn on_release(
449 &self,
450 cx: &mut MutableAppContext,
451 callback: Box<dyn FnOnce(&mut MutableAppContext)>,
452 ) -> gpui::Subscription;
453}
454
455pub trait WeakItemHandle {
456 fn id(&self) -> usize;
457 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>>;
458}
459
460impl dyn ItemHandle {
461 pub fn downcast<T: View>(&self) -> Option<ViewHandle<T>> {
462 self.to_any().downcast()
463 }
464
465 pub fn act_as<T: View>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
466 self.act_as_type(TypeId::of::<T>(), cx)
467 .and_then(|t| t.downcast())
468 }
469}
470
471impl<T: Item> ItemHandle for ViewHandle<T> {
472 fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>> {
473 self.read(cx).tab_description(detail, cx)
474 }
475
476 fn tab_content(
477 &self,
478 detail: Option<usize>,
479 style: &theme::Tab,
480 cx: &AppContext,
481 ) -> ElementBox {
482 self.read(cx).tab_content(detail, style, cx)
483 }
484
485 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
486 self.read(cx).project_path(cx)
487 }
488
489 fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
490 self.read(cx).project_entry_ids(cx)
491 }
492
493 fn is_singleton(&self, cx: &AppContext) -> bool {
494 self.read(cx).is_singleton(cx)
495 }
496
497 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
498 Box::new(self.clone())
499 }
500
501 fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>> {
502 self.update(cx, |item, cx| {
503 cx.add_option_view(|cx| item.clone_on_split(cx))
504 })
505 .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
506 }
507
508 fn added_to_pane(
509 &self,
510 workspace: &mut Workspace,
511 pane: ViewHandle<Pane>,
512 cx: &mut ViewContext<Workspace>,
513 ) {
514 let history = pane.read(cx).nav_history_for_item(self);
515 self.update(cx, |this, cx| this.set_nav_history(history, cx));
516
517 if let Some(followed_item) = self.to_followable_item_handle(cx) {
518 if let Some(message) = followed_item.to_state_proto(cx) {
519 workspace.update_followers(
520 proto::update_followers::Variant::CreateView(proto::View {
521 id: followed_item.id() as u64,
522 variant: Some(message),
523 leader_id: workspace.leader_for_pane(&pane).map(|id| id.0),
524 }),
525 cx,
526 );
527 }
528 }
529
530 let mut pending_autosave = None;
531 let mut cancel_pending_autosave = oneshot::channel::<()>().0;
532 let pending_update = Rc::new(RefCell::new(None));
533 let pending_update_scheduled = Rc::new(AtomicBool::new(false));
534 let pane = pane.downgrade();
535 cx.subscribe(self, move |workspace, item, event, cx| {
536 let pane = if let Some(pane) = pane.upgrade(cx) {
537 pane
538 } else {
539 log::error!("unexpected item event after pane was dropped");
540 return;
541 };
542
543 if let Some(item) = item.to_followable_item_handle(cx) {
544 let leader_id = workspace.leader_for_pane(&pane);
545
546 if leader_id.is_some() && item.should_unfollow_on_event(event, cx) {
547 workspace.unfollow(&pane, cx);
548 }
549
550 if item.add_event_to_update_proto(event, &mut *pending_update.borrow_mut(), cx)
551 && !pending_update_scheduled.load(SeqCst)
552 {
553 pending_update_scheduled.store(true, SeqCst);
554 cx.after_window_update({
555 let pending_update = pending_update.clone();
556 let pending_update_scheduled = pending_update_scheduled.clone();
557 move |this, cx| {
558 pending_update_scheduled.store(false, SeqCst);
559 this.update_followers(
560 proto::update_followers::Variant::UpdateView(proto::UpdateView {
561 id: item.id() as u64,
562 variant: pending_update.borrow_mut().take(),
563 leader_id: leader_id.map(|id| id.0),
564 }),
565 cx,
566 );
567 }
568 });
569 }
570 }
571
572 if T::should_close_item_on_event(event) {
573 Pane::close_item(workspace, pane, item.id(), cx).detach_and_log_err(cx);
574 return;
575 }
576
577 if T::should_activate_item_on_event(event) {
578 pane.update(cx, |pane, cx| {
579 if let Some(ix) = pane.index_for_item(&item) {
580 pane.activate_item(ix, true, true, false, cx);
581 pane.activate(cx);
582 }
583 });
584 }
585
586 if T::should_update_tab_on_event(event) {
587 pane.update(cx, |_, cx| {
588 cx.emit(pane::Event::ChangeItemTitle);
589 cx.notify();
590 });
591 }
592
593 if T::is_edit_event(event) {
594 if let Autosave::AfterDelay { milliseconds } = cx.global::<Settings>().autosave {
595 let prev_autosave = pending_autosave.take().unwrap_or(Task::ready(Some(())));
596 let (cancel_tx, mut cancel_rx) = oneshot::channel::<()>();
597 let prev_cancel_tx = mem::replace(&mut cancel_pending_autosave, cancel_tx);
598 let project = workspace.project.downgrade();
599 let _ = prev_cancel_tx.send(());
600 pending_autosave = Some(cx.spawn_weak(|_, mut cx| async move {
601 let mut timer = cx
602 .background()
603 .timer(Duration::from_millis(milliseconds))
604 .fuse();
605 prev_autosave.await;
606 futures::select_biased! {
607 _ = cancel_rx => return None,
608 _ = timer => {}
609 }
610
611 let project = project.upgrade(&cx)?;
612 cx.update(|cx| Pane::autosave_item(&item, project, cx))
613 .await
614 .log_err();
615 None
616 }));
617 }
618 }
619 })
620 .detach();
621
622 cx.observe_focus(self, move |workspace, item, focused, cx| {
623 if !focused && cx.global::<Settings>().autosave == Autosave::OnFocusChange {
624 Pane::autosave_item(&item, workspace.project.clone(), cx).detach_and_log_err(cx);
625 }
626 })
627 .detach();
628 }
629
630 fn deactivated(&self, cx: &mut MutableAppContext) {
631 self.update(cx, |this, cx| this.deactivated(cx));
632 }
633
634 fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool {
635 self.update(cx, |this, cx| this.navigate(data, cx))
636 }
637
638 fn id(&self) -> usize {
639 self.id()
640 }
641
642 fn to_any(&self) -> AnyViewHandle {
643 self.into()
644 }
645
646 fn is_dirty(&self, cx: &AppContext) -> bool {
647 self.read(cx).is_dirty(cx)
648 }
649
650 fn has_conflict(&self, cx: &AppContext) -> bool {
651 self.read(cx).has_conflict(cx)
652 }
653
654 fn can_save(&self, cx: &AppContext) -> bool {
655 self.read(cx).can_save(cx)
656 }
657
658 fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>> {
659 self.update(cx, |item, cx| item.save(project, cx))
660 }
661
662 fn save_as(
663 &self,
664 project: ModelHandle<Project>,
665 abs_path: PathBuf,
666 cx: &mut MutableAppContext,
667 ) -> Task<anyhow::Result<()>> {
668 self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
669 }
670
671 fn reload(
672 &self,
673 project: ModelHandle<Project>,
674 cx: &mut MutableAppContext,
675 ) -> Task<Result<()>> {
676 self.update(cx, |item, cx| item.reload(project, cx))
677 }
678
679 fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle> {
680 self.read(cx).act_as_type(type_id, self, cx)
681 }
682
683 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
684 if cx.has_global::<FollowableItemBuilders>() {
685 let builders = cx.global::<FollowableItemBuilders>();
686 let item = self.to_any();
687 Some(builders.get(&item.view_type())?.1(item))
688 } else {
689 None
690 }
691 }
692
693 fn on_release(
694 &self,
695 cx: &mut MutableAppContext,
696 callback: Box<dyn FnOnce(&mut MutableAppContext)>,
697 ) -> gpui::Subscription {
698 cx.observe_release(self, move |_, cx| callback(cx))
699 }
700}
701
702impl Into<AnyViewHandle> for Box<dyn ItemHandle> {
703 fn into(self) -> AnyViewHandle {
704 self.to_any()
705 }
706}
707
708impl Clone for Box<dyn ItemHandle> {
709 fn clone(&self) -> Box<dyn ItemHandle> {
710 self.boxed_clone()
711 }
712}
713
714impl<T: Item> WeakItemHandle for WeakViewHandle<T> {
715 fn id(&self) -> usize {
716 self.id()
717 }
718
719 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
720 self.upgrade(cx).map(|v| Box::new(v) as Box<dyn ItemHandle>)
721 }
722}
723
724pub trait Notification: View {
725 fn should_dismiss_notification_on_event(&self, event: &<Self as Entity>::Event) -> bool;
726}
727
728pub trait NotificationHandle {
729 fn id(&self) -> usize;
730 fn to_any(&self) -> AnyViewHandle;
731}
732
733impl<T: Notification> NotificationHandle for ViewHandle<T> {
734 fn id(&self) -> usize {
735 self.id()
736 }
737
738 fn to_any(&self) -> AnyViewHandle {
739 self.into()
740 }
741}
742
743impl Into<AnyViewHandle> for &dyn NotificationHandle {
744 fn into(self) -> AnyViewHandle {
745 self.to_any()
746 }
747}
748
749impl AppState {
750 #[cfg(any(test, feature = "test-support"))]
751 pub fn test(cx: &mut MutableAppContext) -> Arc<Self> {
752 let settings = Settings::test(cx);
753 cx.set_global(settings);
754
755 let fs = project::FakeFs::new(cx.background().clone());
756 let languages = Arc::new(LanguageRegistry::test());
757 let http_client = client::test::FakeHttpClient::with_404_response();
758 let client = Client::new(http_client.clone());
759 let project_store = cx.add_model(|_| ProjectStore::new(project::Db::open_fake()));
760 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
761 let themes = ThemeRegistry::new((), cx.font_cache().clone());
762 Arc::new(Self {
763 client,
764 themes,
765 fs,
766 languages,
767 user_store,
768 project_store,
769 initialize_workspace: |_, _, _| {},
770 build_window_options: || Default::default(),
771 })
772 }
773}
774
775pub enum Event {
776 PaneAdded(ViewHandle<Pane>),
777 ContactRequestedJoin(u64),
778}
779
780pub struct Workspace {
781 weak_self: WeakViewHandle<Self>,
782 client: Arc<Client>,
783 user_store: ModelHandle<client::UserStore>,
784 remote_entity_subscription: Option<Subscription>,
785 fs: Arc<dyn Fs>,
786 modal: Option<AnyViewHandle>,
787 center: PaneGroup,
788 left_sidebar: ViewHandle<Sidebar>,
789 right_sidebar: ViewHandle<Sidebar>,
790 panes: Vec<ViewHandle<Pane>>,
791 active_pane: ViewHandle<Pane>,
792 status_bar: ViewHandle<StatusBar>,
793 notifications: Vec<(TypeId, usize, Box<dyn NotificationHandle>)>,
794 project: ModelHandle<Project>,
795 leader_state: LeaderState,
796 follower_states_by_leader: FollowerStatesByLeader,
797 last_leaders_by_pane: HashMap<WeakViewHandle<Pane>, PeerId>,
798 window_edited: bool,
799 _observe_current_user: Task<()>,
800}
801
802#[derive(Default)]
803struct LeaderState {
804 followers: HashSet<PeerId>,
805}
806
807type FollowerStatesByLeader = HashMap<PeerId, HashMap<ViewHandle<Pane>, FollowerState>>;
808
809#[derive(Default)]
810struct FollowerState {
811 active_view_id: Option<u64>,
812 items_by_leader_view_id: HashMap<u64, FollowerItem>,
813}
814
815#[derive(Debug)]
816enum FollowerItem {
817 Loading(Vec<proto::update_view::Variant>),
818 Loaded(Box<dyn FollowableItemHandle>),
819}
820
821impl Workspace {
822 pub fn new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
823 cx.observe_window_activation(Self::on_window_activation_changed)
824 .detach();
825 cx.observe(&project, |_, _, cx| cx.notify()).detach();
826 cx.subscribe(&project, move |this, _, event, cx| {
827 match event {
828 project::Event::RemoteIdChanged(remote_id) => {
829 this.project_remote_id_changed(*remote_id, cx);
830 }
831 project::Event::CollaboratorLeft(peer_id) => {
832 this.collaborator_left(*peer_id, cx);
833 }
834 project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded => {
835 this.update_window_title(cx);
836 }
837 project::Event::DisconnectedFromHost => {
838 this.update_window_edited(cx);
839 cx.blur();
840 }
841 _ => {}
842 }
843 cx.notify()
844 })
845 .detach();
846
847 let pane = cx.add_view(|cx| Pane::new(cx));
848 let pane_id = pane.id();
849 cx.subscribe(&pane, move |this, _, event, cx| {
850 this.handle_pane_event(pane_id, event, cx)
851 })
852 .detach();
853 cx.focus(&pane);
854 cx.emit(Event::PaneAdded(pane.clone()));
855
856 let fs = project.read(cx).fs().clone();
857 let user_store = project.read(cx).user_store();
858 let client = project.read(cx).client();
859 let mut current_user = user_store.read(cx).watch_current_user().clone();
860 let mut connection_status = client.status().clone();
861 let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
862 current_user.recv().await;
863 connection_status.recv().await;
864 let mut stream =
865 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
866
867 while stream.recv().await.is_some() {
868 cx.update(|cx| {
869 if let Some(this) = this.upgrade(cx) {
870 this.update(cx, |_, cx| cx.notify());
871 }
872 })
873 }
874 });
875
876 let weak_self = cx.weak_handle();
877
878 cx.emit_global(WorkspaceCreated(weak_self.clone()));
879
880 let left_sidebar = cx.add_view(|_| Sidebar::new(Side::Left));
881 let right_sidebar = cx.add_view(|_| Sidebar::new(Side::Right));
882 let left_sidebar_buttons = cx.add_view(|cx| SidebarButtons::new(left_sidebar.clone(), cx));
883 let right_sidebar_buttons =
884 cx.add_view(|cx| SidebarButtons::new(right_sidebar.clone(), cx));
885 let status_bar = cx.add_view(|cx| {
886 let mut status_bar = StatusBar::new(&pane.clone(), cx);
887 status_bar.add_left_item(left_sidebar_buttons, cx);
888 status_bar.add_right_item(right_sidebar_buttons, cx);
889 status_bar
890 });
891
892 let mut this = Workspace {
893 modal: None,
894 weak_self,
895 center: PaneGroup::new(pane.clone()),
896 panes: vec![pane.clone()],
897 active_pane: pane.clone(),
898 status_bar,
899 notifications: Default::default(),
900 client,
901 remote_entity_subscription: None,
902 user_store,
903 fs,
904 left_sidebar,
905 right_sidebar,
906 project,
907 leader_state: Default::default(),
908 follower_states_by_leader: Default::default(),
909 last_leaders_by_pane: Default::default(),
910 window_edited: false,
911 _observe_current_user,
912 };
913 this.project_remote_id_changed(this.project.read(cx).remote_id(), cx);
914 cx.defer(|this, cx| this.update_window_title(cx));
915
916 this
917 }
918
919 pub fn weak_handle(&self) -> WeakViewHandle<Self> {
920 self.weak_self.clone()
921 }
922
923 pub fn left_sidebar(&self) -> &ViewHandle<Sidebar> {
924 &self.left_sidebar
925 }
926
927 pub fn right_sidebar(&self) -> &ViewHandle<Sidebar> {
928 &self.right_sidebar
929 }
930
931 pub fn status_bar(&self) -> &ViewHandle<StatusBar> {
932 &self.status_bar
933 }
934
935 pub fn user_store(&self) -> &ModelHandle<UserStore> {
936 &self.user_store
937 }
938
939 pub fn project(&self) -> &ModelHandle<Project> {
940 &self.project
941 }
942
943 /// Call the given callback with a workspace whose project is local.
944 ///
945 /// If the given workspace has a local project, then it will be passed
946 /// to the callback. Otherwise, a new empty window will be created.
947 pub fn with_local_workspace<T, F>(
948 &mut self,
949 cx: &mut ViewContext<Self>,
950 app_state: Arc<AppState>,
951 mut callback: F,
952 ) -> T
953 where
954 T: 'static,
955 F: FnMut(&mut Workspace, &mut ViewContext<Workspace>) -> T,
956 {
957 if self.project.read(cx).is_local() {
958 callback(self, cx)
959 } else {
960 let (_, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
961 let mut workspace = Workspace::new(
962 Project::local(
963 false,
964 app_state.client.clone(),
965 app_state.user_store.clone(),
966 app_state.project_store.clone(),
967 app_state.languages.clone(),
968 app_state.fs.clone(),
969 cx,
970 ),
971 cx,
972 );
973 (app_state.initialize_workspace)(&mut workspace, &app_state, cx);
974 workspace
975 });
976 workspace.update(cx, callback)
977 }
978 }
979
980 pub fn worktrees<'a>(
981 &self,
982 cx: &'a AppContext,
983 ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
984 self.project.read(cx).worktrees(cx)
985 }
986
987 pub fn visible_worktrees<'a>(
988 &self,
989 cx: &'a AppContext,
990 ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
991 self.project.read(cx).visible_worktrees(cx)
992 }
993
994 pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
995 let futures = self
996 .worktrees(cx)
997 .filter_map(|worktree| worktree.read(cx).as_local())
998 .map(|worktree| worktree.scan_complete())
999 .collect::<Vec<_>>();
1000 async move {
1001 for future in futures {
1002 future.await;
1003 }
1004 }
1005 }
1006
1007 pub fn close(
1008 &mut self,
1009 _: &CloseWindow,
1010 cx: &mut ViewContext<Self>,
1011 ) -> Option<Task<Result<()>>> {
1012 let prepare = self.prepare_to_close(cx);
1013 Some(cx.spawn(|this, mut cx| async move {
1014 if prepare.await? {
1015 this.update(&mut cx, |_, cx| {
1016 let window_id = cx.window_id();
1017 cx.remove_window(window_id);
1018 });
1019 }
1020 Ok(())
1021 }))
1022 }
1023
1024 pub fn prepare_to_close(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<bool>> {
1025 self.save_all_internal(true, cx)
1026 }
1027
1028 fn save_all(&mut self, _: &SaveAll, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
1029 let save_all = self.save_all_internal(false, cx);
1030 Some(cx.foreground().spawn(async move {
1031 save_all.await?;
1032 Ok(())
1033 }))
1034 }
1035
1036 fn save_all_internal(
1037 &mut self,
1038 should_prompt_to_save: bool,
1039 cx: &mut ViewContext<Self>,
1040 ) -> Task<Result<bool>> {
1041 if self.project.read(cx).is_read_only() {
1042 return Task::ready(Ok(true));
1043 }
1044
1045 let dirty_items = self
1046 .panes
1047 .iter()
1048 .flat_map(|pane| {
1049 pane.read(cx).items().filter_map(|item| {
1050 if item.is_dirty(cx) {
1051 Some((pane.clone(), item.boxed_clone()))
1052 } else {
1053 None
1054 }
1055 })
1056 })
1057 .collect::<Vec<_>>();
1058
1059 let project = self.project.clone();
1060 cx.spawn_weak(|_, mut cx| async move {
1061 for (pane, item) in dirty_items {
1062 let (singleton, project_entry_ids) =
1063 cx.read(|cx| (item.is_singleton(cx), item.project_entry_ids(cx)));
1064 if singleton || !project_entry_ids.is_empty() {
1065 if let Some(ix) =
1066 pane.read_with(&cx, |pane, _| pane.index_for_item(item.as_ref()))
1067 {
1068 if !Pane::save_item(
1069 project.clone(),
1070 &pane,
1071 ix,
1072 &item,
1073 should_prompt_to_save,
1074 &mut cx,
1075 )
1076 .await?
1077 {
1078 return Ok(false);
1079 }
1080 }
1081 }
1082 }
1083 Ok(true)
1084 })
1085 }
1086
1087 pub fn open_paths(
1088 &mut self,
1089 mut abs_paths: Vec<PathBuf>,
1090 visible: bool,
1091 cx: &mut ViewContext<Self>,
1092 ) -> Task<Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>> {
1093 let fs = self.fs.clone();
1094
1095 // Sort the paths to ensure we add worktrees for parents before their children.
1096 abs_paths.sort_unstable();
1097 cx.spawn(|this, mut cx| async move {
1098 let mut project_paths = Vec::new();
1099 for path in &abs_paths {
1100 project_paths.push(
1101 this.update(&mut cx, |this, cx| {
1102 this.project_path_for_path(path, visible, cx)
1103 })
1104 .await
1105 .log_err(),
1106 );
1107 }
1108
1109 let tasks = abs_paths
1110 .iter()
1111 .cloned()
1112 .zip(project_paths.into_iter())
1113 .map(|(abs_path, project_path)| {
1114 let this = this.clone();
1115 cx.spawn(|mut cx| {
1116 let fs = fs.clone();
1117 async move {
1118 let (_worktree, project_path) = project_path?;
1119 if fs.is_file(&abs_path).await {
1120 Some(
1121 this.update(&mut cx, |this, cx| {
1122 this.open_path(project_path, true, cx)
1123 })
1124 .await,
1125 )
1126 } else {
1127 None
1128 }
1129 }
1130 })
1131 })
1132 .collect::<Vec<_>>();
1133
1134 futures::future::join_all(tasks).await
1135 })
1136 }
1137
1138 fn add_folder_to_project(&mut self, _: &AddFolderToProject, cx: &mut ViewContext<Self>) {
1139 let mut paths = cx.prompt_for_paths(PathPromptOptions {
1140 files: false,
1141 directories: true,
1142 multiple: true,
1143 });
1144 cx.spawn(|this, mut cx| async move {
1145 if let Some(paths) = paths.recv().await.flatten() {
1146 let results = this
1147 .update(&mut cx, |this, cx| this.open_paths(paths, true, cx))
1148 .await;
1149 for result in results {
1150 if let Some(result) = result {
1151 result.log_err();
1152 }
1153 }
1154 }
1155 })
1156 .detach();
1157 }
1158
1159 fn remove_folder_from_project(
1160 &mut self,
1161 RemoveWorktreeFromProject(worktree_id): &RemoveWorktreeFromProject,
1162 cx: &mut ViewContext<Self>,
1163 ) {
1164 self.project
1165 .update(cx, |project, cx| project.remove_worktree(*worktree_id, cx));
1166 }
1167
1168 fn toggle_project_online(&mut self, action: &ToggleProjectOnline, cx: &mut ViewContext<Self>) {
1169 let project = action
1170 .project
1171 .clone()
1172 .unwrap_or_else(|| self.project.clone());
1173 project.update(cx, |project, cx| {
1174 let public = !project.is_online();
1175 project.set_online(public, cx);
1176 });
1177 }
1178
1179 fn project_path_for_path(
1180 &self,
1181 abs_path: &Path,
1182 visible: bool,
1183 cx: &mut ViewContext<Self>,
1184 ) -> Task<Result<(ModelHandle<Worktree>, ProjectPath)>> {
1185 let entry = self.project().update(cx, |project, cx| {
1186 project.find_or_create_local_worktree(abs_path, visible, cx)
1187 });
1188 cx.spawn(|_, cx| async move {
1189 let (worktree, path) = entry.await?;
1190 let worktree_id = worktree.read_with(&cx, |t, _| t.id());
1191 Ok((
1192 worktree,
1193 ProjectPath {
1194 worktree_id,
1195 path: path.into(),
1196 },
1197 ))
1198 })
1199 }
1200
1201 /// Returns the modal that was toggled closed if it was open.
1202 pub fn toggle_modal<V, F>(
1203 &mut self,
1204 cx: &mut ViewContext<Self>,
1205 add_view: F,
1206 ) -> Option<ViewHandle<V>>
1207 where
1208 V: 'static + View,
1209 F: FnOnce(&mut Self, &mut ViewContext<Self>) -> ViewHandle<V>,
1210 {
1211 cx.notify();
1212 // Whatever modal was visible is getting clobbered. If its the same type as V, then return
1213 // it. Otherwise, create a new modal and set it as active.
1214 let already_open_modal = self.modal.take().and_then(|modal| modal.downcast::<V>());
1215 if let Some(already_open_modal) = already_open_modal {
1216 cx.focus_self();
1217 Some(already_open_modal)
1218 } else {
1219 let modal = add_view(self, cx);
1220 cx.focus(&modal);
1221 self.modal = Some(modal.into());
1222 None
1223 }
1224 }
1225
1226 pub fn modal(&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/cloud_slash_12.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(MouseButton::Left, |_, 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(MouseButton::Left, move |_, cx| {
2035 cx.dispatch_action(ToggleFollow(peer_id))
2036 })
2037 .with_tooltip::<ToggleFollow, _>(
2038 peer_id.0 as usize,
2039 if is_followed {
2040 format!("Unfollow {}", peer_github_login)
2041 } else {
2042 format!("Follow {}", peer_github_login)
2043 },
2044 Some(Box::new(FollowNextCollaborator)),
2045 theme.tooltip.clone(),
2046 cx,
2047 )
2048 .boxed()
2049 } else {
2050 content
2051 }
2052 }
2053
2054 fn render_disconnected_overlay(&self, cx: &AppContext) -> Option<ElementBox> {
2055 if self.project.read(cx).is_read_only() {
2056 let theme = &cx.global::<Settings>().theme;
2057 Some(
2058 EventHandler::new(
2059 Label::new(
2060 "Your connection to the remote project has been lost.".to_string(),
2061 theme.workspace.disconnected_overlay.text.clone(),
2062 )
2063 .aligned()
2064 .contained()
2065 .with_style(theme.workspace.disconnected_overlay.container)
2066 .boxed(),
2067 )
2068 .capture_all::<Self>(0)
2069 .boxed(),
2070 )
2071 } else {
2072 None
2073 }
2074 }
2075
2076 fn render_notifications(&self, theme: &theme::Workspace) -> Option<ElementBox> {
2077 if self.notifications.is_empty() {
2078 None
2079 } else {
2080 Some(
2081 Flex::column()
2082 .with_children(self.notifications.iter().map(|(_, _, notification)| {
2083 ChildView::new(notification.as_ref())
2084 .contained()
2085 .with_style(theme.notification)
2086 .boxed()
2087 }))
2088 .constrained()
2089 .with_width(theme.notifications.width)
2090 .contained()
2091 .with_style(theme.notifications.container)
2092 .aligned()
2093 .bottom()
2094 .right()
2095 .boxed(),
2096 )
2097 }
2098 }
2099
2100 // RPC handlers
2101
2102 async fn handle_follow(
2103 this: ViewHandle<Self>,
2104 envelope: TypedEnvelope<proto::Follow>,
2105 _: Arc<Client>,
2106 mut cx: AsyncAppContext,
2107 ) -> Result<proto::FollowResponse> {
2108 this.update(&mut cx, |this, cx| {
2109 this.leader_state
2110 .followers
2111 .insert(envelope.original_sender_id()?);
2112
2113 let active_view_id = this
2114 .active_item(cx)
2115 .and_then(|i| i.to_followable_item_handle(cx))
2116 .map(|i| i.id() as u64);
2117 Ok(proto::FollowResponse {
2118 active_view_id,
2119 views: this
2120 .panes()
2121 .iter()
2122 .flat_map(|pane| {
2123 let leader_id = this.leader_for_pane(pane).map(|id| id.0);
2124 pane.read(cx).items().filter_map({
2125 let cx = &cx;
2126 move |item| {
2127 let id = item.id() as u64;
2128 let item = item.to_followable_item_handle(cx)?;
2129 let variant = item.to_state_proto(cx)?;
2130 Some(proto::View {
2131 id,
2132 leader_id,
2133 variant: Some(variant),
2134 })
2135 }
2136 })
2137 })
2138 .collect(),
2139 })
2140 })
2141 }
2142
2143 async fn handle_unfollow(
2144 this: ViewHandle<Self>,
2145 envelope: TypedEnvelope<proto::Unfollow>,
2146 _: Arc<Client>,
2147 mut cx: AsyncAppContext,
2148 ) -> Result<()> {
2149 this.update(&mut cx, |this, _| {
2150 this.leader_state
2151 .followers
2152 .remove(&envelope.original_sender_id()?);
2153 Ok(())
2154 })
2155 }
2156
2157 async fn handle_update_followers(
2158 this: ViewHandle<Self>,
2159 envelope: TypedEnvelope<proto::UpdateFollowers>,
2160 _: Arc<Client>,
2161 mut cx: AsyncAppContext,
2162 ) -> Result<()> {
2163 let leader_id = envelope.original_sender_id()?;
2164 match envelope
2165 .payload
2166 .variant
2167 .ok_or_else(|| anyhow!("invalid update"))?
2168 {
2169 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
2170 this.update(&mut cx, |this, cx| {
2171 this.update_leader_state(leader_id, cx, |state, _| {
2172 state.active_view_id = update_active_view.id;
2173 });
2174 Ok::<_, anyhow::Error>(())
2175 })
2176 }
2177 proto::update_followers::Variant::UpdateView(update_view) => {
2178 this.update(&mut cx, |this, cx| {
2179 let variant = update_view
2180 .variant
2181 .ok_or_else(|| anyhow!("missing update view variant"))?;
2182 this.update_leader_state(leader_id, cx, |state, cx| {
2183 let variant = variant.clone();
2184 match state
2185 .items_by_leader_view_id
2186 .entry(update_view.id)
2187 .or_insert(FollowerItem::Loading(Vec::new()))
2188 {
2189 FollowerItem::Loaded(item) => {
2190 item.apply_update_proto(variant, cx).log_err();
2191 }
2192 FollowerItem::Loading(updates) => updates.push(variant),
2193 }
2194 });
2195 Ok(())
2196 })
2197 }
2198 proto::update_followers::Variant::CreateView(view) => {
2199 let panes = this.read_with(&cx, |this, _| {
2200 this.follower_states_by_leader
2201 .get(&leader_id)
2202 .into_iter()
2203 .flat_map(|states_by_pane| states_by_pane.keys())
2204 .cloned()
2205 .collect()
2206 });
2207 Self::add_views_from_leader(this.clone(), leader_id, panes, vec![view], &mut cx)
2208 .await?;
2209 Ok(())
2210 }
2211 }
2212 .log_err();
2213
2214 Ok(())
2215 }
2216
2217 async fn add_views_from_leader(
2218 this: ViewHandle<Self>,
2219 leader_id: PeerId,
2220 panes: Vec<ViewHandle<Pane>>,
2221 views: Vec<proto::View>,
2222 cx: &mut AsyncAppContext,
2223 ) -> Result<()> {
2224 let project = this.read_with(cx, |this, _| this.project.clone());
2225 let replica_id = project
2226 .read_with(cx, |project, _| {
2227 project
2228 .collaborators()
2229 .get(&leader_id)
2230 .map(|c| c.replica_id)
2231 })
2232 .ok_or_else(|| anyhow!("no such collaborator {}", leader_id))?;
2233
2234 let item_builders = cx.update(|cx| {
2235 cx.default_global::<FollowableItemBuilders>()
2236 .values()
2237 .map(|b| b.0)
2238 .collect::<Vec<_>>()
2239 .clone()
2240 });
2241
2242 let mut item_tasks_by_pane = HashMap::default();
2243 for pane in panes {
2244 let mut item_tasks = Vec::new();
2245 let mut leader_view_ids = Vec::new();
2246 for view in &views {
2247 let mut variant = view.variant.clone();
2248 if variant.is_none() {
2249 Err(anyhow!("missing variant"))?;
2250 }
2251 for build_item in &item_builders {
2252 let task =
2253 cx.update(|cx| build_item(pane.clone(), project.clone(), &mut variant, cx));
2254 if let Some(task) = task {
2255 item_tasks.push(task);
2256 leader_view_ids.push(view.id);
2257 break;
2258 } else {
2259 assert!(variant.is_some());
2260 }
2261 }
2262 }
2263
2264 item_tasks_by_pane.insert(pane, (item_tasks, leader_view_ids));
2265 }
2266
2267 for (pane, (item_tasks, leader_view_ids)) in item_tasks_by_pane {
2268 let items = futures::future::try_join_all(item_tasks).await?;
2269 this.update(cx, |this, cx| {
2270 let state = this
2271 .follower_states_by_leader
2272 .get_mut(&leader_id)?
2273 .get_mut(&pane)?;
2274
2275 for (id, item) in leader_view_ids.into_iter().zip(items) {
2276 item.set_leader_replica_id(Some(replica_id), cx);
2277 match state.items_by_leader_view_id.entry(id) {
2278 hash_map::Entry::Occupied(e) => {
2279 let e = e.into_mut();
2280 if let FollowerItem::Loading(updates) = e {
2281 for update in updates.drain(..) {
2282 item.apply_update_proto(update, cx)
2283 .context("failed to apply view update")
2284 .log_err();
2285 }
2286 }
2287 *e = FollowerItem::Loaded(item);
2288 }
2289 hash_map::Entry::Vacant(e) => {
2290 e.insert(FollowerItem::Loaded(item));
2291 }
2292 }
2293 }
2294
2295 Some(())
2296 });
2297 }
2298 this.update(cx, |this, cx| this.leader_updated(leader_id, cx));
2299
2300 Ok(())
2301 }
2302
2303 fn update_followers(
2304 &self,
2305 update: proto::update_followers::Variant,
2306 cx: &AppContext,
2307 ) -> Option<()> {
2308 let project_id = self.project.read(cx).remote_id()?;
2309 if !self.leader_state.followers.is_empty() {
2310 self.client
2311 .send(proto::UpdateFollowers {
2312 project_id,
2313 follower_ids: self.leader_state.followers.iter().map(|f| f.0).collect(),
2314 variant: Some(update),
2315 })
2316 .log_err();
2317 }
2318 None
2319 }
2320
2321 pub fn leader_for_pane(&self, pane: &ViewHandle<Pane>) -> Option<PeerId> {
2322 self.follower_states_by_leader
2323 .iter()
2324 .find_map(|(leader_id, state)| {
2325 if state.contains_key(pane) {
2326 Some(*leader_id)
2327 } else {
2328 None
2329 }
2330 })
2331 }
2332
2333 fn update_leader_state(
2334 &mut self,
2335 leader_id: PeerId,
2336 cx: &mut ViewContext<Self>,
2337 mut update_fn: impl FnMut(&mut FollowerState, &mut ViewContext<Self>),
2338 ) {
2339 for (_, state) in self
2340 .follower_states_by_leader
2341 .get_mut(&leader_id)
2342 .into_iter()
2343 .flatten()
2344 {
2345 update_fn(state, cx);
2346 }
2347 self.leader_updated(leader_id, cx);
2348 }
2349
2350 fn leader_updated(&mut self, leader_id: PeerId, cx: &mut ViewContext<Self>) -> Option<()> {
2351 let mut items_to_add = Vec::new();
2352 for (pane, state) in self.follower_states_by_leader.get(&leader_id)? {
2353 if let Some(active_item) = state
2354 .active_view_id
2355 .and_then(|id| state.items_by_leader_view_id.get(&id))
2356 {
2357 if let FollowerItem::Loaded(item) = active_item {
2358 items_to_add.push((pane.clone(), item.boxed_clone()));
2359 }
2360 }
2361 }
2362
2363 for (pane, item) in items_to_add {
2364 Pane::add_item(self, pane.clone(), item.boxed_clone(), false, false, cx);
2365 if pane == self.active_pane {
2366 pane.update(cx, |pane, cx| pane.focus_active_item(cx));
2367 }
2368 cx.notify();
2369 }
2370 None
2371 }
2372
2373 fn on_window_activation_changed(&mut self, active: bool, cx: &mut ViewContext<Self>) {
2374 if !active
2375 && matches!(
2376 cx.global::<Settings>().autosave,
2377 Autosave::OnWindowChange | Autosave::OnFocusChange
2378 )
2379 {
2380 for pane in &self.panes {
2381 pane.update(cx, |pane, cx| {
2382 for item in pane.items() {
2383 Pane::autosave_item(item.as_ref(), self.project.clone(), cx)
2384 .detach_and_log_err(cx);
2385 }
2386 });
2387 }
2388 }
2389 }
2390}
2391
2392impl Entity for Workspace {
2393 type Event = Event;
2394}
2395
2396impl View for Workspace {
2397 fn ui_name() -> &'static str {
2398 "Workspace"
2399 }
2400
2401 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
2402 let theme = cx.global::<Settings>().theme.clone();
2403 Stack::new()
2404 .with_child(
2405 Flex::column()
2406 .with_child(self.render_titlebar(&theme, cx))
2407 .with_child(
2408 Stack::new()
2409 .with_child({
2410 Flex::row()
2411 .with_children(
2412 if self.left_sidebar.read(cx).active_item().is_some() {
2413 Some(
2414 ChildView::new(&self.left_sidebar)
2415 .flex(0.8, false)
2416 .boxed(),
2417 )
2418 } else {
2419 None
2420 },
2421 )
2422 .with_child(
2423 FlexItem::new(self.center.render(
2424 &theme,
2425 &self.follower_states_by_leader,
2426 self.project.read(cx).collaborators(),
2427 ))
2428 .flex(1., true)
2429 .boxed(),
2430 )
2431 .with_children(
2432 if self.right_sidebar.read(cx).active_item().is_some() {
2433 Some(
2434 ChildView::new(&self.right_sidebar)
2435 .flex(0.8, false)
2436 .boxed(),
2437 )
2438 } else {
2439 None
2440 },
2441 )
2442 .boxed()
2443 })
2444 .with_children(self.modal.as_ref().map(|m| {
2445 ChildView::new(m)
2446 .contained()
2447 .with_style(theme.workspace.modal)
2448 .aligned()
2449 .top()
2450 .boxed()
2451 }))
2452 .with_children(self.render_notifications(&theme.workspace))
2453 .flex(1.0, true)
2454 .boxed(),
2455 )
2456 .with_child(ChildView::new(&self.status_bar).boxed())
2457 .contained()
2458 .with_background_color(theme.workspace.background)
2459 .boxed(),
2460 )
2461 .with_children(self.render_disconnected_overlay(cx))
2462 .named("workspace")
2463 }
2464
2465 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
2466 cx.focus(&self.active_pane);
2467 }
2468}
2469
2470pub trait WorkspaceHandle {
2471 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
2472}
2473
2474impl WorkspaceHandle for ViewHandle<Workspace> {
2475 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
2476 self.read(cx)
2477 .worktrees(cx)
2478 .flat_map(|worktree| {
2479 let worktree_id = worktree.read(cx).id();
2480 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
2481 worktree_id,
2482 path: f.path.clone(),
2483 })
2484 })
2485 .collect::<Vec<_>>()
2486 }
2487}
2488
2489pub struct AvatarRibbon {
2490 color: Color,
2491}
2492
2493impl AvatarRibbon {
2494 pub fn new(color: Color) -> AvatarRibbon {
2495 AvatarRibbon { color }
2496 }
2497}
2498
2499impl Element for AvatarRibbon {
2500 type LayoutState = ();
2501
2502 type PaintState = ();
2503
2504 fn layout(
2505 &mut self,
2506 constraint: gpui::SizeConstraint,
2507 _: &mut gpui::LayoutContext,
2508 ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
2509 (constraint.max, ())
2510 }
2511
2512 fn paint(
2513 &mut self,
2514 bounds: gpui::geometry::rect::RectF,
2515 _: gpui::geometry::rect::RectF,
2516 _: &mut Self::LayoutState,
2517 cx: &mut gpui::PaintContext,
2518 ) -> Self::PaintState {
2519 let mut path = PathBuilder::new();
2520 path.reset(bounds.lower_left());
2521 path.curve_to(
2522 bounds.origin() + vec2f(bounds.height(), 0.),
2523 bounds.origin(),
2524 );
2525 path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
2526 path.curve_to(bounds.lower_right(), bounds.upper_right());
2527 path.line_to(bounds.lower_left());
2528 cx.scene.push_path(path.build(self.color, None));
2529 }
2530
2531 fn dispatch_event(
2532 &mut self,
2533 _: &gpui::Event,
2534 _: RectF,
2535 _: RectF,
2536 _: &mut Self::LayoutState,
2537 _: &mut Self::PaintState,
2538 _: &mut gpui::EventContext,
2539 ) -> bool {
2540 false
2541 }
2542
2543 fn debug(
2544 &self,
2545 bounds: gpui::geometry::rect::RectF,
2546 _: &Self::LayoutState,
2547 _: &Self::PaintState,
2548 _: &gpui::DebugContext,
2549 ) -> gpui::json::Value {
2550 json::json!({
2551 "type": "AvatarRibbon",
2552 "bounds": bounds.to_json(),
2553 "color": self.color.to_json(),
2554 })
2555 }
2556}
2557
2558impl std::fmt::Debug for OpenPaths {
2559 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2560 f.debug_struct("OpenPaths")
2561 .field("paths", &self.paths)
2562 .finish()
2563 }
2564}
2565
2566fn open(_: &Open, cx: &mut MutableAppContext) {
2567 let mut paths = cx.prompt_for_paths(PathPromptOptions {
2568 files: true,
2569 directories: true,
2570 multiple: true,
2571 });
2572 cx.spawn(|mut cx| async move {
2573 if let Some(paths) = paths.recv().await.flatten() {
2574 cx.update(|cx| cx.dispatch_global_action(OpenPaths { paths }));
2575 }
2576 })
2577 .detach();
2578}
2579
2580pub struct WorkspaceCreated(WeakViewHandle<Workspace>);
2581
2582pub fn activate_workspace_for_project(
2583 cx: &mut MutableAppContext,
2584 predicate: impl Fn(&mut Project, &mut ModelContext<Project>) -> bool,
2585) -> Option<ViewHandle<Workspace>> {
2586 for window_id in cx.window_ids().collect::<Vec<_>>() {
2587 if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
2588 let project = workspace_handle.read(cx).project.clone();
2589 if project.update(cx, &predicate) {
2590 cx.activate_window(window_id);
2591 return Some(workspace_handle);
2592 }
2593 }
2594 }
2595 None
2596}
2597
2598pub fn open_paths(
2599 abs_paths: &[PathBuf],
2600 app_state: &Arc<AppState>,
2601 cx: &mut MutableAppContext,
2602) -> Task<(
2603 ViewHandle<Workspace>,
2604 Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>,
2605)> {
2606 log::info!("open paths {:?}", abs_paths);
2607
2608 // Open paths in existing workspace if possible
2609 let existing =
2610 activate_workspace_for_project(cx, |project, cx| project.contains_paths(abs_paths, cx));
2611
2612 let app_state = app_state.clone();
2613 let abs_paths = abs_paths.to_vec();
2614 cx.spawn(|mut cx| async move {
2615 let mut new_project = None;
2616 let workspace = if let Some(existing) = existing {
2617 existing
2618 } else {
2619 let contains_directory =
2620 futures::future::join_all(abs_paths.iter().map(|path| app_state.fs.is_file(path)))
2621 .await
2622 .contains(&false);
2623
2624 cx.add_window((app_state.build_window_options)(), |cx| {
2625 let project = Project::local(
2626 false,
2627 app_state.client.clone(),
2628 app_state.user_store.clone(),
2629 app_state.project_store.clone(),
2630 app_state.languages.clone(),
2631 app_state.fs.clone(),
2632 cx,
2633 );
2634 new_project = Some(project.clone());
2635 let mut workspace = Workspace::new(project, cx);
2636 (app_state.initialize_workspace)(&mut workspace, &app_state, cx);
2637 if contains_directory {
2638 workspace.toggle_sidebar(Side::Left, cx);
2639 }
2640 workspace
2641 })
2642 .1
2643 };
2644
2645 let items = workspace
2646 .update(&mut cx, |workspace, cx| {
2647 workspace.open_paths(abs_paths, true, cx)
2648 })
2649 .await;
2650
2651 if let Some(project) = new_project {
2652 project
2653 .update(&mut cx, |project, cx| project.restore_state(cx))
2654 .await
2655 .log_err();
2656 }
2657
2658 (workspace, items)
2659 })
2660}
2661
2662pub fn join_project(
2663 contact: Arc<Contact>,
2664 project_index: usize,
2665 app_state: &Arc<AppState>,
2666 cx: &mut MutableAppContext,
2667) {
2668 let project_id = contact.projects[project_index].id;
2669
2670 for window_id in cx.window_ids().collect::<Vec<_>>() {
2671 if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
2672 if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
2673 cx.activate_window(window_id);
2674 return;
2675 }
2676 }
2677 }
2678
2679 cx.add_window((app_state.build_window_options)(), |cx| {
2680 WaitingRoom::new(contact, project_index, app_state.clone(), cx)
2681 });
2682}
2683
2684fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
2685 let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
2686 let mut workspace = Workspace::new(
2687 Project::local(
2688 false,
2689 app_state.client.clone(),
2690 app_state.user_store.clone(),
2691 app_state.project_store.clone(),
2692 app_state.languages.clone(),
2693 app_state.fs.clone(),
2694 cx,
2695 ),
2696 cx,
2697 );
2698 (app_state.initialize_workspace)(&mut workspace, app_state, cx);
2699 workspace
2700 });
2701 cx.dispatch_action(window_id, vec![workspace.id()], &NewFile);
2702}
2703
2704#[cfg(test)]
2705mod tests {
2706 use std::cell::Cell;
2707
2708 use super::*;
2709 use gpui::{executor::Deterministic, ModelHandle, TestAppContext, ViewContext};
2710 use project::{FakeFs, Project, ProjectEntryId};
2711 use serde_json::json;
2712
2713 #[gpui::test]
2714 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
2715 cx.foreground().forbid_parking();
2716 Settings::test_async(cx);
2717
2718 let fs = FakeFs::new(cx.background());
2719 let project = Project::test(fs, [], cx).await;
2720 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2721
2722 // Adding an item with no ambiguity renders the tab without detail.
2723 let item1 = cx.add_view(window_id, |_| {
2724 let mut item = TestItem::new();
2725 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
2726 item
2727 });
2728 workspace.update(cx, |workspace, cx| {
2729 workspace.add_item(Box::new(item1.clone()), cx);
2730 });
2731 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), None));
2732
2733 // Adding an item that creates ambiguity increases the level of detail on
2734 // both tabs.
2735 let item2 = cx.add_view(window_id, |_| {
2736 let mut item = TestItem::new();
2737 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
2738 item
2739 });
2740 workspace.update(cx, |workspace, cx| {
2741 workspace.add_item(Box::new(item2.clone()), cx);
2742 });
2743 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2744 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2745
2746 // Adding an item that creates ambiguity increases the level of detail only
2747 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
2748 // we stop at the highest detail available.
2749 let item3 = cx.add_view(window_id, |_| {
2750 let mut item = TestItem::new();
2751 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
2752 item
2753 });
2754 workspace.update(cx, |workspace, cx| {
2755 workspace.add_item(Box::new(item3.clone()), cx);
2756 });
2757 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
2758 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
2759 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
2760 }
2761
2762 #[gpui::test]
2763 async fn test_tracking_active_path(cx: &mut TestAppContext) {
2764 cx.foreground().forbid_parking();
2765 Settings::test_async(cx);
2766 let fs = FakeFs::new(cx.background());
2767 fs.insert_tree(
2768 "/root1",
2769 json!({
2770 "one.txt": "",
2771 "two.txt": "",
2772 }),
2773 )
2774 .await;
2775 fs.insert_tree(
2776 "/root2",
2777 json!({
2778 "three.txt": "",
2779 }),
2780 )
2781 .await;
2782
2783 let project = Project::test(fs, ["root1".as_ref()], cx).await;
2784 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2785 let worktree_id = project.read_with(cx, |project, cx| {
2786 project.worktrees(cx).next().unwrap().read(cx).id()
2787 });
2788
2789 let item1 = cx.add_view(window_id, |_| {
2790 let mut item = TestItem::new();
2791 item.project_path = Some((worktree_id, "one.txt").into());
2792 item
2793 });
2794 let item2 = cx.add_view(window_id, |_| {
2795 let mut item = TestItem::new();
2796 item.project_path = Some((worktree_id, "two.txt").into());
2797 item
2798 });
2799
2800 // Add an item to an empty pane
2801 workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item1), cx));
2802 project.read_with(cx, |project, cx| {
2803 assert_eq!(
2804 project.active_entry(),
2805 project.entry_for_path(&(worktree_id, "one.txt").into(), cx)
2806 );
2807 });
2808 assert_eq!(
2809 cx.current_window_title(window_id).as_deref(),
2810 Some("one.txt — root1")
2811 );
2812
2813 // Add a second item to a non-empty pane
2814 workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item2), cx));
2815 assert_eq!(
2816 cx.current_window_title(window_id).as_deref(),
2817 Some("two.txt — root1")
2818 );
2819 project.read_with(cx, |project, cx| {
2820 assert_eq!(
2821 project.active_entry(),
2822 project.entry_for_path(&(worktree_id, "two.txt").into(), cx)
2823 );
2824 });
2825
2826 // Close the active item
2827 workspace
2828 .update(cx, |workspace, cx| {
2829 Pane::close_active_item(workspace, &Default::default(), cx).unwrap()
2830 })
2831 .await
2832 .unwrap();
2833 assert_eq!(
2834 cx.current_window_title(window_id).as_deref(),
2835 Some("one.txt — root1")
2836 );
2837 project.read_with(cx, |project, cx| {
2838 assert_eq!(
2839 project.active_entry(),
2840 project.entry_for_path(&(worktree_id, "one.txt").into(), cx)
2841 );
2842 });
2843
2844 // Add a project folder
2845 project
2846 .update(cx, |project, cx| {
2847 project.find_or_create_local_worktree("/root2", true, cx)
2848 })
2849 .await
2850 .unwrap();
2851 assert_eq!(
2852 cx.current_window_title(window_id).as_deref(),
2853 Some("one.txt — root1, root2")
2854 );
2855
2856 // Remove a project folder
2857 project.update(cx, |project, cx| {
2858 project.remove_worktree(worktree_id, cx);
2859 });
2860 assert_eq!(
2861 cx.current_window_title(window_id).as_deref(),
2862 Some("one.txt — root2")
2863 );
2864 }
2865
2866 #[gpui::test]
2867 async fn test_close_window(cx: &mut TestAppContext) {
2868 cx.foreground().forbid_parking();
2869 Settings::test_async(cx);
2870 let fs = FakeFs::new(cx.background());
2871 fs.insert_tree("/root", json!({ "one": "" })).await;
2872
2873 let project = Project::test(fs, ["root".as_ref()], cx).await;
2874 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project.clone(), cx));
2875
2876 // When there are no dirty items, there's nothing to do.
2877 let item1 = cx.add_view(window_id, |_| TestItem::new());
2878 workspace.update(cx, |w, cx| w.add_item(Box::new(item1.clone()), cx));
2879 let task = workspace.update(cx, |w, cx| w.prepare_to_close(cx));
2880 assert_eq!(task.await.unwrap(), true);
2881
2882 // When there are dirty untitled items, prompt to save each one. If the user
2883 // cancels any prompt, then abort.
2884 let item2 = cx.add_view(window_id, |_| {
2885 let mut item = TestItem::new();
2886 item.is_dirty = true;
2887 item
2888 });
2889 let item3 = cx.add_view(window_id, |_| {
2890 let mut item = TestItem::new();
2891 item.is_dirty = true;
2892 item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
2893 item
2894 });
2895 workspace.update(cx, |w, cx| {
2896 w.add_item(Box::new(item2.clone()), cx);
2897 w.add_item(Box::new(item3.clone()), cx);
2898 });
2899 let task = workspace.update(cx, |w, cx| w.prepare_to_close(cx));
2900 cx.foreground().run_until_parked();
2901 cx.simulate_prompt_answer(window_id, 2 /* cancel */);
2902 cx.foreground().run_until_parked();
2903 assert!(!cx.has_pending_prompt(window_id));
2904 assert_eq!(task.await.unwrap(), false);
2905 }
2906
2907 #[gpui::test]
2908 async fn test_close_pane_items(cx: &mut TestAppContext) {
2909 cx.foreground().forbid_parking();
2910 Settings::test_async(cx);
2911 let fs = FakeFs::new(cx.background());
2912
2913 let project = Project::test(fs, None, cx).await;
2914 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
2915
2916 let item1 = cx.add_view(window_id, |_| {
2917 let mut item = TestItem::new();
2918 item.is_dirty = true;
2919 item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
2920 item
2921 });
2922 let item2 = cx.add_view(window_id, |_| {
2923 let mut item = TestItem::new();
2924 item.is_dirty = true;
2925 item.has_conflict = true;
2926 item.project_entry_ids = vec![ProjectEntryId::from_proto(2)];
2927 item
2928 });
2929 let item3 = cx.add_view(window_id, |_| {
2930 let mut item = TestItem::new();
2931 item.is_dirty = true;
2932 item.has_conflict = true;
2933 item.project_entry_ids = vec![ProjectEntryId::from_proto(3)];
2934 item
2935 });
2936 let item4 = cx.add_view(window_id, |_| {
2937 let mut item = TestItem::new();
2938 item.is_dirty = true;
2939 item
2940 });
2941 let pane = workspace.update(cx, |workspace, cx| {
2942 workspace.add_item(Box::new(item1.clone()), cx);
2943 workspace.add_item(Box::new(item2.clone()), cx);
2944 workspace.add_item(Box::new(item3.clone()), cx);
2945 workspace.add_item(Box::new(item4.clone()), cx);
2946 workspace.active_pane().clone()
2947 });
2948
2949 let close_items = workspace.update(cx, |workspace, cx| {
2950 pane.update(cx, |pane, cx| {
2951 pane.activate_item(1, true, true, false, cx);
2952 assert_eq!(pane.active_item().unwrap().id(), item2.id());
2953 });
2954
2955 let item1_id = item1.id();
2956 let item3_id = item3.id();
2957 let item4_id = item4.id();
2958 Pane::close_items(workspace, pane.clone(), cx, move |id| {
2959 [item1_id, item3_id, item4_id].contains(&id)
2960 })
2961 });
2962
2963 cx.foreground().run_until_parked();
2964 pane.read_with(cx, |pane, _| {
2965 assert_eq!(pane.items().count(), 4);
2966 assert_eq!(pane.active_item().unwrap().id(), item1.id());
2967 });
2968
2969 cx.simulate_prompt_answer(window_id, 0);
2970 cx.foreground().run_until_parked();
2971 pane.read_with(cx, |pane, cx| {
2972 assert_eq!(item1.read(cx).save_count, 1);
2973 assert_eq!(item1.read(cx).save_as_count, 0);
2974 assert_eq!(item1.read(cx).reload_count, 0);
2975 assert_eq!(pane.items().count(), 3);
2976 assert_eq!(pane.active_item().unwrap().id(), item3.id());
2977 });
2978
2979 cx.simulate_prompt_answer(window_id, 1);
2980 cx.foreground().run_until_parked();
2981 pane.read_with(cx, |pane, cx| {
2982 assert_eq!(item3.read(cx).save_count, 0);
2983 assert_eq!(item3.read(cx).save_as_count, 0);
2984 assert_eq!(item3.read(cx).reload_count, 1);
2985 assert_eq!(pane.items().count(), 2);
2986 assert_eq!(pane.active_item().unwrap().id(), item4.id());
2987 });
2988
2989 cx.simulate_prompt_answer(window_id, 0);
2990 cx.foreground().run_until_parked();
2991 cx.simulate_new_path_selection(|_| Some(Default::default()));
2992 close_items.await.unwrap();
2993 pane.read_with(cx, |pane, cx| {
2994 assert_eq!(item4.read(cx).save_count, 0);
2995 assert_eq!(item4.read(cx).save_as_count, 1);
2996 assert_eq!(item4.read(cx).reload_count, 0);
2997 assert_eq!(pane.items().count(), 1);
2998 assert_eq!(pane.active_item().unwrap().id(), item2.id());
2999 });
3000 }
3001
3002 #[gpui::test]
3003 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
3004 cx.foreground().forbid_parking();
3005 Settings::test_async(cx);
3006 let fs = FakeFs::new(cx.background());
3007
3008 let project = Project::test(fs, [], cx).await;
3009 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
3010
3011 // Create several workspace items with single project entries, and two
3012 // workspace items with multiple project entries.
3013 let single_entry_items = (0..=4)
3014 .map(|project_entry_id| {
3015 let mut item = TestItem::new();
3016 item.is_dirty = true;
3017 item.project_entry_ids = vec![ProjectEntryId::from_proto(project_entry_id)];
3018 item.is_singleton = true;
3019 item
3020 })
3021 .collect::<Vec<_>>();
3022 let item_2_3 = {
3023 let mut item = TestItem::new();
3024 item.is_dirty = true;
3025 item.is_singleton = false;
3026 item.project_entry_ids =
3027 vec![ProjectEntryId::from_proto(2), ProjectEntryId::from_proto(3)];
3028 item
3029 };
3030 let item_3_4 = {
3031 let mut item = TestItem::new();
3032 item.is_dirty = true;
3033 item.is_singleton = false;
3034 item.project_entry_ids =
3035 vec![ProjectEntryId::from_proto(3), ProjectEntryId::from_proto(4)];
3036 item
3037 };
3038
3039 // Create two panes that contain the following project entries:
3040 // left pane:
3041 // multi-entry items: (2, 3)
3042 // single-entry items: 0, 1, 2, 3, 4
3043 // right pane:
3044 // single-entry items: 1
3045 // multi-entry items: (3, 4)
3046 let left_pane = workspace.update(cx, |workspace, cx| {
3047 let left_pane = workspace.active_pane().clone();
3048 let right_pane = workspace.split_pane(left_pane.clone(), SplitDirection::Right, cx);
3049
3050 workspace.activate_pane(left_pane.clone(), cx);
3051 workspace.add_item(Box::new(cx.add_view(|_| item_2_3.clone())), cx);
3052 for item in &single_entry_items {
3053 workspace.add_item(Box::new(cx.add_view(|_| item.clone())), cx);
3054 }
3055
3056 workspace.activate_pane(right_pane.clone(), cx);
3057 workspace.add_item(Box::new(cx.add_view(|_| single_entry_items[1].clone())), cx);
3058 workspace.add_item(Box::new(cx.add_view(|_| item_3_4.clone())), cx);
3059
3060 left_pane
3061 });
3062
3063 // When closing all of the items in the left pane, we should be prompted twice:
3064 // once for project entry 0, and once for project entry 2. After those two
3065 // prompts, the task should complete.
3066 let close = workspace.update(cx, |workspace, cx| {
3067 workspace.activate_pane(left_pane.clone(), cx);
3068 Pane::close_items(workspace, left_pane.clone(), cx, |_| true)
3069 });
3070
3071 cx.foreground().run_until_parked();
3072 left_pane.read_with(cx, |pane, cx| {
3073 assert_eq!(
3074 pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
3075 &[ProjectEntryId::from_proto(0)]
3076 );
3077 });
3078 cx.simulate_prompt_answer(window_id, 0);
3079
3080 cx.foreground().run_until_parked();
3081 left_pane.read_with(cx, |pane, cx| {
3082 assert_eq!(
3083 pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
3084 &[ProjectEntryId::from_proto(2)]
3085 );
3086 });
3087 cx.simulate_prompt_answer(window_id, 0);
3088
3089 cx.foreground().run_until_parked();
3090 close.await.unwrap();
3091 left_pane.read_with(cx, |pane, _| {
3092 assert_eq!(pane.items().count(), 0);
3093 });
3094 }
3095
3096 #[gpui::test]
3097 async fn test_autosave(deterministic: Arc<Deterministic>, cx: &mut gpui::TestAppContext) {
3098 deterministic.forbid_parking();
3099
3100 Settings::test_async(cx);
3101 let fs = FakeFs::new(cx.background());
3102
3103 let project = Project::test(fs, [], cx).await;
3104 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
3105
3106 let item = cx.add_view(window_id, |_| {
3107 let mut item = TestItem::new();
3108 item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3109 item
3110 });
3111 let item_id = item.id();
3112 workspace.update(cx, |workspace, cx| {
3113 workspace.add_item(Box::new(item.clone()), cx);
3114 });
3115
3116 // Autosave on window change.
3117 item.update(cx, |item, cx| {
3118 cx.update_global(|settings: &mut Settings, _| {
3119 settings.autosave = Autosave::OnWindowChange;
3120 });
3121 item.is_dirty = true;
3122 });
3123
3124 // Deactivating the window saves the file.
3125 cx.simulate_window_activation(None);
3126 deterministic.run_until_parked();
3127 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
3128
3129 // Autosave on focus change.
3130 item.update(cx, |item, cx| {
3131 cx.focus_self();
3132 cx.update_global(|settings: &mut Settings, _| {
3133 settings.autosave = Autosave::OnFocusChange;
3134 });
3135 item.is_dirty = true;
3136 });
3137
3138 // Blurring the item saves the file.
3139 item.update(cx, |_, cx| cx.blur());
3140 deterministic.run_until_parked();
3141 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
3142
3143 // Deactivating the window still saves the file.
3144 cx.simulate_window_activation(Some(window_id));
3145 item.update(cx, |item, cx| {
3146 cx.focus_self();
3147 item.is_dirty = true;
3148 });
3149 cx.simulate_window_activation(None);
3150
3151 deterministic.run_until_parked();
3152 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
3153
3154 // Autosave after delay.
3155 item.update(cx, |item, cx| {
3156 cx.update_global(|settings: &mut Settings, _| {
3157 settings.autosave = Autosave::AfterDelay { milliseconds: 500 };
3158 });
3159 item.is_dirty = true;
3160 cx.emit(TestItemEvent::Edit);
3161 });
3162
3163 // Delay hasn't fully expired, so the file is still dirty and unsaved.
3164 deterministic.advance_clock(Duration::from_millis(250));
3165 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
3166
3167 // After delay expires, the file is saved.
3168 deterministic.advance_clock(Duration::from_millis(250));
3169 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
3170
3171 // Autosave on focus change, ensuring closing the tab counts as such.
3172 item.update(cx, |item, cx| {
3173 cx.update_global(|settings: &mut Settings, _| {
3174 settings.autosave = Autosave::OnFocusChange;
3175 });
3176 item.is_dirty = true;
3177 });
3178
3179 workspace
3180 .update(cx, |workspace, cx| {
3181 let pane = workspace.active_pane().clone();
3182 Pane::close_items(workspace, pane, cx, move |id| id == item_id)
3183 })
3184 .await
3185 .unwrap();
3186 assert!(!cx.has_pending_prompt(window_id));
3187 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3188
3189 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
3190 workspace.update(cx, |workspace, cx| {
3191 workspace.add_item(Box::new(item.clone()), cx);
3192 });
3193 item.update(cx, |item, cx| {
3194 item.project_entry_ids = Default::default();
3195 item.is_dirty = true;
3196 cx.blur();
3197 });
3198 deterministic.run_until_parked();
3199 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3200
3201 // Ensure autosave is prevented for deleted files also when closing the buffer.
3202 let _close_items = workspace.update(cx, |workspace, cx| {
3203 let pane = workspace.active_pane().clone();
3204 Pane::close_items(workspace, pane, cx, move |id| id == item_id)
3205 });
3206 deterministic.run_until_parked();
3207 assert!(cx.has_pending_prompt(window_id));
3208 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
3209 }
3210
3211 #[gpui::test]
3212 async fn test_pane_navigation(
3213 deterministic: Arc<Deterministic>,
3214 cx: &mut gpui::TestAppContext,
3215 ) {
3216 deterministic.forbid_parking();
3217 Settings::test_async(cx);
3218 let fs = FakeFs::new(cx.background());
3219
3220 let project = Project::test(fs, [], cx).await;
3221 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
3222
3223 let item = cx.add_view(window_id, |_| {
3224 let mut item = TestItem::new();
3225 item.project_entry_ids = vec![ProjectEntryId::from_proto(1)];
3226 item
3227 });
3228 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
3229 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
3230 let toolbar_notify_count = Rc::new(RefCell::new(0));
3231
3232 workspace.update(cx, |workspace, cx| {
3233 workspace.add_item(Box::new(item.clone()), cx);
3234 let toolbar_notification_count = toolbar_notify_count.clone();
3235 cx.observe(&toolbar, move |_, _, _| {
3236 *toolbar_notification_count.borrow_mut() += 1
3237 })
3238 .detach();
3239 });
3240
3241 pane.read_with(cx, |pane, _| {
3242 assert!(!pane.can_navigate_backward());
3243 assert!(!pane.can_navigate_forward());
3244 });
3245
3246 item.update(cx, |item, cx| {
3247 item.set_state("one".to_string(), cx);
3248 });
3249
3250 // Toolbar must be notified to re-render the navigation buttons
3251 assert_eq!(*toolbar_notify_count.borrow(), 1);
3252
3253 pane.read_with(cx, |pane, _| {
3254 assert!(pane.can_navigate_backward());
3255 assert!(!pane.can_navigate_forward());
3256 });
3257
3258 workspace
3259 .update(cx, |workspace, cx| {
3260 Pane::go_back(workspace, Some(pane.clone()), cx)
3261 })
3262 .await;
3263
3264 assert_eq!(*toolbar_notify_count.borrow(), 3);
3265 pane.read_with(cx, |pane, _| {
3266 assert!(!pane.can_navigate_backward());
3267 assert!(pane.can_navigate_forward());
3268 });
3269 }
3270
3271 struct TestItem {
3272 state: String,
3273 save_count: usize,
3274 save_as_count: usize,
3275 reload_count: usize,
3276 is_dirty: bool,
3277 is_singleton: bool,
3278 has_conflict: bool,
3279 project_entry_ids: Vec<ProjectEntryId>,
3280 project_path: Option<ProjectPath>,
3281 nav_history: Option<ItemNavHistory>,
3282 tab_descriptions: Option<Vec<&'static str>>,
3283 tab_detail: Cell<Option<usize>>,
3284 }
3285
3286 enum TestItemEvent {
3287 Edit,
3288 }
3289
3290 impl Clone for TestItem {
3291 fn clone(&self) -> Self {
3292 Self {
3293 state: self.state.clone(),
3294 save_count: self.save_count,
3295 save_as_count: self.save_as_count,
3296 reload_count: self.reload_count,
3297 is_dirty: self.is_dirty,
3298 is_singleton: self.is_singleton,
3299 has_conflict: self.has_conflict,
3300 project_entry_ids: self.project_entry_ids.clone(),
3301 project_path: self.project_path.clone(),
3302 nav_history: None,
3303 tab_descriptions: None,
3304 tab_detail: Default::default(),
3305 }
3306 }
3307 }
3308
3309 impl TestItem {
3310 fn new() -> Self {
3311 Self {
3312 state: String::new(),
3313 save_count: 0,
3314 save_as_count: 0,
3315 reload_count: 0,
3316 is_dirty: false,
3317 has_conflict: false,
3318 project_entry_ids: Vec::new(),
3319 project_path: None,
3320 is_singleton: true,
3321 nav_history: None,
3322 tab_descriptions: None,
3323 tab_detail: Default::default(),
3324 }
3325 }
3326
3327 fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
3328 self.push_to_nav_history(cx);
3329 self.state = state;
3330 }
3331
3332 fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
3333 if let Some(history) = &mut self.nav_history {
3334 history.push(Some(Box::new(self.state.clone())), cx);
3335 }
3336 }
3337 }
3338
3339 impl Entity for TestItem {
3340 type Event = TestItemEvent;
3341 }
3342
3343 impl View for TestItem {
3344 fn ui_name() -> &'static str {
3345 "TestItem"
3346 }
3347
3348 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
3349 Empty::new().boxed()
3350 }
3351 }
3352
3353 impl Item for TestItem {
3354 fn tab_description<'a>(&'a self, detail: usize, _: &'a AppContext) -> Option<Cow<'a, str>> {
3355 self.tab_descriptions.as_ref().and_then(|descriptions| {
3356 let description = *descriptions.get(detail).or(descriptions.last())?;
3357 Some(description.into())
3358 })
3359 }
3360
3361 fn tab_content(&self, detail: Option<usize>, _: &theme::Tab, _: &AppContext) -> ElementBox {
3362 self.tab_detail.set(detail);
3363 Empty::new().boxed()
3364 }
3365
3366 fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
3367 self.project_path.clone()
3368 }
3369
3370 fn project_entry_ids(&self, _: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
3371 self.project_entry_ids.iter().copied().collect()
3372 }
3373
3374 fn is_singleton(&self, _: &AppContext) -> bool {
3375 self.is_singleton
3376 }
3377
3378 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
3379 self.nav_history = Some(history);
3380 }
3381
3382 fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
3383 let state = *state.downcast::<String>().unwrap_or_default();
3384 if state != self.state {
3385 self.state = state;
3386 true
3387 } else {
3388 false
3389 }
3390 }
3391
3392 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
3393 self.push_to_nav_history(cx);
3394 }
3395
3396 fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
3397 where
3398 Self: Sized,
3399 {
3400 Some(self.clone())
3401 }
3402
3403 fn is_dirty(&self, _: &AppContext) -> bool {
3404 self.is_dirty
3405 }
3406
3407 fn has_conflict(&self, _: &AppContext) -> bool {
3408 self.has_conflict
3409 }
3410
3411 fn can_save(&self, _: &AppContext) -> bool {
3412 self.project_entry_ids.len() > 0
3413 }
3414
3415 fn save(
3416 &mut self,
3417 _: ModelHandle<Project>,
3418 _: &mut ViewContext<Self>,
3419 ) -> Task<anyhow::Result<()>> {
3420 self.save_count += 1;
3421 self.is_dirty = false;
3422 Task::ready(Ok(()))
3423 }
3424
3425 fn save_as(
3426 &mut self,
3427 _: ModelHandle<Project>,
3428 _: std::path::PathBuf,
3429 _: &mut ViewContext<Self>,
3430 ) -> Task<anyhow::Result<()>> {
3431 self.save_as_count += 1;
3432 self.is_dirty = false;
3433 Task::ready(Ok(()))
3434 }
3435
3436 fn reload(
3437 &mut self,
3438 _: ModelHandle<Project>,
3439 _: &mut ViewContext<Self>,
3440 ) -> Task<anyhow::Result<()>> {
3441 self.reload_count += 1;
3442 self.is_dirty = false;
3443 Task::ready(Ok(()))
3444 }
3445
3446 fn should_update_tab_on_event(_: &Self::Event) -> bool {
3447 true
3448 }
3449
3450 fn is_edit_event(event: &Self::Event) -> bool {
3451 matches!(event, TestItemEvent::Edit)
3452 }
3453 }
3454}