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