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