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