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