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