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