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