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