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