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