1pub mod dock;
2pub mod history_manager;
3pub mod item;
4mod modal_layer;
5pub mod notifications;
6pub mod pane;
7pub mod pane_group;
8mod persistence;
9pub mod searchable;
10pub mod shared_screen;
11mod status_bar;
12pub mod tasks;
13mod theme_preview;
14mod toast_layer;
15mod toolbar;
16mod workspace_settings;
17
18pub use toast_layer::{RunAction, ToastAction, ToastLayer, ToastView};
19
20use anyhow::{Context as _, Result, anyhow};
21use call::{ActiveCall, call_settings::CallSettings};
22use client::{
23 ChannelId, Client, ErrorExt, Status, TypedEnvelope, UserStore,
24 proto::{self, ErrorCode, PanelId, PeerId},
25};
26use collections::{HashMap, HashSet, hash_map};
27pub use dock::Panel;
28use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
29use futures::{
30 Future, FutureExt, StreamExt,
31 channel::{
32 mpsc::{self, UnboundedReceiver, UnboundedSender},
33 oneshot,
34 },
35 future::try_join_all,
36};
37use gpui::{
38 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
39 CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
40 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
41 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription, Task,
42 Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId, WindowOptions, action_as, actions,
43 canvas, impl_action_as, impl_actions, point, relative, size, transparent_black,
44};
45pub use history_manager::*;
46pub use item::{
47 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
48 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
49};
50use itertools::Itertools;
51use language::{Buffer, LanguageRegistry, Rope};
52pub use modal_layer::*;
53use node_runtime::NodeRuntime;
54use notifications::{
55 DetachAndPromptErr, Notifications, dismiss_app_notification,
56 simple_message_notification::MessageNotification,
57};
58pub use pane::*;
59pub use pane_group::*;
60use persistence::{
61 DB, SerializedWindowBounds,
62 model::{SerializedSshProject, SerializedWorkspace},
63};
64pub use persistence::{
65 DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
66 model::{ItemId, LocalPaths, SerializedWorkspaceLocation},
67};
68use postage::stream::Stream;
69use project::{
70 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
71 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
72};
73use remote::{SshClientDelegate, SshConnectionOptions, ssh_session::ConnectionIdentifier};
74use schemars::JsonSchema;
75use serde::Deserialize;
76use session::AppSession;
77use settings::Settings;
78use shared_screen::SharedScreen;
79use sqlez::{
80 bindable::{Bind, Column, StaticColumnCount},
81 statement::Statement,
82};
83use status_bar::StatusBar;
84pub use status_bar::StatusItemView;
85use std::{
86 any::TypeId,
87 borrow::Cow,
88 cell::RefCell,
89 cmp,
90 collections::hash_map::DefaultHasher,
91 env,
92 hash::{Hash, Hasher},
93 path::{Path, PathBuf},
94 process::ExitStatus,
95 rc::Rc,
96 sync::{Arc, LazyLock, Weak, atomic::AtomicUsize},
97 time::Duration,
98};
99use task::{DebugScenario, SpawnInTerminal, TaskContext};
100use theme::{ActiveTheme, SystemAppearance, ThemeSettings};
101pub use toolbar::{Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView};
102pub use ui;
103use ui::{Window, prelude::*};
104use util::{ResultExt, TryFutureExt, paths::SanitizedPath, serde::default_true};
105use uuid::Uuid;
106pub use workspace_settings::{
107 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, TabBarSettings, WorkspaceSettings,
108};
109use zed_actions::{Spawn, feedback::FileBugReport};
110
111use crate::notifications::NotificationId;
112use crate::persistence::{
113 SerializedAxis,
114 model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup},
115};
116
117pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
118
119static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
120 env::var("ZED_WINDOW_SIZE")
121 .ok()
122 .as_deref()
123 .and_then(parse_pixel_size_env_var)
124});
125
126static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
127 env::var("ZED_WINDOW_POSITION")
128 .ok()
129 .as_deref()
130 .and_then(parse_pixel_position_env_var)
131});
132
133pub trait TerminalProvider {
134 fn spawn(
135 &self,
136 task: SpawnInTerminal,
137 window: &mut Window,
138 cx: &mut App,
139 ) -> Task<Option<Result<ExitStatus>>>;
140}
141
142pub trait DebuggerProvider {
143 // `active_buffer` is used to resolve build task's name against language-specific tasks.
144 fn start_session(
145 &self,
146 definition: DebugScenario,
147 task_context: TaskContext,
148 active_buffer: Option<Entity<Buffer>>,
149 window: &mut Window,
150 cx: &mut App,
151 );
152
153 fn spawn_task_or_modal(
154 &self,
155 workspace: &mut Workspace,
156 action: &Spawn,
157 window: &mut Window,
158 cx: &mut Context<Workspace>,
159 );
160
161 fn task_scheduled(&self, cx: &mut App);
162 fn debug_scenario_scheduled(&self, cx: &mut App);
163 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
164
165 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
166}
167
168actions!(
169 workspace,
170 [
171 ActivateNextPane,
172 ActivatePreviousPane,
173 ActivateNextWindow,
174 ActivatePreviousWindow,
175 AddFolderToProject,
176 ClearAllNotifications,
177 CloseActiveDock,
178 CloseAllDocks,
179 CloseWindow,
180 Feedback,
181 FollowNextCollaborator,
182 MoveFocusedPanelToNextPosition,
183 NewCenterTerminal,
184 NewFile,
185 NewFileSplitVertical,
186 NewFileSplitHorizontal,
187 NewSearch,
188 NewTerminal,
189 NewWindow,
190 Open,
191 OpenFiles,
192 OpenInTerminal,
193 OpenComponentPreview,
194 ReloadActiveItem,
195 SaveAs,
196 SaveWithoutFormat,
197 ShutdownDebugAdapters,
198 SuppressNotification,
199 ToggleBottomDock,
200 ToggleCenteredLayout,
201 ToggleLeftDock,
202 ToggleRightDock,
203 ToggleZoom,
204 Unfollow,
205 Welcome,
206 RestoreBanner,
207 ToggleExpandItem,
208 ]
209);
210
211#[derive(Clone, PartialEq)]
212pub struct OpenPaths {
213 pub paths: Vec<PathBuf>,
214}
215
216#[derive(Clone, Deserialize, PartialEq, JsonSchema)]
217pub struct ActivatePane(pub usize);
218
219#[derive(Clone, Deserialize, PartialEq, JsonSchema)]
220#[serde(deny_unknown_fields)]
221pub struct MoveItemToPane {
222 pub destination: usize,
223 #[serde(default = "default_true")]
224 pub focus: bool,
225}
226
227#[derive(Clone, Deserialize, PartialEq, JsonSchema)]
228#[serde(deny_unknown_fields)]
229pub struct MoveItemToPaneInDirection {
230 pub direction: SplitDirection,
231 #[serde(default = "default_true")]
232 pub focus: bool,
233}
234
235#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema)]
236#[serde(deny_unknown_fields)]
237pub struct SaveAll {
238 pub save_intent: Option<SaveIntent>,
239}
240
241#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema)]
242#[serde(deny_unknown_fields)]
243pub struct Save {
244 pub save_intent: Option<SaveIntent>,
245}
246
247#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema)]
248#[serde(deny_unknown_fields)]
249pub struct CloseAllItemsAndPanes {
250 pub save_intent: Option<SaveIntent>,
251}
252
253#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema)]
254#[serde(deny_unknown_fields)]
255pub struct CloseInactiveTabsAndPanes {
256 pub save_intent: Option<SaveIntent>,
257}
258
259#[derive(Clone, Deserialize, PartialEq, JsonSchema)]
260pub struct SendKeystrokes(pub String);
261
262#[derive(Clone, Deserialize, PartialEq, Default, JsonSchema)]
263#[serde(deny_unknown_fields)]
264pub struct Reload {
265 pub binary_path: Option<PathBuf>,
266}
267
268action_as!(project_symbols, ToggleProjectSymbols as Toggle);
269
270#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema)]
271pub struct ToggleFileFinder {
272 #[serde(default)]
273 pub separate_history: bool,
274}
275
276impl_action_as!(file_finder, ToggleFileFinder as Toggle);
277
278impl_actions!(
279 workspace,
280 [
281 ActivatePane,
282 CloseAllItemsAndPanes,
283 CloseInactiveTabsAndPanes,
284 MoveItemToPane,
285 MoveItemToPaneInDirection,
286 OpenTerminal,
287 Reload,
288 Save,
289 SaveAll,
290 SendKeystrokes,
291 ]
292);
293
294actions!(
295 workspace,
296 [
297 ActivatePaneLeft,
298 ActivatePaneRight,
299 ActivatePaneUp,
300 ActivatePaneDown,
301 SwapPaneLeft,
302 SwapPaneRight,
303 SwapPaneUp,
304 SwapPaneDown,
305 ]
306);
307
308#[derive(PartialEq, Eq, Debug)]
309pub enum CloseIntent {
310 /// Quit the program entirely.
311 Quit,
312 /// Close a window.
313 CloseWindow,
314 /// Replace the workspace in an existing window.
315 ReplaceWindow,
316}
317
318#[derive(Clone)]
319pub struct Toast {
320 id: NotificationId,
321 msg: Cow<'static, str>,
322 autohide: bool,
323 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
324}
325
326impl Toast {
327 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
328 Toast {
329 id,
330 msg: msg.into(),
331 on_click: None,
332 autohide: false,
333 }
334 }
335
336 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
337 where
338 M: Into<Cow<'static, str>>,
339 F: Fn(&mut Window, &mut App) + 'static,
340 {
341 self.on_click = Some((message.into(), Arc::new(on_click)));
342 self
343 }
344
345 pub fn autohide(mut self) -> Self {
346 self.autohide = true;
347 self
348 }
349}
350
351impl PartialEq for Toast {
352 fn eq(&self, other: &Self) -> bool {
353 self.id == other.id
354 && self.msg == other.msg
355 && self.on_click.is_some() == other.on_click.is_some()
356 }
357}
358
359#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema)]
360#[serde(deny_unknown_fields)]
361pub struct OpenTerminal {
362 pub working_directory: PathBuf,
363}
364
365#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
366pub struct WorkspaceId(i64);
367
368impl StaticColumnCount for WorkspaceId {}
369impl Bind for WorkspaceId {
370 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
371 self.0.bind(statement, start_index)
372 }
373}
374impl Column for WorkspaceId {
375 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
376 i64::column(statement, start_index)
377 .map(|(i, next_index)| (Self(i), next_index))
378 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
379 }
380}
381impl From<WorkspaceId> for i64 {
382 fn from(val: WorkspaceId) -> Self {
383 val.0
384 }
385}
386
387pub fn init_settings(cx: &mut App) {
388 WorkspaceSettings::register(cx);
389 ItemSettings::register(cx);
390 PreviewTabsSettings::register(cx);
391 TabBarSettings::register(cx);
392}
393
394fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
395 let paths = cx.prompt_for_paths(options);
396 cx.spawn(
397 async move |cx| match paths.await.anyhow().and_then(|res| res) {
398 Ok(Some(paths)) => {
399 cx.update(|cx| {
400 open_paths(&paths, app_state, OpenOptions::default(), cx).detach_and_log_err(cx)
401 })
402 .ok();
403 }
404 Ok(None) => {}
405 Err(err) => {
406 util::log_err(&err);
407 cx.update(|cx| {
408 if let Some(workspace_window) = cx
409 .active_window()
410 .and_then(|window| window.downcast::<Workspace>())
411 {
412 workspace_window
413 .update(cx, |workspace, _, cx| {
414 workspace.show_portal_error(err.to_string(), cx);
415 })
416 .ok();
417 }
418 })
419 .ok();
420 }
421 },
422 )
423 .detach();
424}
425
426pub fn init(app_state: Arc<AppState>, cx: &mut App) {
427 init_settings(cx);
428 component::init();
429 theme_preview::init(cx);
430 toast_layer::init(cx);
431 history_manager::init(cx);
432
433 cx.on_action(Workspace::close_global);
434 cx.on_action(reload);
435
436 cx.on_action({
437 let app_state = Arc::downgrade(&app_state);
438 move |_: &Open, cx: &mut App| {
439 if let Some(app_state) = app_state.upgrade() {
440 prompt_and_open_paths(
441 app_state,
442 PathPromptOptions {
443 files: true,
444 directories: true,
445 multiple: true,
446 },
447 cx,
448 );
449 }
450 }
451 });
452 cx.on_action({
453 let app_state = Arc::downgrade(&app_state);
454 move |_: &OpenFiles, cx: &mut App| {
455 let directories = cx.can_select_mixed_files_and_dirs();
456 if let Some(app_state) = app_state.upgrade() {
457 prompt_and_open_paths(
458 app_state,
459 PathPromptOptions {
460 files: true,
461 directories,
462 multiple: true,
463 },
464 cx,
465 );
466 }
467 }
468 });
469}
470
471type BuildProjectItemFn =
472 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
473
474type BuildProjectItemForPathFn =
475 fn(
476 &Entity<Project>,
477 &ProjectPath,
478 &mut Window,
479 &mut App,
480 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
481
482#[derive(Clone, Default)]
483struct ProjectItemRegistry {
484 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
485 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
486}
487
488impl ProjectItemRegistry {
489 fn register<T: ProjectItem>(&mut self) {
490 self.build_project_item_fns_by_type.insert(
491 TypeId::of::<T::Item>(),
492 |item, project, pane, window, cx| {
493 let item = item.downcast().unwrap();
494 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
495 as Box<dyn ItemHandle>
496 },
497 );
498 self.build_project_item_for_path_fns
499 .push(|project, project_path, window, cx| {
500 let project_item =
501 <T::Item as project::ProjectItem>::try_open(project, project_path, cx)?;
502 let project = project.clone();
503 Some(window.spawn(cx, async move |cx| {
504 let project_item = project_item.await?;
505 let project_entry_id: Option<ProjectEntryId> =
506 project_item.read_with(cx, project::ProjectItem::entry_id)?;
507 let build_workspace_item = Box::new(
508 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
509 Box::new(cx.new(|cx| {
510 T::for_project_item(project, Some(pane), project_item, window, cx)
511 })) as Box<dyn ItemHandle>
512 },
513 ) as Box<_>;
514 Ok((project_entry_id, build_workspace_item))
515 }))
516 });
517 }
518
519 fn open_path(
520 &self,
521 project: &Entity<Project>,
522 path: &ProjectPath,
523 window: &mut Window,
524 cx: &mut App,
525 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
526 let Some(open_project_item) = self
527 .build_project_item_for_path_fns
528 .iter()
529 .rev()
530 .find_map(|open_project_item| open_project_item(&project, &path, window, cx))
531 else {
532 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
533 };
534 open_project_item
535 }
536
537 fn build_item<T: project::ProjectItem>(
538 &self,
539 item: Entity<T>,
540 project: Entity<Project>,
541 pane: Option<&Pane>,
542 window: &mut Window,
543 cx: &mut App,
544 ) -> Option<Box<dyn ItemHandle>> {
545 let build = self
546 .build_project_item_fns_by_type
547 .get(&TypeId::of::<T>())?;
548 Some(build(item.into_any(), project, pane, window, cx))
549 }
550}
551
552type WorkspaceItemBuilder =
553 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
554
555impl Global for ProjectItemRegistry {}
556
557/// Registers a [ProjectItem] for the app. When opening a file, all the registered
558/// items will get a chance to open the file, starting from the project item that
559/// was added last.
560pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
561 cx.default_global::<ProjectItemRegistry>().register::<I>();
562}
563
564#[derive(Default)]
565pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
566
567struct FollowableViewDescriptor {
568 from_state_proto: fn(
569 Entity<Workspace>,
570 ViewId,
571 &mut Option<proto::view::Variant>,
572 &mut Window,
573 &mut App,
574 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
575 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
576}
577
578impl Global for FollowableViewRegistry {}
579
580impl FollowableViewRegistry {
581 pub fn register<I: FollowableItem>(cx: &mut App) {
582 cx.default_global::<Self>().0.insert(
583 TypeId::of::<I>(),
584 FollowableViewDescriptor {
585 from_state_proto: |workspace, id, state, window, cx| {
586 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
587 cx.foreground_executor()
588 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
589 })
590 },
591 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
592 },
593 );
594 }
595
596 pub fn from_state_proto(
597 workspace: Entity<Workspace>,
598 view_id: ViewId,
599 mut state: Option<proto::view::Variant>,
600 window: &mut Window,
601 cx: &mut App,
602 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
603 cx.update_default_global(|this: &mut Self, cx| {
604 this.0.values().find_map(|descriptor| {
605 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
606 })
607 })
608 }
609
610 pub fn to_followable_view(
611 view: impl Into<AnyView>,
612 cx: &App,
613 ) -> Option<Box<dyn FollowableItemHandle>> {
614 let this = cx.try_global::<Self>()?;
615 let view = view.into();
616 let descriptor = this.0.get(&view.entity_type())?;
617 Some((descriptor.to_followable_view)(&view))
618 }
619}
620
621#[derive(Copy, Clone)]
622struct SerializableItemDescriptor {
623 deserialize: fn(
624 Entity<Project>,
625 WeakEntity<Workspace>,
626 WorkspaceId,
627 ItemId,
628 &mut Window,
629 &mut Context<Pane>,
630 ) -> Task<Result<Box<dyn ItemHandle>>>,
631 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
632 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
633}
634
635#[derive(Default)]
636struct SerializableItemRegistry {
637 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
638 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
639}
640
641impl Global for SerializableItemRegistry {}
642
643impl SerializableItemRegistry {
644 fn deserialize(
645 item_kind: &str,
646 project: Entity<Project>,
647 workspace: WeakEntity<Workspace>,
648 workspace_id: WorkspaceId,
649 item_item: ItemId,
650 window: &mut Window,
651 cx: &mut Context<Pane>,
652 ) -> Task<Result<Box<dyn ItemHandle>>> {
653 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
654 return Task::ready(Err(anyhow!(
655 "cannot deserialize {}, descriptor not found",
656 item_kind
657 )));
658 };
659
660 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
661 }
662
663 fn cleanup(
664 item_kind: &str,
665 workspace_id: WorkspaceId,
666 loaded_items: Vec<ItemId>,
667 window: &mut Window,
668 cx: &mut App,
669 ) -> Task<Result<()>> {
670 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
671 return Task::ready(Err(anyhow!(
672 "cannot cleanup {}, descriptor not found",
673 item_kind
674 )));
675 };
676
677 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
678 }
679
680 fn view_to_serializable_item_handle(
681 view: AnyView,
682 cx: &App,
683 ) -> Option<Box<dyn SerializableItemHandle>> {
684 let this = cx.try_global::<Self>()?;
685 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
686 Some((descriptor.view_to_serializable_item)(view))
687 }
688
689 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
690 let this = cx.try_global::<Self>()?;
691 this.descriptors_by_kind.get(item_kind).copied()
692 }
693}
694
695pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
696 let serialized_item_kind = I::serialized_item_kind();
697
698 let registry = cx.default_global::<SerializableItemRegistry>();
699 let descriptor = SerializableItemDescriptor {
700 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
701 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
702 cx.foreground_executor()
703 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
704 },
705 cleanup: |workspace_id, loaded_items, window, cx| {
706 I::cleanup(workspace_id, loaded_items, window, cx)
707 },
708 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
709 };
710 registry
711 .descriptors_by_kind
712 .insert(Arc::from(serialized_item_kind), descriptor);
713 registry
714 .descriptors_by_type
715 .insert(TypeId::of::<I>(), descriptor);
716}
717
718pub struct AppState {
719 pub languages: Arc<LanguageRegistry>,
720 pub client: Arc<Client>,
721 pub user_store: Entity<UserStore>,
722 pub workspace_store: Entity<WorkspaceStore>,
723 pub fs: Arc<dyn fs::Fs>,
724 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
725 pub node_runtime: NodeRuntime,
726 pub session: Entity<AppSession>,
727}
728
729struct GlobalAppState(Weak<AppState>);
730
731impl Global for GlobalAppState {}
732
733pub struct WorkspaceStore {
734 workspaces: HashSet<WindowHandle<Workspace>>,
735 client: Arc<Client>,
736 _subscriptions: Vec<client::Subscription>,
737}
738
739#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
740pub enum CollaboratorId {
741 PeerId(PeerId),
742 Agent,
743}
744
745impl From<PeerId> for CollaboratorId {
746 fn from(peer_id: PeerId) -> Self {
747 CollaboratorId::PeerId(peer_id)
748 }
749}
750
751impl From<&PeerId> for CollaboratorId {
752 fn from(peer_id: &PeerId) -> Self {
753 CollaboratorId::PeerId(*peer_id)
754 }
755}
756
757#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
758struct Follower {
759 project_id: Option<u64>,
760 peer_id: PeerId,
761}
762
763impl AppState {
764 #[track_caller]
765 pub fn global(cx: &App) -> Weak<Self> {
766 cx.global::<GlobalAppState>().0.clone()
767 }
768 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
769 cx.try_global::<GlobalAppState>()
770 .map(|state| state.0.clone())
771 }
772 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
773 cx.set_global(GlobalAppState(state));
774 }
775
776 #[cfg(any(test, feature = "test-support"))]
777 pub fn test(cx: &mut App) -> Arc<Self> {
778 use node_runtime::NodeRuntime;
779 use session::Session;
780 use settings::SettingsStore;
781
782 if !cx.has_global::<SettingsStore>() {
783 let settings_store = SettingsStore::test(cx);
784 cx.set_global(settings_store);
785 }
786
787 let fs = fs::FakeFs::new(cx.background_executor().clone());
788 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
789 let clock = Arc::new(clock::FakeSystemClock::new());
790 let http_client = http_client::FakeHttpClient::with_404_response();
791 let client = Client::new(clock, http_client.clone(), cx);
792 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
793 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
794 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
795
796 theme::init(theme::LoadThemes::JustBase, cx);
797 client::init(&client, cx);
798 crate::init_settings(cx);
799
800 Arc::new(Self {
801 client,
802 fs,
803 languages,
804 user_store,
805 workspace_store,
806 node_runtime: NodeRuntime::unavailable(),
807 build_window_options: |_, _| Default::default(),
808 session,
809 })
810 }
811}
812
813struct DelayedDebouncedEditAction {
814 task: Option<Task<()>>,
815 cancel_channel: Option<oneshot::Sender<()>>,
816}
817
818impl DelayedDebouncedEditAction {
819 fn new() -> DelayedDebouncedEditAction {
820 DelayedDebouncedEditAction {
821 task: None,
822 cancel_channel: None,
823 }
824 }
825
826 fn fire_new<F>(
827 &mut self,
828 delay: Duration,
829 window: &mut Window,
830 cx: &mut Context<Workspace>,
831 func: F,
832 ) where
833 F: 'static
834 + Send
835 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
836 {
837 if let Some(channel) = self.cancel_channel.take() {
838 _ = channel.send(());
839 }
840
841 let (sender, mut receiver) = oneshot::channel::<()>();
842 self.cancel_channel = Some(sender);
843
844 let previous_task = self.task.take();
845 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
846 let mut timer = cx.background_executor().timer(delay).fuse();
847 if let Some(previous_task) = previous_task {
848 previous_task.await;
849 }
850
851 futures::select_biased! {
852 _ = receiver => return,
853 _ = timer => {}
854 }
855
856 if let Some(result) = workspace
857 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
858 .log_err()
859 {
860 result.await.log_err();
861 }
862 }));
863 }
864}
865
866pub enum Event {
867 PaneAdded(Entity<Pane>),
868 PaneRemoved,
869 ItemAdded {
870 item: Box<dyn ItemHandle>,
871 },
872 ItemRemoved,
873 ActiveItemChanged,
874 UserSavedItem {
875 pane: WeakEntity<Pane>,
876 item: Box<dyn WeakItemHandle>,
877 save_intent: SaveIntent,
878 },
879 ContactRequestedJoin(u64),
880 WorkspaceCreated(WeakEntity<Workspace>),
881 OpenBundledFile {
882 text: Cow<'static, str>,
883 title: &'static str,
884 language: &'static str,
885 },
886 ZoomChanged,
887 ModalOpened,
888 ClearActivityIndicator,
889}
890
891#[derive(Debug)]
892pub enum OpenVisible {
893 All,
894 None,
895 OnlyFiles,
896 OnlyDirectories,
897}
898
899type PromptForNewPath = Box<
900 dyn Fn(
901 &mut Workspace,
902 DirectoryLister,
903 &mut Window,
904 &mut Context<Workspace>,
905 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
906>;
907
908type PromptForOpenPath = Box<
909 dyn Fn(
910 &mut Workspace,
911 DirectoryLister,
912 &mut Window,
913 &mut Context<Workspace>,
914 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
915>;
916
917/// Collects everything project-related for a certain window opened.
918/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
919///
920/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
921/// The `Workspace` owns everybody's state and serves as a default, "global context",
922/// that can be used to register a global action to be triggered from any place in the window.
923pub struct Workspace {
924 weak_self: WeakEntity<Self>,
925 workspace_actions: Vec<Box<dyn Fn(Div, &mut Window, &mut Context<Self>) -> Div>>,
926 zoomed: Option<AnyWeakView>,
927 previous_dock_drag_coordinates: Option<Point<Pixels>>,
928 zoomed_position: Option<DockPosition>,
929 center: PaneGroup,
930 left_dock: Entity<Dock>,
931 bottom_dock: Entity<Dock>,
932 bottom_dock_layout: BottomDockLayout,
933 right_dock: Entity<Dock>,
934 panes: Vec<Entity<Pane>>,
935 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
936 active_pane: Entity<Pane>,
937 last_active_center_pane: Option<WeakEntity<Pane>>,
938 last_active_view_id: Option<proto::ViewId>,
939 status_bar: Entity<StatusBar>,
940 modal_layer: Entity<ModalLayer>,
941 toast_layer: Entity<ToastLayer>,
942 titlebar_item: Option<AnyView>,
943 notifications: Notifications,
944 suppressed_notifications: HashSet<NotificationId>,
945 project: Entity<Project>,
946 follower_states: HashMap<CollaboratorId, FollowerState>,
947 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
948 window_edited: bool,
949 dirty_items: HashMap<EntityId, Subscription>,
950 active_call: Option<(Entity<ActiveCall>, Vec<Subscription>)>,
951 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
952 database_id: Option<WorkspaceId>,
953 app_state: Arc<AppState>,
954 dispatching_keystrokes: Rc<RefCell<(HashSet<String>, Vec<Keystroke>)>>,
955 _subscriptions: Vec<Subscription>,
956 _apply_leader_updates: Task<Result<()>>,
957 _observe_current_user: Task<Result<()>>,
958 _schedule_serialize: Option<Task<()>>,
959 pane_history_timestamp: Arc<AtomicUsize>,
960 bounds: Bounds<Pixels>,
961 pub centered_layout: bool,
962 bounds_save_task_queued: Option<Task<()>>,
963 on_prompt_for_new_path: Option<PromptForNewPath>,
964 on_prompt_for_open_path: Option<PromptForOpenPath>,
965 terminal_provider: Option<Box<dyn TerminalProvider>>,
966 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
967 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
968 serialized_ssh_project: Option<SerializedSshProject>,
969 _items_serializer: Task<Result<()>>,
970 session_id: Option<String>,
971}
972
973impl EventEmitter<Event> for Workspace {}
974
975#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
976pub struct ViewId {
977 pub creator: CollaboratorId,
978 pub id: u64,
979}
980
981pub struct FollowerState {
982 center_pane: Entity<Pane>,
983 dock_pane: Option<Entity<Pane>>,
984 active_view_id: Option<ViewId>,
985 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
986}
987
988struct FollowerView {
989 view: Box<dyn FollowableItemHandle>,
990 location: Option<proto::PanelId>,
991}
992
993impl Workspace {
994 const DEFAULT_PADDING: f32 = 0.2;
995 const MAX_PADDING: f32 = 0.4;
996
997 pub fn new(
998 workspace_id: Option<WorkspaceId>,
999 project: Entity<Project>,
1000 app_state: Arc<AppState>,
1001 window: &mut Window,
1002 cx: &mut Context<Self>,
1003 ) -> Self {
1004 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1005 match event {
1006 project::Event::RemoteIdChanged(_) => {
1007 this.update_window_title(window, cx);
1008 }
1009
1010 project::Event::CollaboratorLeft(peer_id) => {
1011 this.collaborator_left(*peer_id, window, cx);
1012 }
1013
1014 project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded(_) => {
1015 this.update_window_title(window, cx);
1016 this.serialize_workspace(window, cx);
1017 // This event could be triggered by `AddFolderToProject` or `RemoveFromProject`.
1018 // So we need to update the history.
1019 this.update_history(cx);
1020 }
1021
1022 project::Event::DisconnectedFromHost => {
1023 this.update_window_edited(window, cx);
1024 let leaders_to_unfollow =
1025 this.follower_states.keys().copied().collect::<Vec<_>>();
1026 for leader_id in leaders_to_unfollow {
1027 this.unfollow(leader_id, window, cx);
1028 }
1029 }
1030
1031 project::Event::DisconnectedFromSshRemote => {
1032 this.update_window_edited(window, cx);
1033 }
1034
1035 project::Event::Closed => {
1036 window.remove_window();
1037 }
1038
1039 project::Event::DeletedEntry(_, entry_id) => {
1040 for pane in this.panes.iter() {
1041 pane.update(cx, |pane, cx| {
1042 pane.handle_deleted_project_item(*entry_id, window, cx)
1043 });
1044 }
1045 }
1046
1047 project::Event::Toast {
1048 notification_id,
1049 message,
1050 } => this.show_notification(
1051 NotificationId::named(notification_id.clone()),
1052 cx,
1053 |cx| cx.new(|cx| MessageNotification::new(message.clone(), cx)),
1054 ),
1055
1056 project::Event::HideToast { notification_id } => {
1057 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1058 }
1059
1060 project::Event::LanguageServerPrompt(request) => {
1061 struct LanguageServerPrompt;
1062
1063 let mut hasher = DefaultHasher::new();
1064 request.lsp_name.as_str().hash(&mut hasher);
1065 let id = hasher.finish();
1066
1067 this.show_notification(
1068 NotificationId::composite::<LanguageServerPrompt>(id as usize),
1069 cx,
1070 |cx| {
1071 cx.new(|cx| {
1072 notifications::LanguageServerPrompt::new(request.clone(), cx)
1073 })
1074 },
1075 );
1076 }
1077
1078 project::Event::AgentLocationChanged => {
1079 this.handle_agent_location_changed(window, cx)
1080 }
1081
1082 _ => {}
1083 }
1084 cx.notify()
1085 })
1086 .detach();
1087
1088 cx.subscribe_in(
1089 &project.read(cx).breakpoint_store(),
1090 window,
1091 |workspace, _, event, window, cx| match event {
1092 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1093 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1094 workspace.serialize_workspace(window, cx);
1095 }
1096 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1097 },
1098 )
1099 .detach();
1100
1101 cx.on_focus_lost(window, |this, window, cx| {
1102 let focus_handle = this.focus_handle(cx);
1103 window.focus(&focus_handle);
1104 })
1105 .detach();
1106
1107 let weak_handle = cx.entity().downgrade();
1108 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1109
1110 let center_pane = cx.new(|cx| {
1111 let mut center_pane = Pane::new(
1112 weak_handle.clone(),
1113 project.clone(),
1114 pane_history_timestamp.clone(),
1115 None,
1116 NewFile.boxed_clone(),
1117 window,
1118 cx,
1119 );
1120 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1121 center_pane
1122 });
1123 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1124 .detach();
1125
1126 window.focus(¢er_pane.focus_handle(cx));
1127
1128 cx.emit(Event::PaneAdded(center_pane.clone()));
1129
1130 let window_handle = window.window_handle().downcast::<Workspace>().unwrap();
1131 app_state.workspace_store.update(cx, |store, _| {
1132 store.workspaces.insert(window_handle);
1133 });
1134
1135 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1136 let mut connection_status = app_state.client.status();
1137 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1138 current_user.next().await;
1139 connection_status.next().await;
1140 let mut stream =
1141 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1142
1143 while stream.recv().await.is_some() {
1144 this.update(cx, |_, cx| cx.notify())?;
1145 }
1146 anyhow::Ok(())
1147 });
1148
1149 // All leader updates are enqueued and then processed in a single task, so
1150 // that each asynchronous operation can be run in order.
1151 let (leader_updates_tx, mut leader_updates_rx) =
1152 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1153 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1154 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1155 Self::process_leader_update(&this, leader_id, update, cx)
1156 .await
1157 .log_err();
1158 }
1159
1160 Ok(())
1161 });
1162
1163 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1164 let modal_layer = cx.new(|_| ModalLayer::new());
1165 let toast_layer = cx.new(|_| ToastLayer::new());
1166 cx.subscribe(
1167 &modal_layer,
1168 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1169 cx.emit(Event::ModalOpened);
1170 },
1171 )
1172 .detach();
1173
1174 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
1175 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1176 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1177 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1178 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1179 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1180 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1181 let status_bar = cx.new(|cx| {
1182 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1183 status_bar.add_left_item(left_dock_buttons, window, cx);
1184 status_bar.add_right_item(right_dock_buttons, window, cx);
1185 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1186 status_bar
1187 });
1188
1189 let session_id = app_state.session.read(cx).id().to_owned();
1190
1191 let mut active_call = None;
1192 if let Some(call) = ActiveCall::try_global(cx) {
1193 let call = call.clone();
1194 let subscriptions = vec![cx.subscribe_in(&call, window, Self::on_active_call_event)];
1195 active_call = Some((call, subscriptions));
1196 }
1197
1198 let (serializable_items_tx, serializable_items_rx) =
1199 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1200 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1201 Self::serialize_items(&this, serializable_items_rx, cx).await
1202 });
1203
1204 let subscriptions = vec![
1205 cx.observe_window_activation(window, Self::on_window_activation_changed),
1206 cx.observe_window_bounds(window, move |this, window, cx| {
1207 if this.bounds_save_task_queued.is_some() {
1208 return;
1209 }
1210 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1211 cx.background_executor()
1212 .timer(Duration::from_millis(100))
1213 .await;
1214 this.update_in(cx, |this, window, cx| {
1215 if let Some(display) = window.display(cx) {
1216 if let Ok(display_uuid) = display.uuid() {
1217 let window_bounds = window.inner_window_bounds();
1218 if let Some(database_id) = workspace_id {
1219 cx.background_executor()
1220 .spawn(DB.set_window_open_status(
1221 database_id,
1222 SerializedWindowBounds(window_bounds),
1223 display_uuid,
1224 ))
1225 .detach_and_log_err(cx);
1226 }
1227 }
1228 }
1229 this.bounds_save_task_queued.take();
1230 })
1231 .ok();
1232 }));
1233 cx.notify();
1234 }),
1235 cx.observe_window_appearance(window, |_, window, cx| {
1236 let window_appearance = window.appearance();
1237
1238 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1239
1240 ThemeSettings::reload_current_theme(cx);
1241 ThemeSettings::reload_current_icon_theme(cx);
1242 }),
1243 cx.on_release(move |this, cx| {
1244 this.app_state.workspace_store.update(cx, move |store, _| {
1245 store.workspaces.remove(&window_handle.clone());
1246 })
1247 }),
1248 ];
1249
1250 cx.defer_in(window, |this, window, cx| {
1251 this.update_window_title(window, cx);
1252 this.show_initial_notifications(cx);
1253 });
1254 Workspace {
1255 weak_self: weak_handle.clone(),
1256 zoomed: None,
1257 zoomed_position: None,
1258 previous_dock_drag_coordinates: None,
1259 center: PaneGroup::new(center_pane.clone()),
1260 panes: vec![center_pane.clone()],
1261 panes_by_item: Default::default(),
1262 active_pane: center_pane.clone(),
1263 last_active_center_pane: Some(center_pane.downgrade()),
1264 last_active_view_id: None,
1265 status_bar,
1266 modal_layer,
1267 toast_layer,
1268 titlebar_item: None,
1269 notifications: Notifications::default(),
1270 suppressed_notifications: HashSet::default(),
1271 left_dock,
1272 bottom_dock,
1273 bottom_dock_layout,
1274 right_dock,
1275 project: project.clone(),
1276 follower_states: Default::default(),
1277 last_leaders_by_pane: Default::default(),
1278 dispatching_keystrokes: Default::default(),
1279 window_edited: false,
1280 dirty_items: Default::default(),
1281 active_call,
1282 database_id: workspace_id,
1283 app_state,
1284 _observe_current_user,
1285 _apply_leader_updates,
1286 _schedule_serialize: None,
1287 leader_updates_tx,
1288 _subscriptions: subscriptions,
1289 pane_history_timestamp,
1290 workspace_actions: Default::default(),
1291 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1292 bounds: Default::default(),
1293 centered_layout: false,
1294 bounds_save_task_queued: None,
1295 on_prompt_for_new_path: None,
1296 on_prompt_for_open_path: None,
1297 terminal_provider: None,
1298 debugger_provider: None,
1299 serializable_items_tx,
1300 _items_serializer,
1301 session_id: Some(session_id),
1302 serialized_ssh_project: None,
1303 }
1304 }
1305
1306 pub fn new_local(
1307 abs_paths: Vec<PathBuf>,
1308 app_state: Arc<AppState>,
1309 requesting_window: Option<WindowHandle<Workspace>>,
1310 env: Option<HashMap<String, String>>,
1311 cx: &mut App,
1312 ) -> Task<
1313 anyhow::Result<(
1314 WindowHandle<Workspace>,
1315 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
1316 )>,
1317 > {
1318 let project_handle = Project::local(
1319 app_state.client.clone(),
1320 app_state.node_runtime.clone(),
1321 app_state.user_store.clone(),
1322 app_state.languages.clone(),
1323 app_state.fs.clone(),
1324 env,
1325 cx,
1326 );
1327
1328 cx.spawn(async move |cx| {
1329 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1330 for path in abs_paths.into_iter() {
1331 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1332 paths_to_open.push(canonical)
1333 } else {
1334 paths_to_open.push(path)
1335 }
1336 }
1337
1338 let serialized_workspace =
1339 persistence::DB.workspace_for_roots(paths_to_open.as_slice());
1340
1341 let workspace_location = serialized_workspace
1342 .as_ref()
1343 .map(|ws| &ws.location)
1344 .and_then(|loc| match loc {
1345 SerializedWorkspaceLocation::Local(_, order) => {
1346 Some((loc.sorted_paths(), order.order()))
1347 }
1348 _ => None,
1349 });
1350
1351 if let Some((paths, order)) = workspace_location {
1352 paths_to_open = paths.iter().cloned().collect();
1353
1354 if order.iter().enumerate().any(|(i, &j)| i != j) {
1355 project_handle
1356 .update(cx, |project, cx| {
1357 project.set_worktrees_reordered(true, cx);
1358 })
1359 .log_err();
1360 }
1361 }
1362
1363 // Get project paths for all of the abs_paths
1364 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1365 Vec::with_capacity(paths_to_open.len());
1366
1367 for path in paths_to_open.into_iter() {
1368 if let Some((_, project_entry)) = cx
1369 .update(|cx| {
1370 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1371 })?
1372 .await
1373 .log_err()
1374 {
1375 project_paths.push((path, Some(project_entry)));
1376 } else {
1377 project_paths.push((path, None));
1378 }
1379 }
1380
1381 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1382 serialized_workspace.id
1383 } else {
1384 DB.next_id().await.unwrap_or_else(|_| Default::default())
1385 };
1386
1387 let toolchains = DB.toolchains(workspace_id).await?;
1388
1389 for (toolchain, worktree_id, path) in toolchains {
1390 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1391 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1392 continue;
1393 }
1394
1395 project_handle
1396 .update(cx, |this, cx| {
1397 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1398 })?
1399 .await;
1400 }
1401 let window = if let Some(window) = requesting_window {
1402 cx.update_window(window.into(), |_, window, cx| {
1403 window.replace_root(cx, |window, cx| {
1404 Workspace::new(
1405 Some(workspace_id),
1406 project_handle.clone(),
1407 app_state.clone(),
1408 window,
1409 cx,
1410 )
1411 });
1412 })?;
1413 window
1414 } else {
1415 let window_bounds_override = window_bounds_env_override();
1416
1417 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1418 (Some(WindowBounds::Windowed(bounds)), None)
1419 } else {
1420 let restorable_bounds = serialized_workspace
1421 .as_ref()
1422 .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
1423 .or_else(|| {
1424 let (display, window_bounds) = DB.last_window().log_err()?;
1425 Some((display?, window_bounds?))
1426 });
1427
1428 if let Some((serialized_display, serialized_status)) = restorable_bounds {
1429 (Some(serialized_status.0), Some(serialized_display))
1430 } else {
1431 (None, None)
1432 }
1433 };
1434
1435 // Use the serialized workspace to construct the new window
1436 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx))?;
1437 options.window_bounds = window_bounds;
1438 let centered_layout = serialized_workspace
1439 .as_ref()
1440 .map(|w| w.centered_layout)
1441 .unwrap_or(false);
1442 cx.open_window(options, {
1443 let app_state = app_state.clone();
1444 let project_handle = project_handle.clone();
1445 move |window, cx| {
1446 cx.new(|cx| {
1447 let mut workspace = Workspace::new(
1448 Some(workspace_id),
1449 project_handle,
1450 app_state,
1451 window,
1452 cx,
1453 );
1454 workspace.centered_layout = centered_layout;
1455 workspace
1456 })
1457 }
1458 })?
1459 };
1460
1461 notify_if_database_failed(window, cx);
1462 let opened_items = window
1463 .update(cx, |_workspace, window, cx| {
1464 open_items(serialized_workspace, project_paths, window, cx)
1465 })?
1466 .await
1467 .unwrap_or_default();
1468
1469 window
1470 .update(cx, |workspace, window, cx| {
1471 window.activate_window();
1472 workspace.update_history(cx);
1473 })
1474 .log_err();
1475 Ok((window, opened_items))
1476 })
1477 }
1478
1479 pub fn weak_handle(&self) -> WeakEntity<Self> {
1480 self.weak_self.clone()
1481 }
1482
1483 pub fn left_dock(&self) -> &Entity<Dock> {
1484 &self.left_dock
1485 }
1486
1487 pub fn bottom_dock(&self) -> &Entity<Dock> {
1488 &self.bottom_dock
1489 }
1490
1491 pub fn bottom_dock_layout(&self) -> BottomDockLayout {
1492 self.bottom_dock_layout
1493 }
1494
1495 pub fn set_bottom_dock_layout(
1496 &mut self,
1497 layout: BottomDockLayout,
1498 window: &mut Window,
1499 cx: &mut Context<Self>,
1500 ) {
1501 let fs = self.project().read(cx).fs();
1502 settings::update_settings_file::<WorkspaceSettings>(fs.clone(), cx, move |content, _cx| {
1503 content.bottom_dock_layout = Some(layout);
1504 });
1505
1506 self.bottom_dock_layout = layout;
1507 cx.notify();
1508 self.serialize_workspace(window, cx);
1509 }
1510
1511 pub fn right_dock(&self) -> &Entity<Dock> {
1512 &self.right_dock
1513 }
1514
1515 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
1516 [&self.left_dock, &self.bottom_dock, &self.right_dock]
1517 }
1518
1519 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
1520 match position {
1521 DockPosition::Left => &self.left_dock,
1522 DockPosition::Bottom => &self.bottom_dock,
1523 DockPosition::Right => &self.right_dock,
1524 }
1525 }
1526
1527 pub fn is_edited(&self) -> bool {
1528 self.window_edited
1529 }
1530
1531 pub fn add_panel<T: Panel>(
1532 &mut self,
1533 panel: Entity<T>,
1534 window: &mut Window,
1535 cx: &mut Context<Self>,
1536 ) {
1537 let focus_handle = panel.panel_focus_handle(cx);
1538 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
1539 .detach();
1540
1541 let dock_position = panel.position(window, cx);
1542 let dock = self.dock_at_position(dock_position);
1543
1544 dock.update(cx, |dock, cx| {
1545 dock.add_panel(panel, self.weak_self.clone(), window, cx)
1546 });
1547 }
1548
1549 pub fn status_bar(&self) -> &Entity<StatusBar> {
1550 &self.status_bar
1551 }
1552
1553 pub fn app_state(&self) -> &Arc<AppState> {
1554 &self.app_state
1555 }
1556
1557 pub fn user_store(&self) -> &Entity<UserStore> {
1558 &self.app_state.user_store
1559 }
1560
1561 pub fn project(&self) -> &Entity<Project> {
1562 &self.project
1563 }
1564
1565 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
1566 let mut history: HashMap<EntityId, usize> = HashMap::default();
1567
1568 for pane_handle in &self.panes {
1569 let pane = pane_handle.read(cx);
1570
1571 for entry in pane.activation_history() {
1572 history.insert(
1573 entry.entity_id,
1574 history
1575 .get(&entry.entity_id)
1576 .cloned()
1577 .unwrap_or(0)
1578 .max(entry.timestamp),
1579 );
1580 }
1581 }
1582
1583 history
1584 }
1585
1586 pub fn recent_navigation_history_iter(
1587 &self,
1588 cx: &App,
1589 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> {
1590 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
1591 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
1592
1593 for pane in &self.panes {
1594 let pane = pane.read(cx);
1595
1596 pane.nav_history()
1597 .for_each_entry(cx, |entry, (project_path, fs_path)| {
1598 if let Some(fs_path) = &fs_path {
1599 abs_paths_opened
1600 .entry(fs_path.clone())
1601 .or_default()
1602 .insert(project_path.clone());
1603 }
1604 let timestamp = entry.timestamp;
1605 match history.entry(project_path) {
1606 hash_map::Entry::Occupied(mut entry) => {
1607 let (_, old_timestamp) = entry.get();
1608 if ×tamp > old_timestamp {
1609 entry.insert((fs_path, timestamp));
1610 }
1611 }
1612 hash_map::Entry::Vacant(entry) => {
1613 entry.insert((fs_path, timestamp));
1614 }
1615 }
1616 });
1617
1618 if let Some(item) = pane.active_item() {
1619 if let Some(project_path) = item.project_path(cx) {
1620 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
1621
1622 if let Some(fs_path) = &fs_path {
1623 abs_paths_opened
1624 .entry(fs_path.clone())
1625 .or_default()
1626 .insert(project_path.clone());
1627 }
1628
1629 history.insert(project_path, (fs_path, std::usize::MAX));
1630 }
1631 }
1632 }
1633
1634 history
1635 .into_iter()
1636 .sorted_by_key(|(_, (_, order))| *order)
1637 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
1638 .rev()
1639 .filter(move |(history_path, abs_path)| {
1640 let latest_project_path_opened = abs_path
1641 .as_ref()
1642 .and_then(|abs_path| abs_paths_opened.get(abs_path))
1643 .and_then(|project_paths| {
1644 project_paths
1645 .iter()
1646 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
1647 });
1648
1649 match latest_project_path_opened {
1650 Some(latest_project_path_opened) => latest_project_path_opened == history_path,
1651 None => true,
1652 }
1653 })
1654 }
1655
1656 pub fn recent_navigation_history(
1657 &self,
1658 limit: Option<usize>,
1659 cx: &App,
1660 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
1661 self.recent_navigation_history_iter(cx)
1662 .take(limit.unwrap_or(usize::MAX))
1663 .collect()
1664 }
1665
1666 fn navigate_history(
1667 &mut self,
1668 pane: WeakEntity<Pane>,
1669 mode: NavigationMode,
1670 window: &mut Window,
1671 cx: &mut Context<Workspace>,
1672 ) -> Task<Result<()>> {
1673 let to_load = if let Some(pane) = pane.upgrade() {
1674 pane.update(cx, |pane, cx| {
1675 window.focus(&pane.focus_handle(cx));
1676 loop {
1677 // Retrieve the weak item handle from the history.
1678 let entry = pane.nav_history_mut().pop(mode, cx)?;
1679
1680 // If the item is still present in this pane, then activate it.
1681 if let Some(index) = entry
1682 .item
1683 .upgrade()
1684 .and_then(|v| pane.index_for_item(v.as_ref()))
1685 {
1686 let prev_active_item_index = pane.active_item_index();
1687 pane.nav_history_mut().set_mode(mode);
1688 pane.activate_item(index, true, true, window, cx);
1689 pane.nav_history_mut().set_mode(NavigationMode::Normal);
1690
1691 let mut navigated = prev_active_item_index != pane.active_item_index();
1692 if let Some(data) = entry.data {
1693 navigated |= pane.active_item()?.navigate(data, window, cx);
1694 }
1695
1696 if navigated {
1697 break None;
1698 }
1699 } else {
1700 // If the item is no longer present in this pane, then retrieve its
1701 // path info in order to reopen it.
1702 break pane
1703 .nav_history()
1704 .path_for_item(entry.item.id())
1705 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
1706 }
1707 }
1708 })
1709 } else {
1710 None
1711 };
1712
1713 if let Some((project_path, abs_path, entry)) = to_load {
1714 // If the item was no longer present, then load it again from its previous path, first try the local path
1715 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
1716
1717 cx.spawn_in(window, async move |workspace, cx| {
1718 let open_by_project_path = open_by_project_path.await;
1719 let mut navigated = false;
1720 match open_by_project_path
1721 .with_context(|| format!("Navigating to {project_path:?}"))
1722 {
1723 Ok((project_entry_id, build_item)) => {
1724 let prev_active_item_id = pane.update(cx, |pane, _| {
1725 pane.nav_history_mut().set_mode(mode);
1726 pane.active_item().map(|p| p.item_id())
1727 })?;
1728
1729 pane.update_in(cx, |pane, window, cx| {
1730 let item = pane.open_item(
1731 project_entry_id,
1732 project_path,
1733 true,
1734 entry.is_preview,
1735 true,
1736 None,
1737 window, cx,
1738 build_item,
1739 );
1740 navigated |= Some(item.item_id()) != prev_active_item_id;
1741 pane.nav_history_mut().set_mode(NavigationMode::Normal);
1742 if let Some(data) = entry.data {
1743 navigated |= item.navigate(data, window, cx);
1744 }
1745 })?;
1746 }
1747 Err(open_by_project_path_e) => {
1748 // Fall back to opening by abs path, in case an external file was opened and closed,
1749 // and its worktree is now dropped
1750 if let Some(abs_path) = abs_path {
1751 let prev_active_item_id = pane.update(cx, |pane, _| {
1752 pane.nav_history_mut().set_mode(mode);
1753 pane.active_item().map(|p| p.item_id())
1754 })?;
1755 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
1756 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
1757 })?;
1758 match open_by_abs_path
1759 .await
1760 .with_context(|| format!("Navigating to {abs_path:?}"))
1761 {
1762 Ok(item) => {
1763 pane.update_in(cx, |pane, window, cx| {
1764 navigated |= Some(item.item_id()) != prev_active_item_id;
1765 pane.nav_history_mut().set_mode(NavigationMode::Normal);
1766 if let Some(data) = entry.data {
1767 navigated |= item.navigate(data, window, cx);
1768 }
1769 })?;
1770 }
1771 Err(open_by_abs_path_e) => {
1772 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
1773 }
1774 }
1775 }
1776 }
1777 }
1778
1779 if !navigated {
1780 workspace
1781 .update_in(cx, |workspace, window, cx| {
1782 Self::navigate_history(workspace, pane, mode, window, cx)
1783 })?
1784 .await?;
1785 }
1786
1787 Ok(())
1788 })
1789 } else {
1790 Task::ready(Ok(()))
1791 }
1792 }
1793
1794 pub fn go_back(
1795 &mut self,
1796 pane: WeakEntity<Pane>,
1797 window: &mut Window,
1798 cx: &mut Context<Workspace>,
1799 ) -> Task<Result<()>> {
1800 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
1801 }
1802
1803 pub fn go_forward(
1804 &mut self,
1805 pane: WeakEntity<Pane>,
1806 window: &mut Window,
1807 cx: &mut Context<Workspace>,
1808 ) -> Task<Result<()>> {
1809 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
1810 }
1811
1812 pub fn reopen_closed_item(
1813 &mut self,
1814 window: &mut Window,
1815 cx: &mut Context<Workspace>,
1816 ) -> Task<Result<()>> {
1817 self.navigate_history(
1818 self.active_pane().downgrade(),
1819 NavigationMode::ReopeningClosedItem,
1820 window,
1821 cx,
1822 )
1823 }
1824
1825 pub fn client(&self) -> &Arc<Client> {
1826 &self.app_state.client
1827 }
1828
1829 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
1830 self.titlebar_item = Some(item);
1831 cx.notify();
1832 }
1833
1834 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
1835 self.on_prompt_for_new_path = Some(prompt)
1836 }
1837
1838 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
1839 self.on_prompt_for_open_path = Some(prompt)
1840 }
1841
1842 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
1843 self.terminal_provider = Some(Box::new(provider));
1844 }
1845
1846 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
1847 self.debugger_provider = Some(Arc::new(provider));
1848 }
1849
1850 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
1851 self.debugger_provider.clone()
1852 }
1853
1854 pub fn serialized_ssh_project(&self) -> Option<SerializedSshProject> {
1855 self.serialized_ssh_project.clone()
1856 }
1857
1858 pub fn set_serialized_ssh_project(&mut self, serialized_ssh_project: SerializedSshProject) {
1859 self.serialized_ssh_project = Some(serialized_ssh_project);
1860 }
1861
1862 pub fn prompt_for_open_path(
1863 &mut self,
1864 path_prompt_options: PathPromptOptions,
1865 lister: DirectoryLister,
1866 window: &mut Window,
1867 cx: &mut Context<Self>,
1868 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
1869 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
1870 let prompt = self.on_prompt_for_open_path.take().unwrap();
1871 let rx = prompt(self, lister, window, cx);
1872 self.on_prompt_for_open_path = Some(prompt);
1873 rx
1874 } else {
1875 let (tx, rx) = oneshot::channel();
1876 let abs_path = cx.prompt_for_paths(path_prompt_options);
1877
1878 cx.spawn_in(window, async move |workspace, cx| {
1879 let Ok(result) = abs_path.await else {
1880 return Ok(());
1881 };
1882
1883 match result {
1884 Ok(result) => {
1885 tx.send(result).ok();
1886 }
1887 Err(err) => {
1888 let rx = workspace.update_in(cx, |workspace, window, cx| {
1889 workspace.show_portal_error(err.to_string(), cx);
1890 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
1891 let rx = prompt(workspace, lister, window, cx);
1892 workspace.on_prompt_for_open_path = Some(prompt);
1893 rx
1894 })?;
1895 if let Ok(path) = rx.await {
1896 tx.send(path).ok();
1897 }
1898 }
1899 };
1900 anyhow::Ok(())
1901 })
1902 .detach();
1903
1904 rx
1905 }
1906 }
1907
1908 pub fn prompt_for_new_path(
1909 &mut self,
1910 lister: DirectoryLister,
1911 window: &mut Window,
1912 cx: &mut Context<Self>,
1913 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
1914 if self.project.read(cx).is_via_collab()
1915 || self.project.read(cx).is_via_ssh()
1916 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
1917 {
1918 let prompt = self.on_prompt_for_new_path.take().unwrap();
1919 let rx = prompt(self, lister, window, cx);
1920 self.on_prompt_for_new_path = Some(prompt);
1921 return rx;
1922 }
1923
1924 let (tx, rx) = oneshot::channel();
1925 cx.spawn_in(window, async move |workspace, cx| {
1926 let abs_path = workspace.update(cx, |workspace, cx| {
1927 let relative_to = workspace
1928 .most_recent_active_path(cx)
1929 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
1930 .or_else(|| {
1931 let project = workspace.project.read(cx);
1932 project.visible_worktrees(cx).find_map(|worktree| {
1933 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
1934 })
1935 })
1936 .or_else(std::env::home_dir)
1937 .unwrap_or_else(|| PathBuf::from(""));
1938 cx.prompt_for_new_path(&relative_to)
1939 })?;
1940 let abs_path = match abs_path.await? {
1941 Ok(path) => path,
1942 Err(err) => {
1943 let rx = workspace.update_in(cx, |workspace, window, cx| {
1944 workspace.show_portal_error(err.to_string(), cx);
1945
1946 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
1947 let rx = prompt(workspace, lister, window, cx);
1948 workspace.on_prompt_for_new_path = Some(prompt);
1949 rx
1950 })?;
1951 if let Ok(path) = rx.await {
1952 tx.send(path).ok();
1953 }
1954 return anyhow::Ok(());
1955 }
1956 };
1957
1958 tx.send(abs_path.map(|path| vec![path])).ok();
1959 anyhow::Ok(())
1960 })
1961 .detach();
1962
1963 rx
1964 }
1965
1966 pub fn titlebar_item(&self) -> Option<AnyView> {
1967 self.titlebar_item.clone()
1968 }
1969
1970 /// Call the given callback with a workspace whose project is local.
1971 ///
1972 /// If the given workspace has a local project, then it will be passed
1973 /// to the callback. Otherwise, a new empty window will be created.
1974 pub fn with_local_workspace<T, F>(
1975 &mut self,
1976 window: &mut Window,
1977 cx: &mut Context<Self>,
1978 callback: F,
1979 ) -> Task<Result<T>>
1980 where
1981 T: 'static,
1982 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
1983 {
1984 if self.project.read(cx).is_local() {
1985 Task::ready(Ok(callback(self, window, cx)))
1986 } else {
1987 let env = self.project.read(cx).cli_environment(cx);
1988 let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, cx);
1989 cx.spawn_in(window, async move |_vh, cx| {
1990 let (workspace, _) = task.await?;
1991 workspace.update(cx, callback)
1992 })
1993 }
1994 }
1995
1996 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
1997 self.project.read(cx).worktrees(cx)
1998 }
1999
2000 pub fn visible_worktrees<'a>(
2001 &self,
2002 cx: &'a App,
2003 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2004 self.project.read(cx).visible_worktrees(cx)
2005 }
2006
2007 #[cfg(any(test, feature = "test-support"))]
2008 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2009 let futures = self
2010 .worktrees(cx)
2011 .filter_map(|worktree| worktree.read(cx).as_local())
2012 .map(|worktree| worktree.scan_complete())
2013 .collect::<Vec<_>>();
2014 async move {
2015 for future in futures {
2016 future.await;
2017 }
2018 }
2019 }
2020
2021 pub fn close_global(_: &CloseWindow, cx: &mut App) {
2022 cx.defer(|cx| {
2023 cx.windows().iter().find(|window| {
2024 window
2025 .update(cx, |_, window, _| {
2026 if window.is_window_active() {
2027 //This can only get called when the window's project connection has been lost
2028 //so we don't need to prompt the user for anything and instead just close the window
2029 window.remove_window();
2030 true
2031 } else {
2032 false
2033 }
2034 })
2035 .unwrap_or(false)
2036 });
2037 });
2038 }
2039
2040 pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
2041 let prepare = self.prepare_to_close(CloseIntent::CloseWindow, window, cx);
2042 cx.spawn_in(window, async move |_, cx| {
2043 if prepare.await? {
2044 cx.update(|window, _cx| window.remove_window())?;
2045 }
2046 anyhow::Ok(())
2047 })
2048 .detach_and_log_err(cx)
2049 }
2050
2051 pub fn move_focused_panel_to_next_position(
2052 &mut self,
2053 _: &MoveFocusedPanelToNextPosition,
2054 window: &mut Window,
2055 cx: &mut Context<Self>,
2056 ) {
2057 let docks = self.all_docks();
2058 let active_dock = docks
2059 .into_iter()
2060 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2061
2062 if let Some(dock) = active_dock {
2063 dock.update(cx, |dock, cx| {
2064 let active_panel = dock
2065 .active_panel()
2066 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2067
2068 if let Some(panel) = active_panel {
2069 panel.move_to_next_position(window, cx);
2070 }
2071 })
2072 }
2073 }
2074
2075 pub fn prepare_to_close(
2076 &mut self,
2077 close_intent: CloseIntent,
2078 window: &mut Window,
2079 cx: &mut Context<Self>,
2080 ) -> Task<Result<bool>> {
2081 let active_call = self.active_call().cloned();
2082
2083 // On Linux and Windows, closing the last window should restore the last workspace.
2084 let save_last_workspace = cfg!(not(target_os = "macos"))
2085 && close_intent != CloseIntent::ReplaceWindow
2086 && cx.windows().len() == 1;
2087
2088 cx.spawn_in(window, async move |this, cx| {
2089 let workspace_count = cx.update(|_window, cx| {
2090 cx.windows()
2091 .iter()
2092 .filter(|window| window.downcast::<Workspace>().is_some())
2093 .count()
2094 })?;
2095
2096 if let Some(active_call) = active_call {
2097 if close_intent != CloseIntent::Quit
2098 && workspace_count == 1
2099 && active_call.read_with(cx, |call, _| call.room().is_some())?
2100 {
2101 let answer = cx.update(|window, cx| {
2102 window.prompt(
2103 PromptLevel::Warning,
2104 "Do you want to leave the current call?",
2105 None,
2106 &["Close window and hang up", "Cancel"],
2107 cx,
2108 )
2109 })?;
2110
2111 if answer.await.log_err() == Some(1) {
2112 return anyhow::Ok(false);
2113 } else {
2114 active_call
2115 .update(cx, |call, cx| call.hang_up(cx))?
2116 .await
2117 .log_err();
2118 }
2119 }
2120 }
2121
2122 let save_result = this
2123 .update_in(cx, |this, window, cx| {
2124 this.save_all_internal(SaveIntent::Close, window, cx)
2125 })?
2126 .await;
2127
2128 // If we're not quitting, but closing, we remove the workspace from
2129 // the current session.
2130 if close_intent != CloseIntent::Quit
2131 && !save_last_workspace
2132 && save_result.as_ref().map_or(false, |&res| res)
2133 {
2134 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2135 .await;
2136 }
2137
2138 save_result
2139 })
2140 }
2141
2142 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2143 self.save_all_internal(
2144 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2145 window,
2146 cx,
2147 )
2148 .detach_and_log_err(cx);
2149 }
2150
2151 fn send_keystrokes(
2152 &mut self,
2153 action: &SendKeystrokes,
2154 window: &mut Window,
2155 cx: &mut Context<Self>,
2156 ) {
2157 let mut state = self.dispatching_keystrokes.borrow_mut();
2158 if !state.0.insert(action.0.clone()) {
2159 cx.propagate();
2160 return;
2161 }
2162 let mut keystrokes: Vec<Keystroke> = action
2163 .0
2164 .split(' ')
2165 .flat_map(|k| Keystroke::parse(k).log_err())
2166 .collect();
2167 keystrokes.reverse();
2168
2169 state.1.append(&mut keystrokes);
2170 drop(state);
2171
2172 let keystrokes = self.dispatching_keystrokes.clone();
2173 window
2174 .spawn(cx, async move |cx| {
2175 // limit to 100 keystrokes to avoid infinite recursion.
2176 for _ in 0..100 {
2177 let Some(keystroke) = keystrokes.borrow_mut().1.pop() else {
2178 keystrokes.borrow_mut().0.clear();
2179 return Ok(());
2180 };
2181 cx.update(|window, cx| {
2182 let focused = window.focused(cx);
2183 window.dispatch_keystroke(keystroke.clone(), cx);
2184 if window.focused(cx) != focused {
2185 // dispatch_keystroke may cause the focus to change.
2186 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
2187 // And we need that to happen before the next keystroke to keep vim mode happy...
2188 // (Note that the tests always do this implicitly, so you must manually test with something like:
2189 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
2190 // )
2191 window.draw(cx);
2192 }
2193 })?;
2194 }
2195
2196 *keystrokes.borrow_mut() = Default::default();
2197 anyhow::bail!("over 100 keystrokes passed to send_keystrokes");
2198 })
2199 .detach_and_log_err(cx);
2200 }
2201
2202 fn save_all_internal(
2203 &mut self,
2204 mut save_intent: SaveIntent,
2205 window: &mut Window,
2206 cx: &mut Context<Self>,
2207 ) -> Task<Result<bool>> {
2208 if self.project.read(cx).is_disconnected(cx) {
2209 return Task::ready(Ok(true));
2210 }
2211 let dirty_items = self
2212 .panes
2213 .iter()
2214 .flat_map(|pane| {
2215 pane.read(cx).items().filter_map(|item| {
2216 if item.is_dirty(cx) {
2217 item.tab_content_text(0, cx);
2218 Some((pane.downgrade(), item.boxed_clone()))
2219 } else {
2220 None
2221 }
2222 })
2223 })
2224 .collect::<Vec<_>>();
2225
2226 let project = self.project.clone();
2227 cx.spawn_in(window, async move |workspace, cx| {
2228 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
2229 let (serialize_tasks, remaining_dirty_items) =
2230 workspace.update_in(cx, |workspace, window, cx| {
2231 let mut remaining_dirty_items = Vec::new();
2232 let mut serialize_tasks = Vec::new();
2233 for (pane, item) in dirty_items {
2234 if let Some(task) = item
2235 .to_serializable_item_handle(cx)
2236 .and_then(|handle| handle.serialize(workspace, true, window, cx))
2237 {
2238 serialize_tasks.push(task);
2239 } else {
2240 remaining_dirty_items.push((pane, item));
2241 }
2242 }
2243 (serialize_tasks, remaining_dirty_items)
2244 })?;
2245
2246 futures::future::try_join_all(serialize_tasks).await?;
2247
2248 if remaining_dirty_items.len() > 1 {
2249 let answer = workspace.update_in(cx, |_, window, cx| {
2250 let detail = Pane::file_names_for_prompt(
2251 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
2252 cx,
2253 );
2254 window.prompt(
2255 PromptLevel::Warning,
2256 &"Do you want to save all changes in the following files?",
2257 Some(&detail),
2258 &["Save all", "Discard all", "Cancel"],
2259 cx,
2260 )
2261 })?;
2262 match answer.await.log_err() {
2263 Some(0) => save_intent = SaveIntent::SaveAll,
2264 Some(1) => save_intent = SaveIntent::Skip,
2265 Some(2) => return Ok(false),
2266 _ => {}
2267 }
2268 }
2269
2270 remaining_dirty_items
2271 } else {
2272 dirty_items
2273 };
2274
2275 for (pane, item) in dirty_items {
2276 let (singleton, project_entry_ids) =
2277 cx.update(|_, cx| (item.is_singleton(cx), item.project_entry_ids(cx)))?;
2278 if singleton || !project_entry_ids.is_empty() {
2279 if !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await? {
2280 return Ok(false);
2281 }
2282 }
2283 }
2284 Ok(true)
2285 })
2286 }
2287
2288 pub fn open_workspace_for_paths(
2289 &mut self,
2290 replace_current_window: bool,
2291 paths: Vec<PathBuf>,
2292 window: &mut Window,
2293 cx: &mut Context<Self>,
2294 ) -> Task<Result<()>> {
2295 let window_handle = window.window_handle().downcast::<Self>();
2296 let is_remote = self.project.read(cx).is_via_collab();
2297 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
2298 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
2299
2300 let window_to_replace = if replace_current_window {
2301 window_handle
2302 } else if is_remote || has_worktree || has_dirty_items {
2303 None
2304 } else {
2305 window_handle
2306 };
2307 let app_state = self.app_state.clone();
2308
2309 cx.spawn(async move |_, cx| {
2310 cx.update(|cx| {
2311 open_paths(
2312 &paths,
2313 app_state,
2314 OpenOptions {
2315 replace_window: window_to_replace,
2316 ..Default::default()
2317 },
2318 cx,
2319 )
2320 })?
2321 .await?;
2322 Ok(())
2323 })
2324 }
2325
2326 #[allow(clippy::type_complexity)]
2327 pub fn open_paths(
2328 &mut self,
2329 mut abs_paths: Vec<PathBuf>,
2330 options: OpenOptions,
2331 pane: Option<WeakEntity<Pane>>,
2332 window: &mut Window,
2333 cx: &mut Context<Self>,
2334 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
2335 log::info!("open paths {abs_paths:?}");
2336
2337 let fs = self.app_state.fs.clone();
2338
2339 // Sort the paths to ensure we add worktrees for parents before their children.
2340 abs_paths.sort_unstable();
2341 cx.spawn_in(window, async move |this, cx| {
2342 let mut tasks = Vec::with_capacity(abs_paths.len());
2343
2344 for abs_path in &abs_paths {
2345 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
2346 OpenVisible::All => Some(true),
2347 OpenVisible::None => Some(false),
2348 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
2349 Some(Some(metadata)) => Some(!metadata.is_dir),
2350 Some(None) => Some(true),
2351 None => None,
2352 },
2353 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
2354 Some(Some(metadata)) => Some(metadata.is_dir),
2355 Some(None) => Some(false),
2356 None => None,
2357 },
2358 };
2359 let project_path = match visible {
2360 Some(visible) => match this
2361 .update(cx, |this, cx| {
2362 Workspace::project_path_for_path(
2363 this.project.clone(),
2364 abs_path,
2365 visible,
2366 cx,
2367 )
2368 })
2369 .log_err()
2370 {
2371 Some(project_path) => project_path.await.log_err(),
2372 None => None,
2373 },
2374 None => None,
2375 };
2376
2377 let this = this.clone();
2378 let abs_path: Arc<Path> = SanitizedPath::from(abs_path.clone()).into();
2379 let fs = fs.clone();
2380 let pane = pane.clone();
2381 let task = cx.spawn(async move |cx| {
2382 let (worktree, project_path) = project_path?;
2383 if fs.is_dir(&abs_path).await {
2384 this.update(cx, |workspace, cx| {
2385 let worktree = worktree.read(cx);
2386 let worktree_abs_path = worktree.abs_path();
2387 let entry_id = if abs_path.as_ref() == worktree_abs_path.as_ref() {
2388 worktree.root_entry()
2389 } else {
2390 abs_path
2391 .strip_prefix(worktree_abs_path.as_ref())
2392 .ok()
2393 .and_then(|relative_path| {
2394 worktree.entry_for_path(relative_path)
2395 })
2396 }
2397 .map(|entry| entry.id);
2398 if let Some(entry_id) = entry_id {
2399 workspace.project.update(cx, |_, cx| {
2400 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
2401 })
2402 }
2403 })
2404 .log_err()?;
2405 None
2406 } else {
2407 Some(
2408 this.update_in(cx, |this, window, cx| {
2409 this.open_path(
2410 project_path,
2411 pane,
2412 options.focus.unwrap_or(true),
2413 window,
2414 cx,
2415 )
2416 })
2417 .log_err()?
2418 .await,
2419 )
2420 }
2421 });
2422 tasks.push(task);
2423 }
2424
2425 futures::future::join_all(tasks).await
2426 })
2427 }
2428
2429 pub fn open_resolved_path(
2430 &mut self,
2431 path: ResolvedPath,
2432 window: &mut Window,
2433 cx: &mut Context<Self>,
2434 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
2435 match path {
2436 ResolvedPath::ProjectPath { project_path, .. } => {
2437 self.open_path(project_path, None, true, window, cx)
2438 }
2439 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
2440 path,
2441 OpenOptions {
2442 visible: Some(OpenVisible::None),
2443 ..Default::default()
2444 },
2445 window,
2446 cx,
2447 ),
2448 }
2449 }
2450
2451 pub fn absolute_path_of_worktree(
2452 &self,
2453 worktree_id: WorktreeId,
2454 cx: &mut Context<Self>,
2455 ) -> Option<PathBuf> {
2456 self.project
2457 .read(cx)
2458 .worktree_for_id(worktree_id, cx)
2459 // TODO: use `abs_path` or `root_dir`
2460 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
2461 }
2462
2463 fn add_folder_to_project(
2464 &mut self,
2465 _: &AddFolderToProject,
2466 window: &mut Window,
2467 cx: &mut Context<Self>,
2468 ) {
2469 let project = self.project.read(cx);
2470 if project.is_via_collab() {
2471 self.show_error(
2472 &anyhow!("You cannot add folders to someone else's project"),
2473 cx,
2474 );
2475 return;
2476 }
2477 let paths = self.prompt_for_open_path(
2478 PathPromptOptions {
2479 files: false,
2480 directories: true,
2481 multiple: true,
2482 },
2483 DirectoryLister::Project(self.project.clone()),
2484 window,
2485 cx,
2486 );
2487 cx.spawn_in(window, async move |this, cx| {
2488 if let Some(paths) = paths.await.log_err().flatten() {
2489 let results = this
2490 .update_in(cx, |this, window, cx| {
2491 this.open_paths(
2492 paths,
2493 OpenOptions {
2494 visible: Some(OpenVisible::All),
2495 ..Default::default()
2496 },
2497 None,
2498 window,
2499 cx,
2500 )
2501 })?
2502 .await;
2503 for result in results.into_iter().flatten() {
2504 result.log_err();
2505 }
2506 }
2507 anyhow::Ok(())
2508 })
2509 .detach_and_log_err(cx);
2510 }
2511
2512 pub fn project_path_for_path(
2513 project: Entity<Project>,
2514 abs_path: &Path,
2515 visible: bool,
2516 cx: &mut App,
2517 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
2518 let entry = project.update(cx, |project, cx| {
2519 project.find_or_create_worktree(abs_path, visible, cx)
2520 });
2521 cx.spawn(async move |cx| {
2522 let (worktree, path) = entry.await?;
2523 let worktree_id = worktree.read_with(cx, |t, _| t.id())?;
2524 Ok((
2525 worktree,
2526 ProjectPath {
2527 worktree_id,
2528 path: path.into(),
2529 },
2530 ))
2531 })
2532 }
2533
2534 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
2535 self.panes.iter().flat_map(|pane| pane.read(cx).items())
2536 }
2537
2538 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
2539 self.items_of_type(cx).max_by_key(|item| item.item_id())
2540 }
2541
2542 pub fn items_of_type<'a, T: Item>(
2543 &'a self,
2544 cx: &'a App,
2545 ) -> impl 'a + Iterator<Item = Entity<T>> {
2546 self.panes
2547 .iter()
2548 .flat_map(|pane| pane.read(cx).items_of_type())
2549 }
2550
2551 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
2552 self.active_pane().read(cx).active_item()
2553 }
2554
2555 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
2556 let item = self.active_item(cx)?;
2557 item.to_any().downcast::<I>().ok()
2558 }
2559
2560 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
2561 self.active_item(cx).and_then(|item| item.project_path(cx))
2562 }
2563
2564 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
2565 self.recent_navigation_history_iter(cx)
2566 .filter_map(|(path, abs_path)| {
2567 let worktree = self
2568 .project
2569 .read(cx)
2570 .worktree_for_id(path.worktree_id, cx)?;
2571 if worktree.read(cx).is_visible() {
2572 abs_path
2573 } else {
2574 None
2575 }
2576 })
2577 .next()
2578 }
2579
2580 pub fn save_active_item(
2581 &mut self,
2582 save_intent: SaveIntent,
2583 window: &mut Window,
2584 cx: &mut App,
2585 ) -> Task<Result<()>> {
2586 let project = self.project.clone();
2587 let pane = self.active_pane();
2588 let item = pane.read(cx).active_item();
2589 let pane = pane.downgrade();
2590
2591 window.spawn(cx, async move |mut cx| {
2592 if let Some(item) = item {
2593 Pane::save_item(project, &pane, item.as_ref(), save_intent, &mut cx)
2594 .await
2595 .map(|_| ())
2596 } else {
2597 Ok(())
2598 }
2599 })
2600 }
2601
2602 pub fn close_inactive_items_and_panes(
2603 &mut self,
2604 action: &CloseInactiveTabsAndPanes,
2605 window: &mut Window,
2606 cx: &mut Context<Self>,
2607 ) {
2608 if let Some(task) = self.close_all_internal(
2609 true,
2610 action.save_intent.unwrap_or(SaveIntent::Close),
2611 window,
2612 cx,
2613 ) {
2614 task.detach_and_log_err(cx)
2615 }
2616 }
2617
2618 pub fn close_all_items_and_panes(
2619 &mut self,
2620 action: &CloseAllItemsAndPanes,
2621 window: &mut Window,
2622 cx: &mut Context<Self>,
2623 ) {
2624 if let Some(task) = self.close_all_internal(
2625 false,
2626 action.save_intent.unwrap_or(SaveIntent::Close),
2627 window,
2628 cx,
2629 ) {
2630 task.detach_and_log_err(cx)
2631 }
2632 }
2633
2634 fn close_all_internal(
2635 &mut self,
2636 retain_active_pane: bool,
2637 save_intent: SaveIntent,
2638 window: &mut Window,
2639 cx: &mut Context<Self>,
2640 ) -> Option<Task<Result<()>>> {
2641 let current_pane = self.active_pane();
2642
2643 let mut tasks = Vec::new();
2644
2645 if retain_active_pane {
2646 let current_pane_close = current_pane.update(cx, |pane, cx| {
2647 pane.close_inactive_items(
2648 &CloseInactiveItems {
2649 save_intent: None,
2650 close_pinned: false,
2651 },
2652 window,
2653 cx,
2654 )
2655 });
2656
2657 tasks.push(current_pane_close);
2658 }
2659
2660 for pane in self.panes() {
2661 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
2662 continue;
2663 }
2664
2665 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
2666 pane.close_all_items(
2667 &CloseAllItems {
2668 save_intent: Some(save_intent),
2669 close_pinned: false,
2670 },
2671 window,
2672 cx,
2673 )
2674 });
2675
2676 tasks.push(close_pane_items)
2677 }
2678
2679 if tasks.is_empty() {
2680 None
2681 } else {
2682 Some(cx.spawn_in(window, async move |_, _| {
2683 for task in tasks {
2684 task.await?
2685 }
2686 Ok(())
2687 }))
2688 }
2689 }
2690
2691 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
2692 self.dock_at_position(position).read(cx).is_open()
2693 }
2694
2695 pub fn toggle_dock(
2696 &mut self,
2697 dock_side: DockPosition,
2698 window: &mut Window,
2699 cx: &mut Context<Self>,
2700 ) {
2701 let dock = self.dock_at_position(dock_side);
2702 let mut focus_center = false;
2703 let mut reveal_dock = false;
2704 dock.update(cx, |dock, cx| {
2705 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
2706 let was_visible = dock.is_open() && !other_is_zoomed;
2707 dock.set_open(!was_visible, window, cx);
2708
2709 if dock.active_panel().is_none() {
2710 let Some(panel_ix) = dock
2711 .first_enabled_panel_idx(cx)
2712 .log_with_level(log::Level::Info)
2713 else {
2714 return;
2715 };
2716 dock.activate_panel(panel_ix, window, cx);
2717 }
2718
2719 if let Some(active_panel) = dock.active_panel() {
2720 if was_visible {
2721 if active_panel
2722 .panel_focus_handle(cx)
2723 .contains_focused(window, cx)
2724 {
2725 focus_center = true;
2726 }
2727 } else {
2728 let focus_handle = &active_panel.panel_focus_handle(cx);
2729 window.focus(focus_handle);
2730 reveal_dock = true;
2731 }
2732 }
2733 });
2734
2735 if reveal_dock {
2736 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
2737 }
2738
2739 if focus_center {
2740 self.active_pane
2741 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
2742 }
2743
2744 cx.notify();
2745 self.serialize_workspace(window, cx);
2746 }
2747
2748 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
2749 self.all_docks().into_iter().find(|&dock| {
2750 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
2751 })
2752 }
2753
2754 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2755 if let Some(dock) = self.active_dock(window, cx) {
2756 dock.update(cx, |dock, cx| {
2757 dock.set_open(false, window, cx);
2758 });
2759 }
2760 }
2761
2762 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2763 for dock in self.all_docks() {
2764 dock.update(cx, |dock, cx| {
2765 dock.set_open(false, window, cx);
2766 });
2767 }
2768
2769 cx.focus_self(window);
2770 cx.notify();
2771 self.serialize_workspace(window, cx);
2772 }
2773
2774 /// Transfer focus to the panel of the given type.
2775 pub fn focus_panel<T: Panel>(
2776 &mut self,
2777 window: &mut Window,
2778 cx: &mut Context<Self>,
2779 ) -> Option<Entity<T>> {
2780 let panel = self.focus_or_unfocus_panel::<T>(window, cx, |_, _, _| true)?;
2781 panel.to_any().downcast().ok()
2782 }
2783
2784 /// Focus the panel of the given type if it isn't already focused. If it is
2785 /// already focused, then transfer focus back to the workspace center.
2786 pub fn toggle_panel_focus<T: Panel>(
2787 &mut self,
2788 window: &mut Window,
2789 cx: &mut Context<Self>,
2790 ) -> bool {
2791 let mut did_focus_panel = false;
2792 self.focus_or_unfocus_panel::<T>(window, cx, |panel, window, cx| {
2793 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
2794 did_focus_panel
2795 });
2796 did_focus_panel
2797 }
2798
2799 pub fn activate_panel_for_proto_id(
2800 &mut self,
2801 panel_id: PanelId,
2802 window: &mut Window,
2803 cx: &mut Context<Self>,
2804 ) -> Option<Arc<dyn PanelHandle>> {
2805 let mut panel = None;
2806 for dock in self.all_docks() {
2807 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
2808 panel = dock.update(cx, |dock, cx| {
2809 dock.activate_panel(panel_index, window, cx);
2810 dock.set_open(true, window, cx);
2811 dock.active_panel().cloned()
2812 });
2813 break;
2814 }
2815 }
2816
2817 if panel.is_some() {
2818 cx.notify();
2819 self.serialize_workspace(window, cx);
2820 }
2821
2822 panel
2823 }
2824
2825 /// Focus or unfocus the given panel type, depending on the given callback.
2826 fn focus_or_unfocus_panel<T: Panel>(
2827 &mut self,
2828 window: &mut Window,
2829 cx: &mut Context<Self>,
2830 mut should_focus: impl FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
2831 ) -> Option<Arc<dyn PanelHandle>> {
2832 let mut result_panel = None;
2833 let mut serialize = false;
2834 for dock in self.all_docks() {
2835 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
2836 let mut focus_center = false;
2837 let panel = dock.update(cx, |dock, cx| {
2838 dock.activate_panel(panel_index, window, cx);
2839
2840 let panel = dock.active_panel().cloned();
2841 if let Some(panel) = panel.as_ref() {
2842 if should_focus(&**panel, window, cx) {
2843 dock.set_open(true, window, cx);
2844 panel.panel_focus_handle(cx).focus(window);
2845 } else {
2846 focus_center = true;
2847 }
2848 }
2849 panel
2850 });
2851
2852 if focus_center {
2853 self.active_pane
2854 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
2855 }
2856
2857 result_panel = panel;
2858 serialize = true;
2859 break;
2860 }
2861 }
2862
2863 if serialize {
2864 self.serialize_workspace(window, cx);
2865 }
2866
2867 cx.notify();
2868 result_panel
2869 }
2870
2871 /// Open the panel of the given type
2872 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2873 for dock in self.all_docks() {
2874 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
2875 dock.update(cx, |dock, cx| {
2876 dock.activate_panel(panel_index, window, cx);
2877 dock.set_open(true, window, cx);
2878 });
2879 }
2880 }
2881 }
2882
2883 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
2884 self.all_docks()
2885 .iter()
2886 .find_map(|dock| dock.read(cx).panel::<T>())
2887 }
2888
2889 fn dismiss_zoomed_items_to_reveal(
2890 &mut self,
2891 dock_to_reveal: Option<DockPosition>,
2892 window: &mut Window,
2893 cx: &mut Context<Self>,
2894 ) {
2895 // If a center pane is zoomed, unzoom it.
2896 for pane in &self.panes {
2897 if pane != &self.active_pane || dock_to_reveal.is_some() {
2898 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
2899 }
2900 }
2901
2902 // If another dock is zoomed, hide it.
2903 let mut focus_center = false;
2904 for dock in self.all_docks() {
2905 dock.update(cx, |dock, cx| {
2906 if Some(dock.position()) != dock_to_reveal {
2907 if let Some(panel) = dock.active_panel() {
2908 if panel.is_zoomed(window, cx) {
2909 focus_center |=
2910 panel.panel_focus_handle(cx).contains_focused(window, cx);
2911 dock.set_open(false, window, cx);
2912 }
2913 }
2914 }
2915 });
2916 }
2917
2918 if focus_center {
2919 self.active_pane
2920 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
2921 }
2922
2923 if self.zoomed_position != dock_to_reveal {
2924 self.zoomed = None;
2925 self.zoomed_position = None;
2926 cx.emit(Event::ZoomChanged);
2927 }
2928
2929 cx.notify();
2930 }
2931
2932 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
2933 let pane = cx.new(|cx| {
2934 let mut pane = Pane::new(
2935 self.weak_handle(),
2936 self.project.clone(),
2937 self.pane_history_timestamp.clone(),
2938 None,
2939 NewFile.boxed_clone(),
2940 window,
2941 cx,
2942 );
2943 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
2944 pane
2945 });
2946 cx.subscribe_in(&pane, window, Self::handle_pane_event)
2947 .detach();
2948 self.panes.push(pane.clone());
2949
2950 window.focus(&pane.focus_handle(cx));
2951
2952 cx.emit(Event::PaneAdded(pane.clone()));
2953 pane
2954 }
2955
2956 pub fn add_item_to_center(
2957 &mut self,
2958 item: Box<dyn ItemHandle>,
2959 window: &mut Window,
2960 cx: &mut Context<Self>,
2961 ) -> bool {
2962 if let Some(center_pane) = self.last_active_center_pane.clone() {
2963 if let Some(center_pane) = center_pane.upgrade() {
2964 center_pane.update(cx, |pane, cx| {
2965 pane.add_item(item, true, true, None, window, cx)
2966 });
2967 true
2968 } else {
2969 false
2970 }
2971 } else {
2972 false
2973 }
2974 }
2975
2976 pub fn add_item_to_active_pane(
2977 &mut self,
2978 item: Box<dyn ItemHandle>,
2979 destination_index: Option<usize>,
2980 focus_item: bool,
2981 window: &mut Window,
2982 cx: &mut App,
2983 ) {
2984 self.add_item(
2985 self.active_pane.clone(),
2986 item,
2987 destination_index,
2988 false,
2989 focus_item,
2990 window,
2991 cx,
2992 )
2993 }
2994
2995 pub fn add_item(
2996 &mut self,
2997 pane: Entity<Pane>,
2998 item: Box<dyn ItemHandle>,
2999 destination_index: Option<usize>,
3000 activate_pane: bool,
3001 focus_item: bool,
3002 window: &mut Window,
3003 cx: &mut App,
3004 ) {
3005 if let Some(text) = item.telemetry_event_text(cx) {
3006 telemetry::event!(text);
3007 }
3008
3009 pane.update(cx, |pane, cx| {
3010 pane.add_item(
3011 item,
3012 activate_pane,
3013 focus_item,
3014 destination_index,
3015 window,
3016 cx,
3017 )
3018 });
3019 }
3020
3021 pub fn split_item(
3022 &mut self,
3023 split_direction: SplitDirection,
3024 item: Box<dyn ItemHandle>,
3025 window: &mut Window,
3026 cx: &mut Context<Self>,
3027 ) {
3028 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
3029 self.add_item(new_pane, item, None, true, true, window, cx);
3030 }
3031
3032 pub fn open_abs_path(
3033 &mut self,
3034 abs_path: PathBuf,
3035 options: OpenOptions,
3036 window: &mut Window,
3037 cx: &mut Context<Self>,
3038 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3039 cx.spawn_in(window, async move |workspace, cx| {
3040 let open_paths_task_result = workspace
3041 .update_in(cx, |workspace, window, cx| {
3042 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
3043 })
3044 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
3045 .await;
3046 anyhow::ensure!(
3047 open_paths_task_result.len() == 1,
3048 "open abs path {abs_path:?} task returned incorrect number of results"
3049 );
3050 match open_paths_task_result
3051 .into_iter()
3052 .next()
3053 .expect("ensured single task result")
3054 {
3055 Some(open_result) => {
3056 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
3057 }
3058 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
3059 }
3060 })
3061 }
3062
3063 pub fn split_abs_path(
3064 &mut self,
3065 abs_path: PathBuf,
3066 visible: bool,
3067 window: &mut Window,
3068 cx: &mut Context<Self>,
3069 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3070 let project_path_task =
3071 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
3072 cx.spawn_in(window, async move |this, cx| {
3073 let (_, path) = project_path_task.await?;
3074 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
3075 .await
3076 })
3077 }
3078
3079 pub fn open_path(
3080 &mut self,
3081 path: impl Into<ProjectPath>,
3082 pane: Option<WeakEntity<Pane>>,
3083 focus_item: bool,
3084 window: &mut Window,
3085 cx: &mut App,
3086 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3087 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
3088 }
3089
3090 pub fn open_path_preview(
3091 &mut self,
3092 path: impl Into<ProjectPath>,
3093 pane: Option<WeakEntity<Pane>>,
3094 focus_item: bool,
3095 allow_preview: bool,
3096 activate: bool,
3097 window: &mut Window,
3098 cx: &mut App,
3099 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3100 let pane = pane.unwrap_or_else(|| {
3101 self.last_active_center_pane.clone().unwrap_or_else(|| {
3102 self.panes
3103 .first()
3104 .expect("There must be an active pane")
3105 .downgrade()
3106 })
3107 });
3108
3109 let project_path = path.into();
3110 let task = self.load_path(project_path.clone(), window, cx);
3111 window.spawn(cx, async move |cx| {
3112 let (project_entry_id, build_item) = task.await?;
3113 let result = pane.update_in(cx, |pane, window, cx| {
3114 let result = pane.open_item(
3115 project_entry_id,
3116 project_path,
3117 focus_item,
3118 allow_preview,
3119 activate,
3120 None,
3121 window,
3122 cx,
3123 build_item,
3124 );
3125
3126 result
3127 });
3128 result
3129 })
3130 }
3131
3132 pub fn split_path(
3133 &mut self,
3134 path: impl Into<ProjectPath>,
3135 window: &mut Window,
3136 cx: &mut Context<Self>,
3137 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3138 self.split_path_preview(path, false, None, window, cx)
3139 }
3140
3141 pub fn split_path_preview(
3142 &mut self,
3143 path: impl Into<ProjectPath>,
3144 allow_preview: bool,
3145 split_direction: Option<SplitDirection>,
3146 window: &mut Window,
3147 cx: &mut Context<Self>,
3148 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3149 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
3150 self.panes
3151 .first()
3152 .expect("There must be an active pane")
3153 .downgrade()
3154 });
3155
3156 if let Member::Pane(center_pane) = &self.center.root {
3157 if center_pane.read(cx).items_len() == 0 {
3158 return self.open_path(path, Some(pane), true, window, cx);
3159 }
3160 }
3161
3162 let project_path = path.into();
3163 let task = self.load_path(project_path.clone(), window, cx);
3164 cx.spawn_in(window, async move |this, cx| {
3165 let (project_entry_id, build_item) = task.await?;
3166 this.update_in(cx, move |this, window, cx| -> Option<_> {
3167 let pane = pane.upgrade()?;
3168 let new_pane = this.split_pane(
3169 pane,
3170 split_direction.unwrap_or(SplitDirection::Right),
3171 window,
3172 cx,
3173 );
3174 new_pane.update(cx, |new_pane, cx| {
3175 Some(new_pane.open_item(
3176 project_entry_id,
3177 project_path,
3178 true,
3179 allow_preview,
3180 true,
3181 None,
3182 window,
3183 cx,
3184 build_item,
3185 ))
3186 })
3187 })
3188 .map(|option| option.context("pane was dropped"))?
3189 })
3190 }
3191
3192 fn load_path(
3193 &mut self,
3194 path: ProjectPath,
3195 window: &mut Window,
3196 cx: &mut App,
3197 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
3198 let project = self.project().clone();
3199 let registry = cx.default_global::<ProjectItemRegistry>().clone();
3200 registry.open_path(&project, &path, window, cx)
3201 }
3202
3203 pub fn find_project_item<T>(
3204 &self,
3205 pane: &Entity<Pane>,
3206 project_item: &Entity<T::Item>,
3207 cx: &App,
3208 ) -> Option<Entity<T>>
3209 where
3210 T: ProjectItem,
3211 {
3212 use project::ProjectItem as _;
3213 let project_item = project_item.read(cx);
3214 let entry_id = project_item.entry_id(cx);
3215 let project_path = project_item.project_path(cx);
3216
3217 let mut item = None;
3218 if let Some(entry_id) = entry_id {
3219 item = pane.read(cx).item_for_entry(entry_id, cx);
3220 }
3221 if item.is_none() {
3222 if let Some(project_path) = project_path {
3223 item = pane.read(cx).item_for_path(project_path, cx);
3224 }
3225 }
3226
3227 item.and_then(|item| item.downcast::<T>())
3228 }
3229
3230 pub fn is_project_item_open<T>(
3231 &self,
3232 pane: &Entity<Pane>,
3233 project_item: &Entity<T::Item>,
3234 cx: &App,
3235 ) -> bool
3236 where
3237 T: ProjectItem,
3238 {
3239 self.find_project_item::<T>(pane, project_item, cx)
3240 .is_some()
3241 }
3242
3243 pub fn open_project_item<T>(
3244 &mut self,
3245 pane: Entity<Pane>,
3246 project_item: Entity<T::Item>,
3247 activate_pane: bool,
3248 focus_item: bool,
3249 window: &mut Window,
3250 cx: &mut Context<Self>,
3251 ) -> Entity<T>
3252 where
3253 T: ProjectItem,
3254 {
3255 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
3256 self.activate_item(&item, activate_pane, focus_item, window, cx);
3257 return item;
3258 }
3259
3260 let item = pane.update(cx, |pane, cx| {
3261 cx.new(|cx| {
3262 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
3263 })
3264 });
3265 let item_id = item.item_id();
3266 let mut destination_index = None;
3267 pane.update(cx, |pane, cx| {
3268 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
3269 if let Some(preview_item_id) = pane.preview_item_id() {
3270 if preview_item_id != item_id {
3271 destination_index = pane.close_current_preview_item(window, cx);
3272 }
3273 }
3274 }
3275 pane.set_preview_item_id(Some(item.item_id()), cx)
3276 });
3277
3278 self.add_item(
3279 pane,
3280 Box::new(item.clone()),
3281 destination_index,
3282 activate_pane,
3283 focus_item,
3284 window,
3285 cx,
3286 );
3287 item
3288 }
3289
3290 pub fn open_shared_screen(
3291 &mut self,
3292 peer_id: PeerId,
3293 window: &mut Window,
3294 cx: &mut Context<Self>,
3295 ) {
3296 if let Some(shared_screen) =
3297 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
3298 {
3299 self.active_pane.update(cx, |pane, cx| {
3300 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
3301 });
3302 }
3303 }
3304
3305 pub fn activate_item(
3306 &mut self,
3307 item: &dyn ItemHandle,
3308 activate_pane: bool,
3309 focus_item: bool,
3310 window: &mut Window,
3311 cx: &mut App,
3312 ) -> bool {
3313 let result = self.panes.iter().find_map(|pane| {
3314 pane.read(cx)
3315 .index_for_item(item)
3316 .map(|ix| (pane.clone(), ix))
3317 });
3318 if let Some((pane, ix)) = result {
3319 pane.update(cx, |pane, cx| {
3320 pane.activate_item(ix, activate_pane, focus_item, window, cx)
3321 });
3322 true
3323 } else {
3324 false
3325 }
3326 }
3327
3328 fn activate_pane_at_index(
3329 &mut self,
3330 action: &ActivatePane,
3331 window: &mut Window,
3332 cx: &mut Context<Self>,
3333 ) {
3334 let panes = self.center.panes();
3335 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
3336 window.focus(&pane.focus_handle(cx));
3337 } else {
3338 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx);
3339 }
3340 }
3341
3342 fn move_item_to_pane_at_index(
3343 &mut self,
3344 action: &MoveItemToPane,
3345 window: &mut Window,
3346 cx: &mut Context<Self>,
3347 ) {
3348 let panes = self.center.panes();
3349 let destination = match panes.get(action.destination) {
3350 Some(&destination) => destination.clone(),
3351 None => {
3352 if self.active_pane.read(cx).items_len() < 2 {
3353 return;
3354 }
3355 let direction = SplitDirection::Right;
3356 let split_off_pane = self
3357 .find_pane_in_direction(direction, cx)
3358 .unwrap_or_else(|| self.active_pane.clone());
3359 let new_pane = self.add_pane(window, cx);
3360 if self
3361 .center
3362 .split(&split_off_pane, &new_pane, direction)
3363 .log_err()
3364 .is_none()
3365 {
3366 return;
3367 };
3368 new_pane
3369 }
3370 };
3371
3372 move_active_item(
3373 &self.active_pane,
3374 &destination,
3375 action.focus,
3376 true,
3377 window,
3378 cx,
3379 )
3380 }
3381
3382 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
3383 let panes = self.center.panes();
3384 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
3385 let next_ix = (ix + 1) % panes.len();
3386 let next_pane = panes[next_ix].clone();
3387 window.focus(&next_pane.focus_handle(cx));
3388 }
3389 }
3390
3391 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
3392 let panes = self.center.panes();
3393 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
3394 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
3395 let prev_pane = panes[prev_ix].clone();
3396 window.focus(&prev_pane.focus_handle(cx));
3397 }
3398 }
3399
3400 pub fn activate_pane_in_direction(
3401 &mut self,
3402 direction: SplitDirection,
3403 window: &mut Window,
3404 cx: &mut App,
3405 ) {
3406 use ActivateInDirectionTarget as Target;
3407 enum Origin {
3408 LeftDock,
3409 RightDock,
3410 BottomDock,
3411 Center,
3412 }
3413
3414 let origin: Origin = [
3415 (&self.left_dock, Origin::LeftDock),
3416 (&self.right_dock, Origin::RightDock),
3417 (&self.bottom_dock, Origin::BottomDock),
3418 ]
3419 .into_iter()
3420 .find_map(|(dock, origin)| {
3421 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
3422 Some(origin)
3423 } else {
3424 None
3425 }
3426 })
3427 .unwrap_or(Origin::Center);
3428
3429 let get_last_active_pane = || {
3430 let pane = self
3431 .last_active_center_pane
3432 .clone()
3433 .unwrap_or_else(|| {
3434 self.panes
3435 .first()
3436 .expect("There must be an active pane")
3437 .downgrade()
3438 })
3439 .upgrade()?;
3440 (pane.read(cx).items_len() != 0).then_some(pane)
3441 };
3442
3443 let try_dock =
3444 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
3445
3446 let target = match (origin, direction) {
3447 // We're in the center, so we first try to go to a different pane,
3448 // otherwise try to go to a dock.
3449 (Origin::Center, direction) => {
3450 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
3451 Some(Target::Pane(pane))
3452 } else {
3453 match direction {
3454 SplitDirection::Up => None,
3455 SplitDirection::Down => try_dock(&self.bottom_dock),
3456 SplitDirection::Left => try_dock(&self.left_dock),
3457 SplitDirection::Right => try_dock(&self.right_dock),
3458 }
3459 }
3460 }
3461
3462 (Origin::LeftDock, SplitDirection::Right) => {
3463 if let Some(last_active_pane) = get_last_active_pane() {
3464 Some(Target::Pane(last_active_pane))
3465 } else {
3466 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
3467 }
3468 }
3469
3470 (Origin::LeftDock, SplitDirection::Down)
3471 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
3472
3473 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
3474 (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
3475 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
3476
3477 (Origin::RightDock, SplitDirection::Left) => {
3478 if let Some(last_active_pane) = get_last_active_pane() {
3479 Some(Target::Pane(last_active_pane))
3480 } else {
3481 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
3482 }
3483 }
3484
3485 _ => None,
3486 };
3487
3488 match target {
3489 Some(ActivateInDirectionTarget::Pane(pane)) => {
3490 let pane = pane.read(cx);
3491 if let Some(item) = pane.active_item() {
3492 item.item_focus_handle(cx).focus(window);
3493 } else {
3494 log::error!(
3495 "Could not find a focus target when in switching focus in {direction} direction for a pane",
3496 );
3497 }
3498 }
3499 Some(ActivateInDirectionTarget::Dock(dock)) => {
3500 // Defer this to avoid a panic when the dock's active panel is already on the stack.
3501 window.defer(cx, move |window, cx| {
3502 let dock = dock.read(cx);
3503 if let Some(panel) = dock.active_panel() {
3504 panel.panel_focus_handle(cx).focus(window);
3505 } else {
3506 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
3507 }
3508 })
3509 }
3510 None => {}
3511 }
3512 }
3513
3514 pub fn move_item_to_pane_in_direction(
3515 &mut self,
3516 action: &MoveItemToPaneInDirection,
3517 window: &mut Window,
3518 cx: &mut Context<Self>,
3519 ) {
3520 let destination = match self.find_pane_in_direction(action.direction, cx) {
3521 Some(destination) => destination,
3522 None => {
3523 if self.active_pane.read(cx).items_len() < 2 {
3524 return;
3525 }
3526 let new_pane = self.add_pane(window, cx);
3527 if self
3528 .center
3529 .split(&self.active_pane, &new_pane, action.direction)
3530 .log_err()
3531 .is_none()
3532 {
3533 return;
3534 };
3535 new_pane
3536 }
3537 };
3538
3539 move_active_item(
3540 &self.active_pane,
3541 &destination,
3542 action.focus,
3543 true,
3544 window,
3545 cx,
3546 );
3547 }
3548
3549 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
3550 self.center.bounding_box_for_pane(pane)
3551 }
3552
3553 pub fn find_pane_in_direction(
3554 &mut self,
3555 direction: SplitDirection,
3556 cx: &App,
3557 ) -> Option<Entity<Pane>> {
3558 self.center
3559 .find_pane_in_direction(&self.active_pane, direction, cx)
3560 .cloned()
3561 }
3562
3563 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
3564 if let Some(to) = self.find_pane_in_direction(direction, cx) {
3565 self.center.swap(&self.active_pane, &to);
3566 cx.notify();
3567 }
3568 }
3569
3570 pub fn resize_pane(
3571 &mut self,
3572 axis: gpui::Axis,
3573 amount: Pixels,
3574 window: &mut Window,
3575 cx: &mut Context<Self>,
3576 ) {
3577 let docks = self.all_docks();
3578 let active_dock = docks
3579 .into_iter()
3580 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3581
3582 if let Some(dock) = active_dock {
3583 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
3584 return;
3585 };
3586 match dock.read(cx).position() {
3587 DockPosition::Left => resize_left_dock(panel_size + amount, self, window, cx),
3588 DockPosition::Bottom => resize_bottom_dock(panel_size + amount, self, window, cx),
3589 DockPosition::Right => resize_right_dock(panel_size + amount, self, window, cx),
3590 }
3591 } else {
3592 self.center
3593 .resize(&self.active_pane, axis, amount, &self.bounds);
3594 }
3595 cx.notify();
3596 }
3597
3598 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
3599 self.center.reset_pane_sizes();
3600 cx.notify();
3601 }
3602
3603 fn handle_pane_focused(
3604 &mut self,
3605 pane: Entity<Pane>,
3606 window: &mut Window,
3607 cx: &mut Context<Self>,
3608 ) {
3609 // This is explicitly hoisted out of the following check for pane identity as
3610 // terminal panel panes are not registered as a center panes.
3611 self.status_bar.update(cx, |status_bar, cx| {
3612 status_bar.set_active_pane(&pane, window, cx);
3613 });
3614 if self.active_pane != pane {
3615 self.set_active_pane(&pane, window, cx);
3616 }
3617
3618 if self.last_active_center_pane.is_none() {
3619 self.last_active_center_pane = Some(pane.downgrade());
3620 }
3621
3622 self.dismiss_zoomed_items_to_reveal(None, window, cx);
3623 if pane.read(cx).is_zoomed() {
3624 self.zoomed = Some(pane.downgrade().into());
3625 } else {
3626 self.zoomed = None;
3627 }
3628 self.zoomed_position = None;
3629 cx.emit(Event::ZoomChanged);
3630 self.update_active_view_for_followers(window, cx);
3631 pane.update(cx, |pane, _| {
3632 pane.track_alternate_file_items();
3633 });
3634
3635 cx.notify();
3636 }
3637
3638 fn set_active_pane(
3639 &mut self,
3640 pane: &Entity<Pane>,
3641 window: &mut Window,
3642 cx: &mut Context<Self>,
3643 ) {
3644 self.active_pane = pane.clone();
3645 self.active_item_path_changed(window, cx);
3646 self.last_active_center_pane = Some(pane.downgrade());
3647 }
3648
3649 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3650 self.update_active_view_for_followers(window, cx);
3651 }
3652
3653 fn handle_pane_event(
3654 &mut self,
3655 pane: &Entity<Pane>,
3656 event: &pane::Event,
3657 window: &mut Window,
3658 cx: &mut Context<Self>,
3659 ) {
3660 let mut serialize_workspace = true;
3661 match event {
3662 pane::Event::AddItem { item } => {
3663 item.added_to_pane(self, pane.clone(), window, cx);
3664 cx.emit(Event::ItemAdded {
3665 item: item.boxed_clone(),
3666 });
3667 }
3668 pane::Event::Split(direction) => {
3669 self.split_and_clone(pane.clone(), *direction, window, cx);
3670 }
3671 pane::Event::JoinIntoNext => {
3672 self.join_pane_into_next(pane.clone(), window, cx);
3673 }
3674 pane::Event::JoinAll => {
3675 self.join_all_panes(window, cx);
3676 }
3677 pane::Event::Remove { focus_on_pane } => {
3678 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
3679 }
3680 pane::Event::ActivateItem {
3681 local,
3682 focus_changed,
3683 } => {
3684 cx.on_next_frame(window, |_, window, _| {
3685 window.invalidate_character_coordinates();
3686 });
3687
3688 pane.update(cx, |pane, _| {
3689 pane.track_alternate_file_items();
3690 });
3691 if *local {
3692 self.unfollow_in_pane(&pane, window, cx);
3693 }
3694 if pane == self.active_pane() {
3695 self.active_item_path_changed(window, cx);
3696 self.update_active_view_for_followers(window, cx);
3697 }
3698 serialize_workspace = *focus_changed || pane != self.active_pane();
3699 }
3700 pane::Event::UserSavedItem { item, save_intent } => {
3701 cx.emit(Event::UserSavedItem {
3702 pane: pane.downgrade(),
3703 item: item.boxed_clone(),
3704 save_intent: *save_intent,
3705 });
3706 serialize_workspace = false;
3707 }
3708 pane::Event::ChangeItemTitle => {
3709 if *pane == self.active_pane {
3710 self.active_item_path_changed(window, cx);
3711 }
3712 serialize_workspace = false;
3713 }
3714 pane::Event::RemoveItem { .. } => {}
3715 pane::Event::RemovedItem { item } => {
3716 cx.emit(Event::ActiveItemChanged);
3717 self.update_window_edited(window, cx);
3718 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id()) {
3719 if entry.get().entity_id() == pane.entity_id() {
3720 entry.remove();
3721 }
3722 }
3723 }
3724 pane::Event::Focus => {
3725 cx.on_next_frame(window, |_, window, _| {
3726 window.invalidate_character_coordinates();
3727 });
3728 self.handle_pane_focused(pane.clone(), window, cx);
3729 }
3730 pane::Event::ZoomIn => {
3731 if *pane == self.active_pane {
3732 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
3733 if pane.read(cx).has_focus(window, cx) {
3734 self.zoomed = Some(pane.downgrade().into());
3735 self.zoomed_position = None;
3736 cx.emit(Event::ZoomChanged);
3737 }
3738 cx.notify();
3739 }
3740 }
3741 pane::Event::ZoomOut => {
3742 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3743 if self.zoomed_position.is_none() {
3744 self.zoomed = None;
3745 cx.emit(Event::ZoomChanged);
3746 }
3747 cx.notify();
3748 }
3749 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
3750 }
3751
3752 if serialize_workspace {
3753 self.serialize_workspace(window, cx);
3754 }
3755 }
3756
3757 pub fn unfollow_in_pane(
3758 &mut self,
3759 pane: &Entity<Pane>,
3760 window: &mut Window,
3761 cx: &mut Context<Workspace>,
3762 ) -> Option<CollaboratorId> {
3763 let leader_id = self.leader_for_pane(pane)?;
3764 self.unfollow(leader_id, window, cx);
3765 Some(leader_id)
3766 }
3767
3768 pub fn split_pane(
3769 &mut self,
3770 pane_to_split: Entity<Pane>,
3771 split_direction: SplitDirection,
3772 window: &mut Window,
3773 cx: &mut Context<Self>,
3774 ) -> Entity<Pane> {
3775 let new_pane = self.add_pane(window, cx);
3776 self.center
3777 .split(&pane_to_split, &new_pane, split_direction)
3778 .unwrap();
3779 cx.notify();
3780 new_pane
3781 }
3782
3783 pub fn split_and_clone(
3784 &mut self,
3785 pane: Entity<Pane>,
3786 direction: SplitDirection,
3787 window: &mut Window,
3788 cx: &mut Context<Self>,
3789 ) -> Option<Entity<Pane>> {
3790 let item = pane.read(cx).active_item()?;
3791 let maybe_pane_handle =
3792 if let Some(clone) = item.clone_on_split(self.database_id(), window, cx) {
3793 let new_pane = self.add_pane(window, cx);
3794 new_pane.update(cx, |pane, cx| {
3795 pane.add_item(clone, true, true, None, window, cx)
3796 });
3797 self.center.split(&pane, &new_pane, direction).unwrap();
3798 Some(new_pane)
3799 } else {
3800 None
3801 };
3802 cx.notify();
3803 maybe_pane_handle
3804 }
3805
3806 pub fn split_pane_with_item(
3807 &mut self,
3808 pane_to_split: WeakEntity<Pane>,
3809 split_direction: SplitDirection,
3810 from: WeakEntity<Pane>,
3811 item_id_to_move: EntityId,
3812 window: &mut Window,
3813 cx: &mut Context<Self>,
3814 ) {
3815 let Some(pane_to_split) = pane_to_split.upgrade() else {
3816 return;
3817 };
3818 let Some(from) = from.upgrade() else {
3819 return;
3820 };
3821
3822 let new_pane = self.add_pane(window, cx);
3823 move_item(&from, &new_pane, item_id_to_move, 0, true, window, cx);
3824 self.center
3825 .split(&pane_to_split, &new_pane, split_direction)
3826 .unwrap();
3827 cx.notify();
3828 }
3829
3830 pub fn split_pane_with_project_entry(
3831 &mut self,
3832 pane_to_split: WeakEntity<Pane>,
3833 split_direction: SplitDirection,
3834 project_entry: ProjectEntryId,
3835 window: &mut Window,
3836 cx: &mut Context<Self>,
3837 ) -> Option<Task<Result<()>>> {
3838 let pane_to_split = pane_to_split.upgrade()?;
3839 let new_pane = self.add_pane(window, cx);
3840 self.center
3841 .split(&pane_to_split, &new_pane, split_direction)
3842 .unwrap();
3843
3844 let path = self.project.read(cx).path_for_entry(project_entry, cx)?;
3845 let task = self.open_path(path, Some(new_pane.downgrade()), true, window, cx);
3846 Some(cx.foreground_executor().spawn(async move {
3847 task.await?;
3848 Ok(())
3849 }))
3850 }
3851
3852 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3853 let active_item = self.active_pane.read(cx).active_item();
3854 for pane in &self.panes {
3855 join_pane_into_active(&self.active_pane, pane, window, cx);
3856 }
3857 if let Some(active_item) = active_item {
3858 self.activate_item(active_item.as_ref(), true, true, window, cx);
3859 }
3860 cx.notify();
3861 }
3862
3863 pub fn join_pane_into_next(
3864 &mut self,
3865 pane: Entity<Pane>,
3866 window: &mut Window,
3867 cx: &mut Context<Self>,
3868 ) {
3869 let next_pane = self
3870 .find_pane_in_direction(SplitDirection::Right, cx)
3871 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
3872 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
3873 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
3874 let Some(next_pane) = next_pane else {
3875 return;
3876 };
3877 move_all_items(&pane, &next_pane, window, cx);
3878 cx.notify();
3879 }
3880
3881 fn remove_pane(
3882 &mut self,
3883 pane: Entity<Pane>,
3884 focus_on: Option<Entity<Pane>>,
3885 window: &mut Window,
3886 cx: &mut Context<Self>,
3887 ) {
3888 if self.center.remove(&pane).unwrap() {
3889 self.force_remove_pane(&pane, &focus_on, window, cx);
3890 self.unfollow_in_pane(&pane, window, cx);
3891 self.last_leaders_by_pane.remove(&pane.downgrade());
3892 for removed_item in pane.read(cx).items() {
3893 self.panes_by_item.remove(&removed_item.item_id());
3894 }
3895
3896 cx.notify();
3897 } else {
3898 self.active_item_path_changed(window, cx);
3899 }
3900 cx.emit(Event::PaneRemoved);
3901 }
3902
3903 pub fn panes(&self) -> &[Entity<Pane>] {
3904 &self.panes
3905 }
3906
3907 pub fn active_pane(&self) -> &Entity<Pane> {
3908 &self.active_pane
3909 }
3910
3911 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
3912 for dock in self.all_docks() {
3913 if dock.focus_handle(cx).contains_focused(window, cx) {
3914 if let Some(pane) = dock
3915 .read(cx)
3916 .active_panel()
3917 .and_then(|panel| panel.pane(cx))
3918 {
3919 return pane;
3920 }
3921 }
3922 }
3923 self.active_pane().clone()
3924 }
3925
3926 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
3927 self.find_pane_in_direction(SplitDirection::Right, cx)
3928 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
3929 .unwrap_or_else(|| {
3930 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
3931 })
3932 .clone()
3933 }
3934
3935 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
3936 let weak_pane = self.panes_by_item.get(&handle.item_id())?;
3937 weak_pane.upgrade()
3938 }
3939
3940 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
3941 self.follower_states.retain(|leader_id, state| {
3942 if *leader_id == CollaboratorId::PeerId(peer_id) {
3943 for item in state.items_by_leader_view_id.values() {
3944 item.view.set_leader_id(None, window, cx);
3945 }
3946 false
3947 } else {
3948 true
3949 }
3950 });
3951 cx.notify();
3952 }
3953
3954 pub fn start_following(
3955 &mut self,
3956 leader_id: impl Into<CollaboratorId>,
3957 window: &mut Window,
3958 cx: &mut Context<Self>,
3959 ) -> Option<Task<Result<()>>> {
3960 let leader_id = leader_id.into();
3961 let pane = self.active_pane().clone();
3962
3963 self.last_leaders_by_pane
3964 .insert(pane.downgrade(), leader_id);
3965 self.unfollow(leader_id, window, cx);
3966 self.unfollow_in_pane(&pane, window, cx);
3967 self.follower_states.insert(
3968 leader_id,
3969 FollowerState {
3970 center_pane: pane.clone(),
3971 dock_pane: None,
3972 active_view_id: None,
3973 items_by_leader_view_id: Default::default(),
3974 },
3975 );
3976 cx.notify();
3977
3978 match leader_id {
3979 CollaboratorId::PeerId(leader_peer_id) => {
3980 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
3981 let project_id = self.project.read(cx).remote_id();
3982 let request = self.app_state.client.request(proto::Follow {
3983 room_id,
3984 project_id,
3985 leader_id: Some(leader_peer_id),
3986 });
3987
3988 Some(cx.spawn_in(window, async move |this, cx| {
3989 let response = request.await?;
3990 this.update(cx, |this, _| {
3991 let state = this
3992 .follower_states
3993 .get_mut(&leader_id)
3994 .context("following interrupted")?;
3995 state.active_view_id = response
3996 .active_view
3997 .as_ref()
3998 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
3999 anyhow::Ok(())
4000 })??;
4001 if let Some(view) = response.active_view {
4002 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
4003 }
4004 this.update_in(cx, |this, window, cx| {
4005 this.leader_updated(leader_id, window, cx)
4006 })?;
4007 Ok(())
4008 }))
4009 }
4010 CollaboratorId::Agent => {
4011 self.leader_updated(leader_id, window, cx)?;
4012 Some(Task::ready(Ok(())))
4013 }
4014 }
4015 }
4016
4017 pub fn follow_next_collaborator(
4018 &mut self,
4019 _: &FollowNextCollaborator,
4020 window: &mut Window,
4021 cx: &mut Context<Self>,
4022 ) {
4023 let collaborators = self.project.read(cx).collaborators();
4024 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
4025 let mut collaborators = collaborators.keys().copied();
4026 for peer_id in collaborators.by_ref() {
4027 if CollaboratorId::PeerId(peer_id) == leader_id {
4028 break;
4029 }
4030 }
4031 collaborators.next().map(CollaboratorId::PeerId)
4032 } else if let Some(last_leader_id) =
4033 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
4034 {
4035 match last_leader_id {
4036 CollaboratorId::PeerId(peer_id) => {
4037 if collaborators.contains_key(peer_id) {
4038 Some(*last_leader_id)
4039 } else {
4040 None
4041 }
4042 }
4043 CollaboratorId::Agent => Some(CollaboratorId::Agent),
4044 }
4045 } else {
4046 None
4047 };
4048
4049 let pane = self.active_pane.clone();
4050 let Some(leader_id) = next_leader_id.or_else(|| {
4051 Some(CollaboratorId::PeerId(
4052 collaborators.keys().copied().next()?,
4053 ))
4054 }) else {
4055 return;
4056 };
4057 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
4058 return;
4059 }
4060 if let Some(task) = self.start_following(leader_id, window, cx) {
4061 task.detach_and_log_err(cx)
4062 }
4063 }
4064
4065 pub fn follow(
4066 &mut self,
4067 leader_id: impl Into<CollaboratorId>,
4068 window: &mut Window,
4069 cx: &mut Context<Self>,
4070 ) {
4071 let leader_id = leader_id.into();
4072
4073 if let CollaboratorId::PeerId(peer_id) = leader_id {
4074 let Some(room) = ActiveCall::global(cx).read(cx).room() else {
4075 return;
4076 };
4077 let room = room.read(cx);
4078 let Some(remote_participant) = room.remote_participant_for_peer_id(peer_id) else {
4079 return;
4080 };
4081
4082 let project = self.project.read(cx);
4083
4084 let other_project_id = match remote_participant.location {
4085 call::ParticipantLocation::External => None,
4086 call::ParticipantLocation::UnsharedProject => None,
4087 call::ParticipantLocation::SharedProject { project_id } => {
4088 if Some(project_id) == project.remote_id() {
4089 None
4090 } else {
4091 Some(project_id)
4092 }
4093 }
4094 };
4095
4096 // if they are active in another project, follow there.
4097 if let Some(project_id) = other_project_id {
4098 let app_state = self.app_state.clone();
4099 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
4100 .detach_and_log_err(cx);
4101 }
4102 }
4103
4104 // if you're already following, find the right pane and focus it.
4105 if let Some(follower_state) = self.follower_states.get(&leader_id) {
4106 window.focus(&follower_state.pane().focus_handle(cx));
4107
4108 return;
4109 }
4110
4111 // Otherwise, follow.
4112 if let Some(task) = self.start_following(leader_id, window, cx) {
4113 task.detach_and_log_err(cx)
4114 }
4115 }
4116
4117 pub fn unfollow(
4118 &mut self,
4119 leader_id: impl Into<CollaboratorId>,
4120 window: &mut Window,
4121 cx: &mut Context<Self>,
4122 ) -> Option<()> {
4123 cx.notify();
4124
4125 let leader_id = leader_id.into();
4126 let state = self.follower_states.remove(&leader_id)?;
4127 for (_, item) in state.items_by_leader_view_id {
4128 item.view.set_leader_id(None, window, cx);
4129 }
4130
4131 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
4132 let project_id = self.project.read(cx).remote_id();
4133 let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
4134 self.app_state
4135 .client
4136 .send(proto::Unfollow {
4137 room_id,
4138 project_id,
4139 leader_id: Some(leader_peer_id),
4140 })
4141 .log_err();
4142 }
4143
4144 Some(())
4145 }
4146
4147 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
4148 self.follower_states.contains_key(&id.into())
4149 }
4150
4151 fn active_item_path_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4152 cx.emit(Event::ActiveItemChanged);
4153 let active_entry = self.active_project_path(cx);
4154 self.project
4155 .update(cx, |project, cx| project.set_active_path(active_entry, cx));
4156
4157 self.update_window_title(window, cx);
4158 }
4159
4160 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
4161 let project = self.project().read(cx);
4162 let mut title = String::new();
4163
4164 for (i, name) in project.worktree_root_names(cx).enumerate() {
4165 if i > 0 {
4166 title.push_str(", ");
4167 }
4168 title.push_str(name);
4169 }
4170
4171 if title.is_empty() {
4172 title = "empty project".to_string();
4173 }
4174
4175 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
4176 let filename = path
4177 .path
4178 .file_name()
4179 .map(|s| s.to_string_lossy())
4180 .or_else(|| {
4181 Some(Cow::Borrowed(
4182 project
4183 .worktree_for_id(path.worktree_id, cx)?
4184 .read(cx)
4185 .root_name(),
4186 ))
4187 });
4188
4189 if let Some(filename) = filename {
4190 title.push_str(" — ");
4191 title.push_str(filename.as_ref());
4192 }
4193 }
4194
4195 if project.is_via_collab() {
4196 title.push_str(" ↙");
4197 } else if project.is_shared() {
4198 title.push_str(" ↗");
4199 }
4200
4201 window.set_window_title(&title);
4202 }
4203
4204 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
4205 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
4206 if is_edited != self.window_edited {
4207 self.window_edited = is_edited;
4208 window.set_window_edited(self.window_edited)
4209 }
4210 }
4211
4212 fn update_item_dirty_state(
4213 &mut self,
4214 item: &dyn ItemHandle,
4215 window: &mut Window,
4216 cx: &mut App,
4217 ) {
4218 let is_dirty = item.is_dirty(cx);
4219 let item_id = item.item_id();
4220 let was_dirty = self.dirty_items.contains_key(&item_id);
4221 if is_dirty == was_dirty {
4222 return;
4223 }
4224 if was_dirty {
4225 self.dirty_items.remove(&item_id);
4226 self.update_window_edited(window, cx);
4227 return;
4228 }
4229 if let Some(window_handle) = window.window_handle().downcast::<Self>() {
4230 let s = item.on_release(
4231 cx,
4232 Box::new(move |cx| {
4233 window_handle
4234 .update(cx, |this, window, cx| {
4235 this.dirty_items.remove(&item_id);
4236 this.update_window_edited(window, cx)
4237 })
4238 .ok();
4239 }),
4240 );
4241 self.dirty_items.insert(item_id, s);
4242 self.update_window_edited(window, cx);
4243 }
4244 }
4245
4246 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
4247 if self.notifications.is_empty() {
4248 None
4249 } else {
4250 Some(
4251 div()
4252 .absolute()
4253 .right_3()
4254 .bottom_3()
4255 .w_112()
4256 .h_full()
4257 .flex()
4258 .flex_col()
4259 .justify_end()
4260 .gap_2()
4261 .children(
4262 self.notifications
4263 .iter()
4264 .map(|(_, notification)| notification.clone().into_any()),
4265 ),
4266 )
4267 }
4268 }
4269
4270 // RPC handlers
4271
4272 fn active_view_for_follower(
4273 &self,
4274 follower_project_id: Option<u64>,
4275 window: &mut Window,
4276 cx: &mut Context<Self>,
4277 ) -> Option<proto::View> {
4278 let (item, panel_id) = self.active_item_for_followers(window, cx);
4279 let item = item?;
4280 let leader_id = self
4281 .pane_for(&*item)
4282 .and_then(|pane| self.leader_for_pane(&pane));
4283 let leader_peer_id = match leader_id {
4284 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
4285 Some(CollaboratorId::Agent) | None => None,
4286 };
4287
4288 let item_handle = item.to_followable_item_handle(cx)?;
4289 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
4290 let variant = item_handle.to_state_proto(window, cx)?;
4291
4292 if item_handle.is_project_item(window, cx)
4293 && (follower_project_id.is_none()
4294 || follower_project_id != self.project.read(cx).remote_id())
4295 {
4296 return None;
4297 }
4298
4299 Some(proto::View {
4300 id: id.to_proto(),
4301 leader_id: leader_peer_id,
4302 variant: Some(variant),
4303 panel_id: panel_id.map(|id| id as i32),
4304 })
4305 }
4306
4307 fn handle_follow(
4308 &mut self,
4309 follower_project_id: Option<u64>,
4310 window: &mut Window,
4311 cx: &mut Context<Self>,
4312 ) -> proto::FollowResponse {
4313 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
4314
4315 cx.notify();
4316 proto::FollowResponse {
4317 // TODO: Remove after version 0.145.x stabilizes.
4318 active_view_id: active_view.as_ref().and_then(|view| view.id.clone()),
4319 views: active_view.iter().cloned().collect(),
4320 active_view,
4321 }
4322 }
4323
4324 fn handle_update_followers(
4325 &mut self,
4326 leader_id: PeerId,
4327 message: proto::UpdateFollowers,
4328 _window: &mut Window,
4329 _cx: &mut Context<Self>,
4330 ) {
4331 self.leader_updates_tx
4332 .unbounded_send((leader_id, message))
4333 .ok();
4334 }
4335
4336 async fn process_leader_update(
4337 this: &WeakEntity<Self>,
4338 leader_id: PeerId,
4339 update: proto::UpdateFollowers,
4340 cx: &mut AsyncWindowContext,
4341 ) -> Result<()> {
4342 match update.variant.context("invalid update")? {
4343 proto::update_followers::Variant::CreateView(view) => {
4344 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
4345 let should_add_view = this.update(cx, |this, _| {
4346 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
4347 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
4348 } else {
4349 anyhow::Ok(false)
4350 }
4351 })??;
4352
4353 if should_add_view {
4354 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
4355 }
4356 }
4357 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
4358 let should_add_view = this.update(cx, |this, _| {
4359 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
4360 state.active_view_id = update_active_view
4361 .view
4362 .as_ref()
4363 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
4364
4365 if state.active_view_id.is_some_and(|view_id| {
4366 !state.items_by_leader_view_id.contains_key(&view_id)
4367 }) {
4368 anyhow::Ok(true)
4369 } else {
4370 anyhow::Ok(false)
4371 }
4372 } else {
4373 anyhow::Ok(false)
4374 }
4375 })??;
4376
4377 if should_add_view {
4378 if let Some(view) = update_active_view.view {
4379 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
4380 }
4381 }
4382 }
4383 proto::update_followers::Variant::UpdateView(update_view) => {
4384 let variant = update_view.variant.context("missing update view variant")?;
4385 let id = update_view.id.context("missing update view id")?;
4386 let mut tasks = Vec::new();
4387 this.update_in(cx, |this, window, cx| {
4388 let project = this.project.clone();
4389 if let Some(state) = this.follower_states.get(&leader_id.into()) {
4390 let view_id = ViewId::from_proto(id.clone())?;
4391 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
4392 tasks.push(item.view.apply_update_proto(
4393 &project,
4394 variant.clone(),
4395 window,
4396 cx,
4397 ));
4398 }
4399 }
4400 anyhow::Ok(())
4401 })??;
4402 try_join_all(tasks).await.log_err();
4403 }
4404 }
4405 this.update_in(cx, |this, window, cx| {
4406 this.leader_updated(leader_id, window, cx)
4407 })?;
4408 Ok(())
4409 }
4410
4411 async fn add_view_from_leader(
4412 this: WeakEntity<Self>,
4413 leader_id: PeerId,
4414 view: &proto::View,
4415 cx: &mut AsyncWindowContext,
4416 ) -> Result<()> {
4417 let this = this.upgrade().context("workspace dropped")?;
4418
4419 let Some(id) = view.id.clone() else {
4420 anyhow::bail!("no id for view");
4421 };
4422 let id = ViewId::from_proto(id)?;
4423 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
4424
4425 let pane = this.update(cx, |this, _cx| {
4426 let state = this
4427 .follower_states
4428 .get(&leader_id.into())
4429 .context("stopped following")?;
4430 anyhow::Ok(state.pane().clone())
4431 })??;
4432 let existing_item = pane.update_in(cx, |pane, window, cx| {
4433 let client = this.read(cx).client().clone();
4434 pane.items().find_map(|item| {
4435 let item = item.to_followable_item_handle(cx)?;
4436 if item.remote_id(&client, window, cx) == Some(id) {
4437 Some(item)
4438 } else {
4439 None
4440 }
4441 })
4442 })?;
4443 let item = if let Some(existing_item) = existing_item {
4444 existing_item
4445 } else {
4446 let variant = view.variant.clone();
4447 anyhow::ensure!(variant.is_some(), "missing view variant");
4448
4449 let task = cx.update(|window, cx| {
4450 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
4451 })?;
4452
4453 let Some(task) = task else {
4454 anyhow::bail!(
4455 "failed to construct view from leader (maybe from a different version of zed?)"
4456 );
4457 };
4458
4459 let mut new_item = task.await?;
4460 pane.update_in(cx, |pane, window, cx| {
4461 let mut item_to_remove = None;
4462 for (ix, item) in pane.items().enumerate() {
4463 if let Some(item) = item.to_followable_item_handle(cx) {
4464 match new_item.dedup(item.as_ref(), window, cx) {
4465 Some(item::Dedup::KeepExisting) => {
4466 new_item =
4467 item.boxed_clone().to_followable_item_handle(cx).unwrap();
4468 break;
4469 }
4470 Some(item::Dedup::ReplaceExisting) => {
4471 item_to_remove = Some((ix, item.item_id()));
4472 break;
4473 }
4474 None => {}
4475 }
4476 }
4477 }
4478
4479 if let Some((ix, id)) = item_to_remove {
4480 pane.remove_item(id, false, false, window, cx);
4481 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
4482 }
4483 })?;
4484
4485 new_item
4486 };
4487
4488 this.update_in(cx, |this, window, cx| {
4489 let state = this.follower_states.get_mut(&leader_id.into())?;
4490 item.set_leader_id(Some(leader_id.into()), window, cx);
4491 state.items_by_leader_view_id.insert(
4492 id,
4493 FollowerView {
4494 view: item,
4495 location: panel_id,
4496 },
4497 );
4498
4499 Some(())
4500 })?;
4501
4502 Ok(())
4503 }
4504
4505 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4506 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
4507 return;
4508 };
4509
4510 if let Some(agent_location) = self.project.read(cx).agent_location() {
4511 let buffer_entity_id = agent_location.buffer.entity_id();
4512 let view_id = ViewId {
4513 creator: CollaboratorId::Agent,
4514 id: buffer_entity_id.as_u64(),
4515 };
4516 follower_state.active_view_id = Some(view_id);
4517
4518 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
4519 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
4520 hash_map::Entry::Vacant(entry) => {
4521 let existing_view =
4522 follower_state
4523 .center_pane
4524 .read(cx)
4525 .items()
4526 .find_map(|item| {
4527 let item = item.to_followable_item_handle(cx)?;
4528 if item.is_singleton(cx)
4529 && item.project_item_model_ids(cx).as_slice()
4530 == [buffer_entity_id]
4531 {
4532 Some(item)
4533 } else {
4534 None
4535 }
4536 });
4537 let view = existing_view.or_else(|| {
4538 agent_location.buffer.upgrade().and_then(|buffer| {
4539 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
4540 registry.build_item(buffer, self.project.clone(), None, window, cx)
4541 })?
4542 .to_followable_item_handle(cx)
4543 })
4544 });
4545
4546 if let Some(view) = view {
4547 Some(entry.insert(FollowerView {
4548 view,
4549 location: None,
4550 }))
4551 } else {
4552 None
4553 }
4554 }
4555 };
4556
4557 if let Some(item) = item {
4558 item.view
4559 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
4560 item.view
4561 .update_agent_location(agent_location.position, window, cx);
4562 }
4563 } else {
4564 follower_state.active_view_id = None;
4565 }
4566
4567 self.leader_updated(CollaboratorId::Agent, window, cx);
4568 }
4569
4570 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
4571 let mut is_project_item = true;
4572 let mut update = proto::UpdateActiveView::default();
4573 if window.is_window_active() {
4574 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
4575
4576 if let Some(item) = active_item {
4577 if item.item_focus_handle(cx).contains_focused(window, cx) {
4578 let leader_id = self
4579 .pane_for(&*item)
4580 .and_then(|pane| self.leader_for_pane(&pane));
4581 let leader_peer_id = match leader_id {
4582 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
4583 Some(CollaboratorId::Agent) | None => None,
4584 };
4585
4586 if let Some(item) = item.to_followable_item_handle(cx) {
4587 let id = item
4588 .remote_id(&self.app_state.client, window, cx)
4589 .map(|id| id.to_proto());
4590
4591 if let Some(id) = id.clone() {
4592 if let Some(variant) = item.to_state_proto(window, cx) {
4593 let view = Some(proto::View {
4594 id: id.clone(),
4595 leader_id: leader_peer_id,
4596 variant: Some(variant),
4597 panel_id: panel_id.map(|id| id as i32),
4598 });
4599
4600 is_project_item = item.is_project_item(window, cx);
4601 update = proto::UpdateActiveView {
4602 view,
4603 // TODO: Remove after version 0.145.x stabilizes.
4604 id: id.clone(),
4605 leader_id: leader_peer_id,
4606 };
4607 }
4608 };
4609 }
4610 }
4611 }
4612 }
4613
4614 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
4615 if active_view_id != self.last_active_view_id.as_ref() {
4616 self.last_active_view_id = active_view_id.cloned();
4617 self.update_followers(
4618 is_project_item,
4619 proto::update_followers::Variant::UpdateActiveView(update),
4620 window,
4621 cx,
4622 );
4623 }
4624 }
4625
4626 fn active_item_for_followers(
4627 &self,
4628 window: &mut Window,
4629 cx: &mut App,
4630 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
4631 let mut active_item = None;
4632 let mut panel_id = None;
4633 for dock in self.all_docks() {
4634 if dock.focus_handle(cx).contains_focused(window, cx) {
4635 if let Some(panel) = dock.read(cx).active_panel() {
4636 if let Some(pane) = panel.pane(cx) {
4637 if let Some(item) = pane.read(cx).active_item() {
4638 active_item = Some(item);
4639 panel_id = panel.remote_id();
4640 break;
4641 }
4642 }
4643 }
4644 }
4645 }
4646
4647 if active_item.is_none() {
4648 active_item = self.active_pane().read(cx).active_item();
4649 }
4650 (active_item, panel_id)
4651 }
4652
4653 fn update_followers(
4654 &self,
4655 project_only: bool,
4656 update: proto::update_followers::Variant,
4657 _: &mut Window,
4658 cx: &mut App,
4659 ) -> Option<()> {
4660 // If this update only applies to for followers in the current project,
4661 // then skip it unless this project is shared. If it applies to all
4662 // followers, regardless of project, then set `project_id` to none,
4663 // indicating that it goes to all followers.
4664 let project_id = if project_only {
4665 Some(self.project.read(cx).remote_id()?)
4666 } else {
4667 None
4668 };
4669 self.app_state().workspace_store.update(cx, |store, cx| {
4670 store.update_followers(project_id, update, cx)
4671 })
4672 }
4673
4674 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
4675 self.follower_states.iter().find_map(|(leader_id, state)| {
4676 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
4677 Some(*leader_id)
4678 } else {
4679 None
4680 }
4681 })
4682 }
4683
4684 fn leader_updated(
4685 &mut self,
4686 leader_id: impl Into<CollaboratorId>,
4687 window: &mut Window,
4688 cx: &mut Context<Self>,
4689 ) -> Option<Box<dyn ItemHandle>> {
4690 cx.notify();
4691
4692 let leader_id = leader_id.into();
4693 let (panel_id, item) = match leader_id {
4694 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
4695 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
4696 };
4697
4698 let state = self.follower_states.get(&leader_id)?;
4699 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
4700 let pane;
4701 if let Some(panel_id) = panel_id {
4702 pane = self
4703 .activate_panel_for_proto_id(panel_id, window, cx)?
4704 .pane(cx)?;
4705 let state = self.follower_states.get_mut(&leader_id)?;
4706 state.dock_pane = Some(pane.clone());
4707 } else {
4708 pane = state.center_pane.clone();
4709 let state = self.follower_states.get_mut(&leader_id)?;
4710 if let Some(dock_pane) = state.dock_pane.take() {
4711 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
4712 }
4713 }
4714
4715 pane.update(cx, |pane, cx| {
4716 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
4717 if let Some(index) = pane.index_for_item(item.as_ref()) {
4718 pane.activate_item(index, false, false, window, cx);
4719 } else {
4720 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
4721 }
4722
4723 if focus_active_item {
4724 pane.focus_active_item(window, cx)
4725 }
4726 });
4727
4728 Some(item)
4729 }
4730
4731 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
4732 let state = self.follower_states.get(&CollaboratorId::Agent)?;
4733 let active_view_id = state.active_view_id?;
4734 Some(
4735 state
4736 .items_by_leader_view_id
4737 .get(&active_view_id)?
4738 .view
4739 .boxed_clone(),
4740 )
4741 }
4742
4743 fn active_item_for_peer(
4744 &self,
4745 peer_id: PeerId,
4746 window: &mut Window,
4747 cx: &mut Context<Self>,
4748 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
4749 let call = self.active_call()?;
4750 let room = call.read(cx).room()?.read(cx);
4751 let participant = room.remote_participant_for_peer_id(peer_id)?;
4752 let leader_in_this_app;
4753 let leader_in_this_project;
4754 match participant.location {
4755 call::ParticipantLocation::SharedProject { project_id } => {
4756 leader_in_this_app = true;
4757 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
4758 }
4759 call::ParticipantLocation::UnsharedProject => {
4760 leader_in_this_app = true;
4761 leader_in_this_project = false;
4762 }
4763 call::ParticipantLocation::External => {
4764 leader_in_this_app = false;
4765 leader_in_this_project = false;
4766 }
4767 };
4768 let state = self.follower_states.get(&peer_id.into())?;
4769 let mut item_to_activate = None;
4770 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
4771 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id) {
4772 if leader_in_this_project || !item.view.is_project_item(window, cx) {
4773 item_to_activate = Some((item.location, item.view.boxed_clone()));
4774 }
4775 }
4776 } else if let Some(shared_screen) =
4777 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
4778 {
4779 item_to_activate = Some((None, Box::new(shared_screen)));
4780 }
4781 item_to_activate
4782 }
4783
4784 fn shared_screen_for_peer(
4785 &self,
4786 peer_id: PeerId,
4787 pane: &Entity<Pane>,
4788 window: &mut Window,
4789 cx: &mut App,
4790 ) -> Option<Entity<SharedScreen>> {
4791 let call = self.active_call()?;
4792 let room = call.read(cx).room()?.clone();
4793 let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
4794 let track = participant.video_tracks.values().next()?.clone();
4795 let user = participant.user.clone();
4796
4797 for item in pane.read(cx).items_of_type::<SharedScreen>() {
4798 if item.read(cx).peer_id == peer_id {
4799 return Some(item);
4800 }
4801 }
4802
4803 Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
4804 }
4805
4806 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4807 if window.is_window_active() {
4808 self.update_active_view_for_followers(window, cx);
4809
4810 if let Some(database_id) = self.database_id {
4811 cx.background_spawn(persistence::DB.update_timestamp(database_id))
4812 .detach();
4813 }
4814 } else {
4815 for pane in &self.panes {
4816 pane.update(cx, |pane, cx| {
4817 if let Some(item) = pane.active_item() {
4818 item.workspace_deactivated(window, cx);
4819 }
4820 for item in pane.items() {
4821 if matches!(
4822 item.workspace_settings(cx).autosave,
4823 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
4824 ) {
4825 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
4826 .detach_and_log_err(cx);
4827 }
4828 }
4829 });
4830 }
4831 }
4832 }
4833
4834 pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
4835 self.active_call.as_ref().map(|(call, _)| call)
4836 }
4837
4838 fn on_active_call_event(
4839 &mut self,
4840 _: &Entity<ActiveCall>,
4841 event: &call::room::Event,
4842 window: &mut Window,
4843 cx: &mut Context<Self>,
4844 ) {
4845 match event {
4846 call::room::Event::ParticipantLocationChanged { participant_id }
4847 | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
4848 self.leader_updated(participant_id, window, cx);
4849 }
4850 _ => {}
4851 }
4852 }
4853
4854 pub fn database_id(&self) -> Option<WorkspaceId> {
4855 self.database_id
4856 }
4857
4858 pub fn session_id(&self) -> Option<String> {
4859 self.session_id.clone()
4860 }
4861
4862 fn local_paths(&self, cx: &App) -> Option<Vec<Arc<Path>>> {
4863 let project = self.project().read(cx);
4864
4865 if project.is_local() {
4866 Some(
4867 project
4868 .visible_worktrees(cx)
4869 .map(|worktree| worktree.read(cx).abs_path())
4870 .collect::<Vec<_>>(),
4871 )
4872 } else {
4873 None
4874 }
4875 }
4876
4877 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
4878 match member {
4879 Member::Axis(PaneAxis { members, .. }) => {
4880 for child in members.iter() {
4881 self.remove_panes(child.clone(), window, cx)
4882 }
4883 }
4884 Member::Pane(pane) => {
4885 self.force_remove_pane(&pane, &None, window, cx);
4886 }
4887 }
4888 }
4889
4890 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
4891 self.session_id.take();
4892 self.serialize_workspace_internal(window, cx)
4893 }
4894
4895 fn force_remove_pane(
4896 &mut self,
4897 pane: &Entity<Pane>,
4898 focus_on: &Option<Entity<Pane>>,
4899 window: &mut Window,
4900 cx: &mut Context<Workspace>,
4901 ) {
4902 self.panes.retain(|p| p != pane);
4903 if let Some(focus_on) = focus_on {
4904 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
4905 } else {
4906 if self.active_pane() == pane {
4907 self.panes
4908 .last()
4909 .unwrap()
4910 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
4911 }
4912 }
4913 if self.last_active_center_pane == Some(pane.downgrade()) {
4914 self.last_active_center_pane = None;
4915 }
4916 cx.notify();
4917 }
4918
4919 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4920 if self._schedule_serialize.is_none() {
4921 self._schedule_serialize = Some(cx.spawn_in(window, async move |this, cx| {
4922 cx.background_executor()
4923 .timer(Duration::from_millis(100))
4924 .await;
4925 this.update_in(cx, |this, window, cx| {
4926 this.serialize_workspace_internal(window, cx).detach();
4927 this._schedule_serialize.take();
4928 })
4929 .log_err();
4930 }));
4931 }
4932 }
4933
4934 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
4935 let Some(database_id) = self.database_id() else {
4936 return Task::ready(());
4937 };
4938
4939 fn serialize_pane_handle(
4940 pane_handle: &Entity<Pane>,
4941 window: &mut Window,
4942 cx: &mut App,
4943 ) -> SerializedPane {
4944 let (items, active, pinned_count) = {
4945 let pane = pane_handle.read(cx);
4946 let active_item_id = pane.active_item().map(|item| item.item_id());
4947 (
4948 pane.items()
4949 .filter_map(|handle| {
4950 let handle = handle.to_serializable_item_handle(cx)?;
4951
4952 Some(SerializedItem {
4953 kind: Arc::from(handle.serialized_item_kind()),
4954 item_id: handle.item_id().as_u64(),
4955 active: Some(handle.item_id()) == active_item_id,
4956 preview: pane.is_active_preview_item(handle.item_id()),
4957 })
4958 })
4959 .collect::<Vec<_>>(),
4960 pane.has_focus(window, cx),
4961 pane.pinned_count(),
4962 )
4963 };
4964
4965 SerializedPane::new(items, active, pinned_count)
4966 }
4967
4968 fn build_serialized_pane_group(
4969 pane_group: &Member,
4970 window: &mut Window,
4971 cx: &mut App,
4972 ) -> SerializedPaneGroup {
4973 match pane_group {
4974 Member::Axis(PaneAxis {
4975 axis,
4976 members,
4977 flexes,
4978 bounding_boxes: _,
4979 }) => SerializedPaneGroup::Group {
4980 axis: SerializedAxis(*axis),
4981 children: members
4982 .iter()
4983 .map(|member| build_serialized_pane_group(member, window, cx))
4984 .collect::<Vec<_>>(),
4985 flexes: Some(flexes.lock().clone()),
4986 },
4987 Member::Pane(pane_handle) => {
4988 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
4989 }
4990 }
4991 }
4992
4993 fn build_serialized_docks(
4994 this: &Workspace,
4995 window: &mut Window,
4996 cx: &mut App,
4997 ) -> DockStructure {
4998 let left_dock = this.left_dock.read(cx);
4999 let left_visible = left_dock.is_open();
5000 let left_active_panel = left_dock
5001 .active_panel()
5002 .map(|panel| panel.persistent_name().to_string());
5003 let left_dock_zoom = left_dock
5004 .active_panel()
5005 .map(|panel| panel.is_zoomed(window, cx))
5006 .unwrap_or(false);
5007
5008 let right_dock = this.right_dock.read(cx);
5009 let right_visible = right_dock.is_open();
5010 let right_active_panel = right_dock
5011 .active_panel()
5012 .map(|panel| panel.persistent_name().to_string());
5013 let right_dock_zoom = right_dock
5014 .active_panel()
5015 .map(|panel| panel.is_zoomed(window, cx))
5016 .unwrap_or(false);
5017
5018 let bottom_dock = this.bottom_dock.read(cx);
5019 let bottom_visible = bottom_dock.is_open();
5020 let bottom_active_panel = bottom_dock
5021 .active_panel()
5022 .map(|panel| panel.persistent_name().to_string());
5023 let bottom_dock_zoom = bottom_dock
5024 .active_panel()
5025 .map(|panel| panel.is_zoomed(window, cx))
5026 .unwrap_or(false);
5027
5028 DockStructure {
5029 left: DockData {
5030 visible: left_visible,
5031 active_panel: left_active_panel,
5032 zoom: left_dock_zoom,
5033 },
5034 right: DockData {
5035 visible: right_visible,
5036 active_panel: right_active_panel,
5037 zoom: right_dock_zoom,
5038 },
5039 bottom: DockData {
5040 visible: bottom_visible,
5041 active_panel: bottom_active_panel,
5042 zoom: bottom_dock_zoom,
5043 },
5044 }
5045 }
5046
5047 if let Some(location) = self.serialize_workspace_location(cx) {
5048 let breakpoints = self.project.update(cx, |project, cx| {
5049 project
5050 .breakpoint_store()
5051 .read(cx)
5052 .all_source_breakpoints(cx)
5053 });
5054
5055 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
5056 let docks = build_serialized_docks(self, window, cx);
5057 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
5058 let serialized_workspace = SerializedWorkspace {
5059 id: database_id,
5060 location,
5061 center_group,
5062 window_bounds,
5063 display: Default::default(),
5064 docks,
5065 centered_layout: self.centered_layout,
5066 session_id: self.session_id.clone(),
5067 breakpoints,
5068 window_id: Some(window.window_handle().window_id().as_u64()),
5069 };
5070
5071 return window.spawn(cx, async move |_| {
5072 persistence::DB.save_workspace(serialized_workspace).await;
5073 });
5074 }
5075 Task::ready(())
5076 }
5077
5078 fn serialize_workspace_location(&self, cx: &App) -> Option<SerializedWorkspaceLocation> {
5079 if let Some(ssh_project) = &self.serialized_ssh_project {
5080 Some(SerializedWorkspaceLocation::Ssh(ssh_project.clone()))
5081 } else if let Some(local_paths) = self.local_paths(cx) {
5082 if !local_paths.is_empty() {
5083 Some(SerializedWorkspaceLocation::from_local_paths(local_paths))
5084 } else {
5085 None
5086 }
5087 } else {
5088 None
5089 }
5090 }
5091
5092 fn update_history(&self, cx: &mut App) {
5093 let Some(id) = self.database_id() else {
5094 return;
5095 };
5096 let Some(location) = self.serialize_workspace_location(cx) else {
5097 return;
5098 };
5099 if let Some(manager) = HistoryManager::global(cx) {
5100 manager.update(cx, |this, cx| {
5101 this.update_history(id, HistoryManagerEntry::new(id, &location), cx);
5102 });
5103 }
5104 }
5105
5106 async fn serialize_items(
5107 this: &WeakEntity<Self>,
5108 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
5109 cx: &mut AsyncWindowContext,
5110 ) -> Result<()> {
5111 const CHUNK_SIZE: usize = 200;
5112
5113 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
5114
5115 while let Some(items_received) = serializable_items.next().await {
5116 let unique_items =
5117 items_received
5118 .into_iter()
5119 .fold(HashMap::default(), |mut acc, item| {
5120 acc.entry(item.item_id()).or_insert(item);
5121 acc
5122 });
5123
5124 // We use into_iter() here so that the references to the items are moved into
5125 // the tasks and not kept alive while we're sleeping.
5126 for (_, item) in unique_items.into_iter() {
5127 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
5128 item.serialize(workspace, false, window, cx)
5129 }) {
5130 cx.background_spawn(async move { task.await.log_err() })
5131 .detach();
5132 }
5133 }
5134
5135 cx.background_executor()
5136 .timer(SERIALIZATION_THROTTLE_TIME)
5137 .await;
5138 }
5139
5140 Ok(())
5141 }
5142
5143 pub(crate) fn enqueue_item_serialization(
5144 &mut self,
5145 item: Box<dyn SerializableItemHandle>,
5146 ) -> Result<()> {
5147 self.serializable_items_tx
5148 .unbounded_send(item)
5149 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
5150 }
5151
5152 pub(crate) fn load_workspace(
5153 serialized_workspace: SerializedWorkspace,
5154 paths_to_open: Vec<Option<ProjectPath>>,
5155 window: &mut Window,
5156 cx: &mut Context<Workspace>,
5157 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
5158 cx.spawn_in(window, async move |workspace, cx| {
5159 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
5160
5161 let mut center_group = None;
5162 let mut center_items = None;
5163
5164 // Traverse the splits tree and add to things
5165 if let Some((group, active_pane, items)) = serialized_workspace
5166 .center_group
5167 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
5168 .await
5169 {
5170 center_items = Some(items);
5171 center_group = Some((group, active_pane))
5172 }
5173
5174 let mut items_by_project_path = HashMap::default();
5175 let mut item_ids_by_kind = HashMap::default();
5176 let mut all_deserialized_items = Vec::default();
5177 cx.update(|_, cx| {
5178 for item in center_items.unwrap_or_default().into_iter().flatten() {
5179 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
5180 item_ids_by_kind
5181 .entry(serializable_item_handle.serialized_item_kind())
5182 .or_insert(Vec::new())
5183 .push(item.item_id().as_u64() as ItemId);
5184 }
5185
5186 if let Some(project_path) = item.project_path(cx) {
5187 items_by_project_path.insert(project_path, item.clone());
5188 }
5189 all_deserialized_items.push(item);
5190 }
5191 })?;
5192
5193 let opened_items = paths_to_open
5194 .into_iter()
5195 .map(|path_to_open| {
5196 path_to_open
5197 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
5198 })
5199 .collect::<Vec<_>>();
5200
5201 // Remove old panes from workspace panes list
5202 workspace.update_in(cx, |workspace, window, cx| {
5203 if let Some((center_group, active_pane)) = center_group {
5204 workspace.remove_panes(workspace.center.root.clone(), window, cx);
5205
5206 // Swap workspace center group
5207 workspace.center = PaneGroup::with_root(center_group);
5208 if let Some(active_pane) = active_pane {
5209 workspace.set_active_pane(&active_pane, window, cx);
5210 cx.focus_self(window);
5211 } else {
5212 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
5213 }
5214 }
5215
5216 let docks = serialized_workspace.docks;
5217
5218 for (dock, serialized_dock) in [
5219 (&mut workspace.right_dock, docks.right),
5220 (&mut workspace.left_dock, docks.left),
5221 (&mut workspace.bottom_dock, docks.bottom),
5222 ]
5223 .iter_mut()
5224 {
5225 dock.update(cx, |dock, cx| {
5226 dock.serialized_dock = Some(serialized_dock.clone());
5227 dock.restore_state(window, cx);
5228 });
5229 }
5230
5231 cx.notify();
5232 })?;
5233
5234 let _ = project
5235 .update(cx, |project, cx| {
5236 project
5237 .breakpoint_store()
5238 .update(cx, |breakpoint_store, cx| {
5239 breakpoint_store
5240 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
5241 })
5242 })?
5243 .await;
5244
5245 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
5246 // after loading the items, we might have different items and in order to avoid
5247 // the database filling up, we delete items that haven't been loaded now.
5248 //
5249 // The items that have been loaded, have been saved after they've been added to the workspace.
5250 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
5251 item_ids_by_kind
5252 .into_iter()
5253 .map(|(item_kind, loaded_items)| {
5254 SerializableItemRegistry::cleanup(
5255 item_kind,
5256 serialized_workspace.id,
5257 loaded_items,
5258 window,
5259 cx,
5260 )
5261 .log_err()
5262 })
5263 .collect::<Vec<_>>()
5264 })?;
5265
5266 futures::future::join_all(clean_up_tasks).await;
5267
5268 workspace
5269 .update_in(cx, |workspace, window, cx| {
5270 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
5271 workspace.serialize_workspace_internal(window, cx).detach();
5272
5273 // Ensure that we mark the window as edited if we did load dirty items
5274 workspace.update_window_edited(window, cx);
5275 })
5276 .ok();
5277
5278 Ok(opened_items)
5279 })
5280 }
5281
5282 fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
5283 self.add_workspace_actions_listeners(div, window, cx)
5284 .on_action(cx.listener(Self::close_inactive_items_and_panes))
5285 .on_action(cx.listener(Self::close_all_items_and_panes))
5286 .on_action(cx.listener(Self::save_all))
5287 .on_action(cx.listener(Self::send_keystrokes))
5288 .on_action(cx.listener(Self::add_folder_to_project))
5289 .on_action(cx.listener(Self::follow_next_collaborator))
5290 .on_action(cx.listener(Self::close_window))
5291 .on_action(cx.listener(Self::activate_pane_at_index))
5292 .on_action(cx.listener(Self::move_item_to_pane_at_index))
5293 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
5294 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
5295 let pane = workspace.active_pane().clone();
5296 workspace.unfollow_in_pane(&pane, window, cx);
5297 }))
5298 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
5299 workspace
5300 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
5301 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
5302 }))
5303 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
5304 workspace
5305 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
5306 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
5307 }))
5308 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
5309 workspace
5310 .save_active_item(SaveIntent::SaveAs, window, cx)
5311 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
5312 }))
5313 .on_action(
5314 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
5315 workspace.activate_previous_pane(window, cx)
5316 }),
5317 )
5318 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
5319 workspace.activate_next_pane(window, cx)
5320 }))
5321 .on_action(
5322 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
5323 workspace.activate_next_window(cx)
5324 }),
5325 )
5326 .on_action(
5327 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
5328 workspace.activate_previous_window(cx)
5329 }),
5330 )
5331 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
5332 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
5333 }))
5334 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
5335 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
5336 }))
5337 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
5338 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
5339 }))
5340 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
5341 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
5342 }))
5343 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
5344 workspace.activate_next_pane(window, cx)
5345 }))
5346 .on_action(cx.listener(
5347 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
5348 workspace.move_item_to_pane_in_direction(action, window, cx)
5349 },
5350 ))
5351 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
5352 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
5353 }))
5354 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
5355 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
5356 }))
5357 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
5358 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
5359 }))
5360 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
5361 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
5362 }))
5363 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
5364 this.toggle_dock(DockPosition::Left, window, cx);
5365 }))
5366 .on_action(cx.listener(
5367 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
5368 workspace.toggle_dock(DockPosition::Right, window, cx);
5369 },
5370 ))
5371 .on_action(cx.listener(
5372 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
5373 workspace.toggle_dock(DockPosition::Bottom, window, cx);
5374 },
5375 ))
5376 .on_action(cx.listener(
5377 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
5378 workspace.close_active_dock(window, cx);
5379 },
5380 ))
5381 .on_action(
5382 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
5383 workspace.close_all_docks(window, cx);
5384 }),
5385 )
5386 .on_action(cx.listener(
5387 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
5388 workspace.clear_all_notifications(cx);
5389 },
5390 ))
5391 .on_action(cx.listener(
5392 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
5393 if let Some((notification_id, _)) = workspace.notifications.pop() {
5394 workspace.suppress_notification(¬ification_id, cx);
5395 }
5396 },
5397 ))
5398 .on_action(cx.listener(
5399 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
5400 workspace.reopen_closed_item(window, cx).detach();
5401 },
5402 ))
5403 .on_action(cx.listener(Workspace::toggle_centered_layout))
5404 .on_action(cx.listener(Workspace::cancel))
5405 }
5406
5407 #[cfg(any(test, feature = "test-support"))]
5408 pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
5409 use node_runtime::NodeRuntime;
5410 use session::Session;
5411
5412 let client = project.read(cx).client();
5413 let user_store = project.read(cx).user_store();
5414
5415 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
5416 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
5417 window.activate_window();
5418 let app_state = Arc::new(AppState {
5419 languages: project.read(cx).languages().clone(),
5420 workspace_store,
5421 client,
5422 user_store,
5423 fs: project.read(cx).fs().clone(),
5424 build_window_options: |_, _| Default::default(),
5425 node_runtime: NodeRuntime::unavailable(),
5426 session,
5427 });
5428 let workspace = Self::new(Default::default(), project, app_state, window, cx);
5429 workspace
5430 .active_pane
5431 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
5432 workspace
5433 }
5434
5435 pub fn register_action<A: Action>(
5436 &mut self,
5437 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
5438 ) -> &mut Self {
5439 let callback = Arc::new(callback);
5440
5441 self.workspace_actions.push(Box::new(move |div, _, cx| {
5442 let callback = callback.clone();
5443 div.on_action(cx.listener(move |workspace, event, window, cx| {
5444 (callback)(workspace, event, window, cx)
5445 }))
5446 }));
5447 self
5448 }
5449
5450 fn add_workspace_actions_listeners(
5451 &self,
5452 mut div: Div,
5453 window: &mut Window,
5454 cx: &mut Context<Self>,
5455 ) -> Div {
5456 for action in self.workspace_actions.iter() {
5457 div = (action)(div, window, cx)
5458 }
5459 div
5460 }
5461
5462 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
5463 self.modal_layer.read(cx).has_active_modal()
5464 }
5465
5466 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
5467 self.modal_layer.read(cx).active_modal()
5468 }
5469
5470 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
5471 where
5472 B: FnOnce(&mut Window, &mut Context<V>) -> V,
5473 {
5474 self.modal_layer.update(cx, |modal_layer, cx| {
5475 modal_layer.toggle_modal(window, cx, build)
5476 })
5477 }
5478
5479 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
5480 self.toast_layer
5481 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
5482 }
5483
5484 pub fn toggle_centered_layout(
5485 &mut self,
5486 _: &ToggleCenteredLayout,
5487 _: &mut Window,
5488 cx: &mut Context<Self>,
5489 ) {
5490 self.centered_layout = !self.centered_layout;
5491 if let Some(database_id) = self.database_id() {
5492 cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
5493 .detach_and_log_err(cx);
5494 }
5495 cx.notify();
5496 }
5497
5498 fn adjust_padding(padding: Option<f32>) -> f32 {
5499 padding
5500 .unwrap_or(Self::DEFAULT_PADDING)
5501 .clamp(0.0, Self::MAX_PADDING)
5502 }
5503
5504 fn render_dock(
5505 &self,
5506 position: DockPosition,
5507 dock: &Entity<Dock>,
5508 window: &mut Window,
5509 cx: &mut App,
5510 ) -> Option<Div> {
5511 if self.zoomed_position == Some(position) {
5512 return None;
5513 }
5514
5515 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
5516 let pane = panel.pane(cx)?;
5517 let follower_states = &self.follower_states;
5518 leader_border_for_pane(follower_states, &pane, window, cx)
5519 });
5520
5521 Some(
5522 div()
5523 .flex()
5524 .flex_none()
5525 .overflow_hidden()
5526 .child(dock.clone())
5527 .children(leader_border),
5528 )
5529 }
5530
5531 pub fn for_window(window: &mut Window, _: &mut App) -> Option<Entity<Workspace>> {
5532 window.root().flatten()
5533 }
5534
5535 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
5536 self.zoomed.as_ref()
5537 }
5538
5539 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
5540 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
5541 return;
5542 };
5543 let windows = cx.windows();
5544 let Some(next_window) = windows
5545 .iter()
5546 .cycle()
5547 .skip_while(|window| window.window_id() != current_window_id)
5548 .nth(1)
5549 else {
5550 return;
5551 };
5552 next_window
5553 .update(cx, |_, window, _| window.activate_window())
5554 .ok();
5555 }
5556
5557 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
5558 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
5559 return;
5560 };
5561 let windows = cx.windows();
5562 let Some(prev_window) = windows
5563 .iter()
5564 .rev()
5565 .cycle()
5566 .skip_while(|window| window.window_id() != current_window_id)
5567 .nth(1)
5568 else {
5569 return;
5570 };
5571 prev_window
5572 .update(cx, |_, window, _| window.activate_window())
5573 .ok();
5574 }
5575
5576 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
5577 if cx.stop_active_drag(window) {
5578 return;
5579 } else if let Some((notification_id, _)) = self.notifications.pop() {
5580 dismiss_app_notification(¬ification_id, cx);
5581 } else {
5582 cx.emit(Event::ClearActivityIndicator);
5583 cx.propagate();
5584 }
5585 }
5586}
5587
5588fn leader_border_for_pane(
5589 follower_states: &HashMap<CollaboratorId, FollowerState>,
5590 pane: &Entity<Pane>,
5591 _: &Window,
5592 cx: &App,
5593) -> Option<Div> {
5594 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
5595 if state.pane() == pane {
5596 Some((*leader_id, state))
5597 } else {
5598 None
5599 }
5600 })?;
5601
5602 let mut leader_color = match leader_id {
5603 CollaboratorId::PeerId(leader_peer_id) => {
5604 let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
5605 let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
5606
5607 cx.theme()
5608 .players()
5609 .color_for_participant(leader.participant_index.0)
5610 .cursor
5611 }
5612 CollaboratorId::Agent => cx.theme().players().agent().cursor,
5613 };
5614 leader_color.fade_out(0.3);
5615 Some(
5616 div()
5617 .absolute()
5618 .size_full()
5619 .left_0()
5620 .top_0()
5621 .border_2()
5622 .border_color(leader_color),
5623 )
5624}
5625
5626fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
5627 ZED_WINDOW_POSITION
5628 .zip(*ZED_WINDOW_SIZE)
5629 .map(|(position, size)| Bounds {
5630 origin: position,
5631 size,
5632 })
5633}
5634
5635fn open_items(
5636 serialized_workspace: Option<SerializedWorkspace>,
5637 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
5638 window: &mut Window,
5639 cx: &mut Context<Workspace>,
5640) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
5641 let restored_items = serialized_workspace.map(|serialized_workspace| {
5642 Workspace::load_workspace(
5643 serialized_workspace,
5644 project_paths_to_open
5645 .iter()
5646 .map(|(_, project_path)| project_path)
5647 .cloned()
5648 .collect(),
5649 window,
5650 cx,
5651 )
5652 });
5653
5654 cx.spawn_in(window, async move |workspace, cx| {
5655 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
5656
5657 if let Some(restored_items) = restored_items {
5658 let restored_items = restored_items.await?;
5659
5660 let restored_project_paths = restored_items
5661 .iter()
5662 .filter_map(|item| {
5663 cx.update(|_, cx| item.as_ref()?.project_path(cx))
5664 .ok()
5665 .flatten()
5666 })
5667 .collect::<HashSet<_>>();
5668
5669 for restored_item in restored_items {
5670 opened_items.push(restored_item.map(Ok));
5671 }
5672
5673 project_paths_to_open
5674 .iter_mut()
5675 .for_each(|(_, project_path)| {
5676 if let Some(project_path_to_open) = project_path {
5677 if restored_project_paths.contains(project_path_to_open) {
5678 *project_path = None;
5679 }
5680 }
5681 });
5682 } else {
5683 for _ in 0..project_paths_to_open.len() {
5684 opened_items.push(None);
5685 }
5686 }
5687 assert!(opened_items.len() == project_paths_to_open.len());
5688
5689 let tasks =
5690 project_paths_to_open
5691 .into_iter()
5692 .enumerate()
5693 .map(|(ix, (abs_path, project_path))| {
5694 let workspace = workspace.clone();
5695 cx.spawn(async move |cx| {
5696 let file_project_path = project_path?;
5697 let abs_path_task = workspace.update(cx, |workspace, cx| {
5698 workspace.project().update(cx, |project, cx| {
5699 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
5700 })
5701 });
5702
5703 // We only want to open file paths here. If one of the items
5704 // here is a directory, it was already opened further above
5705 // with a `find_or_create_worktree`.
5706 if let Ok(task) = abs_path_task {
5707 if task.await.map_or(true, |p| p.is_file()) {
5708 return Some((
5709 ix,
5710 workspace
5711 .update_in(cx, |workspace, window, cx| {
5712 workspace.open_path(
5713 file_project_path,
5714 None,
5715 true,
5716 window,
5717 cx,
5718 )
5719 })
5720 .log_err()?
5721 .await,
5722 ));
5723 }
5724 }
5725 None
5726 })
5727 });
5728
5729 let tasks = tasks.collect::<Vec<_>>();
5730
5731 let tasks = futures::future::join_all(tasks);
5732 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
5733 opened_items[ix] = Some(path_open_result);
5734 }
5735
5736 Ok(opened_items)
5737 })
5738}
5739
5740enum ActivateInDirectionTarget {
5741 Pane(Entity<Pane>),
5742 Dock(Entity<Dock>),
5743}
5744
5745fn notify_if_database_failed(workspace: WindowHandle<Workspace>, cx: &mut AsyncApp) {
5746 workspace
5747 .update(cx, |workspace, _, cx| {
5748 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
5749 struct DatabaseFailedNotification;
5750
5751 workspace.show_notification(
5752 NotificationId::unique::<DatabaseFailedNotification>(),
5753 cx,
5754 |cx| {
5755 cx.new(|cx| {
5756 MessageNotification::new("Failed to load the database file.", cx)
5757 .primary_message("File an Issue")
5758 .primary_icon(IconName::Plus)
5759 .primary_on_click(|window, cx| {
5760 window.dispatch_action(Box::new(FileBugReport), cx)
5761 })
5762 })
5763 },
5764 );
5765 }
5766 })
5767 .log_err();
5768}
5769
5770impl Focusable for Workspace {
5771 fn focus_handle(&self, cx: &App) -> FocusHandle {
5772 self.active_pane.focus_handle(cx)
5773 }
5774}
5775
5776#[derive(Clone)]
5777struct DraggedDock(DockPosition);
5778
5779impl Render for DraggedDock {
5780 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5781 gpui::Empty
5782 }
5783}
5784
5785impl Render for Workspace {
5786 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5787 let mut context = KeyContext::new_with_defaults();
5788 context.add("Workspace");
5789 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
5790 if let Some(status) = self
5791 .debugger_provider
5792 .as_ref()
5793 .and_then(|provider| provider.active_thread_state(cx))
5794 {
5795 match status {
5796 ThreadStatus::Running | ThreadStatus::Stepping => {
5797 context.add("debugger_running");
5798 }
5799 ThreadStatus::Stopped => context.add("debugger_stopped"),
5800 ThreadStatus::Exited | ThreadStatus::Ended => {}
5801 }
5802 }
5803
5804 let centered_layout = self.centered_layout
5805 && self.center.panes().len() == 1
5806 && self.active_item(cx).is_some();
5807 let render_padding = |size| {
5808 (size > 0.0).then(|| {
5809 div()
5810 .h_full()
5811 .w(relative(size))
5812 .bg(cx.theme().colors().editor_background)
5813 .border_color(cx.theme().colors().pane_group_border)
5814 })
5815 };
5816 let paddings = if centered_layout {
5817 let settings = WorkspaceSettings::get_global(cx).centered_layout;
5818 (
5819 render_padding(Self::adjust_padding(settings.left_padding)),
5820 render_padding(Self::adjust_padding(settings.right_padding)),
5821 )
5822 } else {
5823 (None, None)
5824 };
5825 let ui_font = theme::setup_ui_font(window, cx);
5826
5827 let theme = cx.theme().clone();
5828 let colors = theme.colors();
5829 let notification_entities = self
5830 .notifications
5831 .iter()
5832 .map(|(_, notification)| notification.entity_id())
5833 .collect::<Vec<_>>();
5834
5835 client_side_decorations(
5836 self.actions(div(), window, cx)
5837 .key_context(context)
5838 .relative()
5839 .size_full()
5840 .flex()
5841 .flex_col()
5842 .font(ui_font)
5843 .gap_0()
5844 .justify_start()
5845 .items_start()
5846 .text_color(colors.text)
5847 .overflow_hidden()
5848 .children(self.titlebar_item.clone())
5849 .on_modifiers_changed(move |_, _, cx| {
5850 for &id in ¬ification_entities {
5851 cx.notify(id);
5852 }
5853 })
5854 .child(
5855 div()
5856 .size_full()
5857 .relative()
5858 .flex_1()
5859 .flex()
5860 .flex_col()
5861 .child(
5862 div()
5863 .id("workspace")
5864 .bg(colors.background)
5865 .relative()
5866 .flex_1()
5867 .w_full()
5868 .flex()
5869 .flex_col()
5870 .overflow_hidden()
5871 .border_t_1()
5872 .border_b_1()
5873 .border_color(colors.border)
5874 .child({
5875 let this = cx.entity().clone();
5876 canvas(
5877 move |bounds, window, cx| {
5878 this.update(cx, |this, cx| {
5879 let bounds_changed = this.bounds != bounds;
5880 this.bounds = bounds;
5881
5882 if bounds_changed {
5883 this.left_dock.update(cx, |dock, cx| {
5884 dock.clamp_panel_size(
5885 bounds.size.width,
5886 window,
5887 cx,
5888 )
5889 });
5890
5891 this.right_dock.update(cx, |dock, cx| {
5892 dock.clamp_panel_size(
5893 bounds.size.width,
5894 window,
5895 cx,
5896 )
5897 });
5898
5899 this.bottom_dock.update(cx, |dock, cx| {
5900 dock.clamp_panel_size(
5901 bounds.size.height,
5902 window,
5903 cx,
5904 )
5905 });
5906 }
5907 })
5908 },
5909 |_, _, _, _| {},
5910 )
5911 .absolute()
5912 .size_full()
5913 })
5914 .when(self.zoomed.is_none(), |this| {
5915 this.on_drag_move(cx.listener(
5916 move |workspace,
5917 e: &DragMoveEvent<DraggedDock>,
5918 window,
5919 cx| {
5920 if workspace.previous_dock_drag_coordinates
5921 != Some(e.event.position)
5922 {
5923 workspace.previous_dock_drag_coordinates =
5924 Some(e.event.position);
5925 match e.drag(cx).0 {
5926 DockPosition::Left => {
5927 resize_left_dock(
5928 e.event.position.x
5929 - workspace.bounds.left(),
5930 workspace,
5931 window,
5932 cx,
5933 );
5934 }
5935 DockPosition::Right => {
5936 resize_right_dock(
5937 workspace.bounds.right()
5938 - e.event.position.x,
5939 workspace,
5940 window,
5941 cx,
5942 );
5943 }
5944 DockPosition::Bottom => {
5945 resize_bottom_dock(
5946 workspace.bounds.bottom()
5947 - e.event.position.y,
5948 workspace,
5949 window,
5950 cx,
5951 );
5952 }
5953 };
5954 workspace.serialize_workspace(window, cx);
5955 }
5956 },
5957 ))
5958 })
5959 .child({
5960 match self.bottom_dock_layout {
5961 BottomDockLayout::Full => div()
5962 .flex()
5963 .flex_col()
5964 .h_full()
5965 .child(
5966 div()
5967 .flex()
5968 .flex_row()
5969 .flex_1()
5970 .overflow_hidden()
5971 .children(self.render_dock(
5972 DockPosition::Left,
5973 &self.left_dock,
5974 window,
5975 cx,
5976 ))
5977 .child(
5978 div()
5979 .flex()
5980 .flex_col()
5981 .flex_1()
5982 .overflow_hidden()
5983 .child(
5984 h_flex()
5985 .flex_1()
5986 .when_some(
5987 paddings.0,
5988 |this, p| {
5989 this.child(
5990 p.border_r_1(),
5991 )
5992 },
5993 )
5994 .child(self.center.render(
5995 self.zoomed.as_ref(),
5996 &PaneRenderContext {
5997 follower_states:
5998 &self.follower_states,
5999 active_call: self.active_call(),
6000 active_pane: &self.active_pane,
6001 app_state: &self.app_state,
6002 project: &self.project,
6003 workspace: &self.weak_self,
6004 },
6005 window,
6006 cx,
6007 ))
6008 .when_some(
6009 paddings.1,
6010 |this, p| {
6011 this.child(
6012 p.border_l_1(),
6013 )
6014 },
6015 ),
6016 ),
6017 )
6018 .children(self.render_dock(
6019 DockPosition::Right,
6020 &self.right_dock,
6021 window,
6022 cx,
6023 )),
6024 )
6025 .child(div().w_full().children(self.render_dock(
6026 DockPosition::Bottom,
6027 &self.bottom_dock,
6028 window,
6029 cx
6030 ))),
6031
6032 BottomDockLayout::LeftAligned => div()
6033 .flex()
6034 .flex_row()
6035 .h_full()
6036 .child(
6037 div()
6038 .flex()
6039 .flex_col()
6040 .flex_1()
6041 .h_full()
6042 .child(
6043 div()
6044 .flex()
6045 .flex_row()
6046 .flex_1()
6047 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
6048 .child(
6049 div()
6050 .flex()
6051 .flex_col()
6052 .flex_1()
6053 .overflow_hidden()
6054 .child(
6055 h_flex()
6056 .flex_1()
6057 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
6058 .child(self.center.render(
6059 self.zoomed.as_ref(),
6060 &PaneRenderContext {
6061 follower_states:
6062 &self.follower_states,
6063 active_call: self.active_call(),
6064 active_pane: &self.active_pane,
6065 app_state: &self.app_state,
6066 project: &self.project,
6067 workspace: &self.weak_self,
6068 },
6069 window,
6070 cx,
6071 ))
6072 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
6073 )
6074 )
6075 )
6076 .child(
6077 div()
6078 .w_full()
6079 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
6080 ),
6081 )
6082 .children(self.render_dock(
6083 DockPosition::Right,
6084 &self.right_dock,
6085 window,
6086 cx,
6087 )),
6088
6089 BottomDockLayout::RightAligned => div()
6090 .flex()
6091 .flex_row()
6092 .h_full()
6093 .children(self.render_dock(
6094 DockPosition::Left,
6095 &self.left_dock,
6096 window,
6097 cx,
6098 ))
6099 .child(
6100 div()
6101 .flex()
6102 .flex_col()
6103 .flex_1()
6104 .h_full()
6105 .child(
6106 div()
6107 .flex()
6108 .flex_row()
6109 .flex_1()
6110 .child(
6111 div()
6112 .flex()
6113 .flex_col()
6114 .flex_1()
6115 .overflow_hidden()
6116 .child(
6117 h_flex()
6118 .flex_1()
6119 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
6120 .child(self.center.render(
6121 self.zoomed.as_ref(),
6122 &PaneRenderContext {
6123 follower_states:
6124 &self.follower_states,
6125 active_call: self.active_call(),
6126 active_pane: &self.active_pane,
6127 app_state: &self.app_state,
6128 project: &self.project,
6129 workspace: &self.weak_self,
6130 },
6131 window,
6132 cx,
6133 ))
6134 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
6135 )
6136 )
6137 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
6138 )
6139 .child(
6140 div()
6141 .w_full()
6142 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
6143 ),
6144 ),
6145
6146 BottomDockLayout::Contained => div()
6147 .flex()
6148 .flex_row()
6149 .h_full()
6150 .children(self.render_dock(
6151 DockPosition::Left,
6152 &self.left_dock,
6153 window,
6154 cx,
6155 ))
6156 .child(
6157 div()
6158 .flex()
6159 .flex_col()
6160 .flex_1()
6161 .overflow_hidden()
6162 .child(
6163 h_flex()
6164 .flex_1()
6165 .when_some(paddings.0, |this, p| {
6166 this.child(p.border_r_1())
6167 })
6168 .child(self.center.render(
6169 self.zoomed.as_ref(),
6170 &PaneRenderContext {
6171 follower_states:
6172 &self.follower_states,
6173 active_call: self.active_call(),
6174 active_pane: &self.active_pane,
6175 app_state: &self.app_state,
6176 project: &self.project,
6177 workspace: &self.weak_self,
6178 },
6179 window,
6180 cx,
6181 ))
6182 .when_some(paddings.1, |this, p| {
6183 this.child(p.border_l_1())
6184 }),
6185 )
6186 .children(self.render_dock(
6187 DockPosition::Bottom,
6188 &self.bottom_dock,
6189 window,
6190 cx,
6191 )),
6192 )
6193 .children(self.render_dock(
6194 DockPosition::Right,
6195 &self.right_dock,
6196 window,
6197 cx,
6198 )),
6199 }
6200 })
6201 .children(self.zoomed.as_ref().and_then(|view| {
6202 let zoomed_view = view.upgrade()?;
6203 let div = div()
6204 .occlude()
6205 .absolute()
6206 .overflow_hidden()
6207 .border_color(colors.border)
6208 .bg(colors.background)
6209 .child(zoomed_view)
6210 .inset_0()
6211 .shadow_lg();
6212
6213 Some(match self.zoomed_position {
6214 Some(DockPosition::Left) => div.right_2().border_r_1(),
6215 Some(DockPosition::Right) => div.left_2().border_l_1(),
6216 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
6217 None => {
6218 div.top_2().bottom_2().left_2().right_2().border_1()
6219 }
6220 })
6221 }))
6222 .children(self.render_notifications(window, cx)),
6223 )
6224 .child(self.status_bar.clone())
6225 .child(self.modal_layer.clone())
6226 .child(self.toast_layer.clone()),
6227 ),
6228 window,
6229 cx,
6230 )
6231 }
6232}
6233
6234fn resize_bottom_dock(
6235 new_size: Pixels,
6236 workspace: &mut Workspace,
6237 window: &mut Window,
6238 cx: &mut App,
6239) {
6240 let size =
6241 new_size.min(workspace.bounds.bottom() - RESIZE_HANDLE_SIZE - workspace.bounds.top());
6242 workspace.bottom_dock.update(cx, |bottom_dock, cx| {
6243 bottom_dock.resize_active_panel(Some(size), window, cx);
6244 });
6245}
6246
6247fn resize_right_dock(
6248 new_size: Pixels,
6249 workspace: &mut Workspace,
6250 window: &mut Window,
6251 cx: &mut App,
6252) {
6253 let size = new_size.max(workspace.bounds.left() - RESIZE_HANDLE_SIZE);
6254 workspace.right_dock.update(cx, |right_dock, cx| {
6255 right_dock.resize_active_panel(Some(size), window, cx);
6256 });
6257}
6258
6259fn resize_left_dock(
6260 new_size: Pixels,
6261 workspace: &mut Workspace,
6262 window: &mut Window,
6263 cx: &mut App,
6264) {
6265 let size = new_size.min(workspace.bounds.right() - RESIZE_HANDLE_SIZE);
6266
6267 workspace.left_dock.update(cx, |left_dock, cx| {
6268 left_dock.resize_active_panel(Some(size), window, cx);
6269 });
6270}
6271
6272impl WorkspaceStore {
6273 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
6274 Self {
6275 workspaces: Default::default(),
6276 _subscriptions: vec![
6277 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
6278 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
6279 ],
6280 client,
6281 }
6282 }
6283
6284 pub fn update_followers(
6285 &self,
6286 project_id: Option<u64>,
6287 update: proto::update_followers::Variant,
6288 cx: &App,
6289 ) -> Option<()> {
6290 let active_call = ActiveCall::try_global(cx)?;
6291 let room_id = active_call.read(cx).room()?.read(cx).id();
6292 self.client
6293 .send(proto::UpdateFollowers {
6294 room_id,
6295 project_id,
6296 variant: Some(update),
6297 })
6298 .log_err()
6299 }
6300
6301 pub async fn handle_follow(
6302 this: Entity<Self>,
6303 envelope: TypedEnvelope<proto::Follow>,
6304 mut cx: AsyncApp,
6305 ) -> Result<proto::FollowResponse> {
6306 this.update(&mut cx, |this, cx| {
6307 let follower = Follower {
6308 project_id: envelope.payload.project_id,
6309 peer_id: envelope.original_sender_id()?,
6310 };
6311
6312 let mut response = proto::FollowResponse::default();
6313 this.workspaces.retain(|workspace| {
6314 workspace
6315 .update(cx, |workspace, window, cx| {
6316 let handler_response =
6317 workspace.handle_follow(follower.project_id, window, cx);
6318 if let Some(active_view) = handler_response.active_view.clone() {
6319 if workspace.project.read(cx).remote_id() == follower.project_id {
6320 response.active_view = Some(active_view)
6321 }
6322 }
6323 })
6324 .is_ok()
6325 });
6326
6327 Ok(response)
6328 })?
6329 }
6330
6331 async fn handle_update_followers(
6332 this: Entity<Self>,
6333 envelope: TypedEnvelope<proto::UpdateFollowers>,
6334 mut cx: AsyncApp,
6335 ) -> Result<()> {
6336 let leader_id = envelope.original_sender_id()?;
6337 let update = envelope.payload;
6338
6339 this.update(&mut cx, |this, cx| {
6340 this.workspaces.retain(|workspace| {
6341 workspace
6342 .update(cx, |workspace, window, cx| {
6343 let project_id = workspace.project.read(cx).remote_id();
6344 if update.project_id != project_id && update.project_id.is_some() {
6345 return;
6346 }
6347 workspace.handle_update_followers(leader_id, update.clone(), window, cx);
6348 })
6349 .is_ok()
6350 });
6351 Ok(())
6352 })?
6353 }
6354}
6355
6356impl ViewId {
6357 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
6358 Ok(Self {
6359 creator: message
6360 .creator
6361 .map(CollaboratorId::PeerId)
6362 .context("creator is missing")?,
6363 id: message.id,
6364 })
6365 }
6366
6367 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
6368 if let CollaboratorId::PeerId(peer_id) = self.creator {
6369 Some(proto::ViewId {
6370 creator: Some(peer_id),
6371 id: self.id,
6372 })
6373 } else {
6374 None
6375 }
6376 }
6377}
6378
6379impl FollowerState {
6380 fn pane(&self) -> &Entity<Pane> {
6381 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
6382 }
6383}
6384
6385pub trait WorkspaceHandle {
6386 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
6387}
6388
6389impl WorkspaceHandle for Entity<Workspace> {
6390 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
6391 self.read(cx)
6392 .worktrees(cx)
6393 .flat_map(|worktree| {
6394 let worktree_id = worktree.read(cx).id();
6395 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
6396 worktree_id,
6397 path: f.path.clone(),
6398 })
6399 })
6400 .collect::<Vec<_>>()
6401 }
6402}
6403
6404impl std::fmt::Debug for OpenPaths {
6405 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6406 f.debug_struct("OpenPaths")
6407 .field("paths", &self.paths)
6408 .finish()
6409 }
6410}
6411
6412pub async fn last_opened_workspace_location() -> Option<SerializedWorkspaceLocation> {
6413 DB.last_workspace().await.log_err().flatten()
6414}
6415
6416pub fn last_session_workspace_locations(
6417 last_session_id: &str,
6418 last_session_window_stack: Option<Vec<WindowId>>,
6419) -> Option<Vec<SerializedWorkspaceLocation>> {
6420 DB.last_session_workspace_locations(last_session_id, last_session_window_stack)
6421 .log_err()
6422}
6423
6424actions!(
6425 collab,
6426 [
6427 OpenChannelNotes,
6428 Mute,
6429 Deafen,
6430 LeaveCall,
6431 ShareProject,
6432 ScreenShare
6433 ]
6434);
6435actions!(zed, [OpenLog]);
6436
6437async fn join_channel_internal(
6438 channel_id: ChannelId,
6439 app_state: &Arc<AppState>,
6440 requesting_window: Option<WindowHandle<Workspace>>,
6441 active_call: &Entity<ActiveCall>,
6442 cx: &mut AsyncApp,
6443) -> Result<bool> {
6444 let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
6445 let Some(room) = active_call.room().map(|room| room.read(cx)) else {
6446 return (false, None);
6447 };
6448
6449 let already_in_channel = room.channel_id() == Some(channel_id);
6450 let should_prompt = room.is_sharing_project()
6451 && !room.remote_participants().is_empty()
6452 && !already_in_channel;
6453 let open_room = if already_in_channel {
6454 active_call.room().cloned()
6455 } else {
6456 None
6457 };
6458 (should_prompt, open_room)
6459 })?;
6460
6461 if let Some(room) = open_room {
6462 let task = room.update(cx, |room, cx| {
6463 if let Some((project, host)) = room.most_active_project(cx) {
6464 return Some(join_in_room_project(project, host, app_state.clone(), cx));
6465 }
6466
6467 None
6468 })?;
6469 if let Some(task) = task {
6470 task.await?;
6471 }
6472 return anyhow::Ok(true);
6473 }
6474
6475 if should_prompt {
6476 if let Some(workspace) = requesting_window {
6477 let answer = workspace
6478 .update(cx, |_, window, cx| {
6479 window.prompt(
6480 PromptLevel::Warning,
6481 "Do you want to switch channels?",
6482 Some("Leaving this call will unshare your current project."),
6483 &["Yes, Join Channel", "Cancel"],
6484 cx,
6485 )
6486 })?
6487 .await;
6488
6489 if answer == Ok(1) {
6490 return Ok(false);
6491 }
6492 } else {
6493 return Ok(false); // unreachable!() hopefully
6494 }
6495 }
6496
6497 let client = cx.update(|cx| active_call.read(cx).client())?;
6498
6499 let mut client_status = client.status();
6500
6501 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
6502 'outer: loop {
6503 let Some(status) = client_status.recv().await else {
6504 anyhow::bail!("error connecting");
6505 };
6506
6507 match status {
6508 Status::Connecting
6509 | Status::Authenticating
6510 | Status::Reconnecting
6511 | Status::Reauthenticating => continue,
6512 Status::Connected { .. } => break 'outer,
6513 Status::SignedOut => return Err(ErrorCode::SignedOut.into()),
6514 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
6515 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
6516 return Err(ErrorCode::Disconnected.into());
6517 }
6518 }
6519 }
6520
6521 let room = active_call
6522 .update(cx, |active_call, cx| {
6523 active_call.join_channel(channel_id, cx)
6524 })?
6525 .await?;
6526
6527 let Some(room) = room else {
6528 return anyhow::Ok(true);
6529 };
6530
6531 room.update(cx, |room, _| room.room_update_completed())?
6532 .await;
6533
6534 let task = room.update(cx, |room, cx| {
6535 if let Some((project, host)) = room.most_active_project(cx) {
6536 return Some(join_in_room_project(project, host, app_state.clone(), cx));
6537 }
6538
6539 // If you are the first to join a channel, see if you should share your project.
6540 if room.remote_participants().is_empty() && !room.local_participant_is_guest() {
6541 if let Some(workspace) = requesting_window {
6542 let project = workspace.update(cx, |workspace, _, cx| {
6543 let project = workspace.project.read(cx);
6544
6545 if !CallSettings::get_global(cx).share_on_join {
6546 return None;
6547 }
6548
6549 if (project.is_local() || project.is_via_ssh())
6550 && project.visible_worktrees(cx).any(|tree| {
6551 tree.read(cx)
6552 .root_entry()
6553 .map_or(false, |entry| entry.is_dir())
6554 })
6555 {
6556 Some(workspace.project.clone())
6557 } else {
6558 None
6559 }
6560 });
6561 if let Ok(Some(project)) = project {
6562 return Some(cx.spawn(async move |room, cx| {
6563 room.update(cx, |room, cx| room.share_project(project, cx))?
6564 .await?;
6565 Ok(())
6566 }));
6567 }
6568 }
6569 }
6570
6571 None
6572 })?;
6573 if let Some(task) = task {
6574 task.await?;
6575 return anyhow::Ok(true);
6576 }
6577 anyhow::Ok(false)
6578}
6579
6580pub fn join_channel(
6581 channel_id: ChannelId,
6582 app_state: Arc<AppState>,
6583 requesting_window: Option<WindowHandle<Workspace>>,
6584 cx: &mut App,
6585) -> Task<Result<()>> {
6586 let active_call = ActiveCall::global(cx);
6587 cx.spawn(async move |cx| {
6588 let result = join_channel_internal(
6589 channel_id,
6590 &app_state,
6591 requesting_window,
6592 &active_call,
6593 cx,
6594 )
6595 .await;
6596
6597 // join channel succeeded, and opened a window
6598 if matches!(result, Ok(true)) {
6599 return anyhow::Ok(());
6600 }
6601
6602 // find an existing workspace to focus and show call controls
6603 let mut active_window =
6604 requesting_window.or_else(|| activate_any_workspace_window( cx));
6605 if active_window.is_none() {
6606 // no open workspaces, make one to show the error in (blergh)
6607 let (window_handle, _) = cx
6608 .update(|cx| {
6609 Workspace::new_local(vec![], app_state.clone(), requesting_window, None, cx)
6610 })?
6611 .await?;
6612
6613 if result.is_ok() {
6614 cx.update(|cx| {
6615 cx.dispatch_action(&OpenChannelNotes);
6616 }).log_err();
6617 }
6618
6619 active_window = Some(window_handle);
6620 }
6621
6622 if let Err(err) = result {
6623 log::error!("failed to join channel: {}", err);
6624 if let Some(active_window) = active_window {
6625 active_window
6626 .update(cx, |_, window, cx| {
6627 let detail: SharedString = match err.error_code() {
6628 ErrorCode::SignedOut => {
6629 "Please sign in to continue.".into()
6630 }
6631 ErrorCode::UpgradeRequired => {
6632 "Your are running an unsupported version of Zed. Please update to continue.".into()
6633 }
6634 ErrorCode::NoSuchChannel => {
6635 "No matching channel was found. Please check the link and try again.".into()
6636 }
6637 ErrorCode::Forbidden => {
6638 "This channel is private, and you do not have access. Please ask someone to add you and try again.".into()
6639 }
6640 ErrorCode::Disconnected => "Please check your internet connection and try again.".into(),
6641 _ => format!("{}\n\nPlease try again.", err).into(),
6642 };
6643 window.prompt(
6644 PromptLevel::Critical,
6645 "Failed to join channel",
6646 Some(&detail),
6647 &["Ok"],
6648 cx)
6649 })?
6650 .await
6651 .ok();
6652 }
6653 }
6654
6655 // return ok, we showed the error to the user.
6656 anyhow::Ok(())
6657 })
6658}
6659
6660pub async fn get_any_active_workspace(
6661 app_state: Arc<AppState>,
6662 mut cx: AsyncApp,
6663) -> anyhow::Result<WindowHandle<Workspace>> {
6664 // find an existing workspace to focus and show call controls
6665 let active_window = activate_any_workspace_window(&mut cx);
6666 if active_window.is_none() {
6667 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, cx))?
6668 .await?;
6669 }
6670 activate_any_workspace_window(&mut cx).context("could not open zed")
6671}
6672
6673fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
6674 cx.update(|cx| {
6675 if let Some(workspace_window) = cx
6676 .active_window()
6677 .and_then(|window| window.downcast::<Workspace>())
6678 {
6679 return Some(workspace_window);
6680 }
6681
6682 for window in cx.windows() {
6683 if let Some(workspace_window) = window.downcast::<Workspace>() {
6684 workspace_window
6685 .update(cx, |_, window, _| window.activate_window())
6686 .ok();
6687 return Some(workspace_window);
6688 }
6689 }
6690 None
6691 })
6692 .ok()
6693 .flatten()
6694}
6695
6696pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
6697 cx.windows()
6698 .into_iter()
6699 .filter_map(|window| window.downcast::<Workspace>())
6700 .filter(|workspace| {
6701 workspace
6702 .read(cx)
6703 .is_ok_and(|workspace| workspace.project.read(cx).is_local())
6704 })
6705 .collect()
6706}
6707
6708#[derive(Default)]
6709pub struct OpenOptions {
6710 pub visible: Option<OpenVisible>,
6711 pub focus: Option<bool>,
6712 pub open_new_workspace: Option<bool>,
6713 pub replace_window: Option<WindowHandle<Workspace>>,
6714 pub env: Option<HashMap<String, String>>,
6715}
6716
6717#[allow(clippy::type_complexity)]
6718pub fn open_paths(
6719 abs_paths: &[PathBuf],
6720 app_state: Arc<AppState>,
6721 open_options: OpenOptions,
6722 cx: &mut App,
6723) -> Task<
6724 anyhow::Result<(
6725 WindowHandle<Workspace>,
6726 Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
6727 )>,
6728> {
6729 let abs_paths = abs_paths.to_vec();
6730 let mut existing = None;
6731 let mut best_match = None;
6732 let mut open_visible = OpenVisible::All;
6733
6734 cx.spawn(async move |cx| {
6735 if open_options.open_new_workspace != Some(true) {
6736 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
6737 let all_metadatas = futures::future::join_all(all_paths)
6738 .await
6739 .into_iter()
6740 .filter_map(|result| result.ok().flatten())
6741 .collect::<Vec<_>>();
6742
6743 cx.update(|cx| {
6744 for window in local_workspace_windows(&cx) {
6745 if let Ok(workspace) = window.read(&cx) {
6746 let m = workspace.project.read(&cx).visibility_for_paths(
6747 &abs_paths,
6748 &all_metadatas,
6749 open_options.open_new_workspace == None,
6750 cx,
6751 );
6752 if m > best_match {
6753 existing = Some(window);
6754 best_match = m;
6755 } else if best_match.is_none()
6756 && open_options.open_new_workspace == Some(false)
6757 {
6758 existing = Some(window)
6759 }
6760 }
6761 }
6762 })?;
6763
6764 if open_options.open_new_workspace.is_none() && existing.is_none() {
6765 if all_metadatas.iter().all(|file| !file.is_dir) {
6766 cx.update(|cx| {
6767 if let Some(window) = cx
6768 .active_window()
6769 .and_then(|window| window.downcast::<Workspace>())
6770 {
6771 if let Ok(workspace) = window.read(cx) {
6772 let project = workspace.project().read(cx);
6773 if project.is_local() && !project.is_via_collab() {
6774 existing = Some(window);
6775 open_visible = OpenVisible::None;
6776 return;
6777 }
6778 }
6779 }
6780 for window in local_workspace_windows(cx) {
6781 if let Ok(workspace) = window.read(cx) {
6782 let project = workspace.project().read(cx);
6783 if project.is_via_collab() {
6784 continue;
6785 }
6786 existing = Some(window);
6787 open_visible = OpenVisible::None;
6788 break;
6789 }
6790 }
6791 })?;
6792 }
6793 }
6794 }
6795
6796 if let Some(existing) = existing {
6797 let open_task = existing
6798 .update(cx, |workspace, window, cx| {
6799 window.activate_window();
6800 workspace.open_paths(
6801 abs_paths,
6802 OpenOptions {
6803 visible: Some(open_visible),
6804 ..Default::default()
6805 },
6806 None,
6807 window,
6808 cx,
6809 )
6810 })?
6811 .await;
6812
6813 _ = existing.update(cx, |workspace, _, cx| {
6814 for item in open_task.iter().flatten() {
6815 if let Err(e) = item {
6816 workspace.show_error(&e, cx);
6817 }
6818 }
6819 });
6820
6821 Ok((existing, open_task))
6822 } else {
6823 cx.update(move |cx| {
6824 Workspace::new_local(
6825 abs_paths,
6826 app_state.clone(),
6827 open_options.replace_window,
6828 open_options.env,
6829 cx,
6830 )
6831 })?
6832 .await
6833 }
6834 })
6835}
6836
6837pub fn open_new(
6838 open_options: OpenOptions,
6839 app_state: Arc<AppState>,
6840 cx: &mut App,
6841 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
6842) -> Task<anyhow::Result<()>> {
6843 let task = Workspace::new_local(Vec::new(), app_state, None, open_options.env, cx);
6844 cx.spawn(async move |cx| {
6845 let (workspace, opened_paths) = task.await?;
6846 workspace.update(cx, |workspace, window, cx| {
6847 if opened_paths.is_empty() {
6848 init(workspace, window, cx)
6849 }
6850 })?;
6851 Ok(())
6852 })
6853}
6854
6855pub fn create_and_open_local_file(
6856 path: &'static Path,
6857 window: &mut Window,
6858 cx: &mut Context<Workspace>,
6859 default_content: impl 'static + Send + FnOnce() -> Rope,
6860) -> Task<Result<Box<dyn ItemHandle>>> {
6861 cx.spawn_in(window, async move |workspace, cx| {
6862 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
6863 if !fs.is_file(path).await {
6864 fs.create_file(path, Default::default()).await?;
6865 fs.save(path, &default_content(), Default::default())
6866 .await?;
6867 }
6868
6869 let mut items = workspace
6870 .update_in(cx, |workspace, window, cx| {
6871 workspace.with_local_workspace(window, cx, |workspace, window, cx| {
6872 workspace.open_paths(
6873 vec![path.to_path_buf()],
6874 OpenOptions {
6875 visible: Some(OpenVisible::None),
6876 ..Default::default()
6877 },
6878 None,
6879 window,
6880 cx,
6881 )
6882 })
6883 })?
6884 .await?
6885 .await;
6886
6887 let item = items.pop().flatten();
6888 item.with_context(|| format!("path {path:?} is not a file"))?
6889 })
6890}
6891
6892pub fn open_ssh_project_with_new_connection(
6893 window: WindowHandle<Workspace>,
6894 connection_options: SshConnectionOptions,
6895 cancel_rx: oneshot::Receiver<()>,
6896 delegate: Arc<dyn SshClientDelegate>,
6897 app_state: Arc<AppState>,
6898 paths: Vec<PathBuf>,
6899 cx: &mut App,
6900) -> Task<Result<()>> {
6901 cx.spawn(async move |cx| {
6902 let (serialized_ssh_project, workspace_id, serialized_workspace) =
6903 serialize_ssh_project(connection_options.clone(), paths.clone(), &cx).await?;
6904
6905 let session = match cx
6906 .update(|cx| {
6907 remote::SshRemoteClient::new(
6908 ConnectionIdentifier::Workspace(workspace_id.0),
6909 connection_options,
6910 cancel_rx,
6911 delegate,
6912 cx,
6913 )
6914 })?
6915 .await?
6916 {
6917 Some(result) => result,
6918 None => return Ok(()),
6919 };
6920
6921 let project = cx.update(|cx| {
6922 project::Project::ssh(
6923 session,
6924 app_state.client.clone(),
6925 app_state.node_runtime.clone(),
6926 app_state.user_store.clone(),
6927 app_state.languages.clone(),
6928 app_state.fs.clone(),
6929 cx,
6930 )
6931 })?;
6932
6933 open_ssh_project_inner(
6934 project,
6935 paths,
6936 serialized_ssh_project,
6937 workspace_id,
6938 serialized_workspace,
6939 app_state,
6940 window,
6941 cx,
6942 )
6943 .await
6944 })
6945}
6946
6947pub fn open_ssh_project_with_existing_connection(
6948 connection_options: SshConnectionOptions,
6949 project: Entity<Project>,
6950 paths: Vec<PathBuf>,
6951 app_state: Arc<AppState>,
6952 window: WindowHandle<Workspace>,
6953 cx: &mut AsyncApp,
6954) -> Task<Result<()>> {
6955 cx.spawn(async move |cx| {
6956 let (serialized_ssh_project, workspace_id, serialized_workspace) =
6957 serialize_ssh_project(connection_options.clone(), paths.clone(), &cx).await?;
6958
6959 open_ssh_project_inner(
6960 project,
6961 paths,
6962 serialized_ssh_project,
6963 workspace_id,
6964 serialized_workspace,
6965 app_state,
6966 window,
6967 cx,
6968 )
6969 .await
6970 })
6971}
6972
6973async fn open_ssh_project_inner(
6974 project: Entity<Project>,
6975 paths: Vec<PathBuf>,
6976 serialized_ssh_project: SerializedSshProject,
6977 workspace_id: WorkspaceId,
6978 serialized_workspace: Option<SerializedWorkspace>,
6979 app_state: Arc<AppState>,
6980 window: WindowHandle<Workspace>,
6981 cx: &mut AsyncApp,
6982) -> Result<()> {
6983 let toolchains = DB.toolchains(workspace_id).await?;
6984 for (toolchain, worktree_id, path) in toolchains {
6985 project
6986 .update(cx, |this, cx| {
6987 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
6988 })?
6989 .await;
6990 }
6991 let mut project_paths_to_open = vec![];
6992 let mut project_path_errors = vec![];
6993
6994 for path in paths {
6995 let result = cx
6996 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
6997 .await;
6998 match result {
6999 Ok((_, project_path)) => {
7000 project_paths_to_open.push((path.clone(), Some(project_path)));
7001 }
7002 Err(error) => {
7003 project_path_errors.push(error);
7004 }
7005 };
7006 }
7007
7008 if project_paths_to_open.is_empty() {
7009 return Err(project_path_errors.pop().context("no paths given")?);
7010 }
7011
7012 cx.update_window(window.into(), |_, window, cx| {
7013 window.replace_root(cx, |window, cx| {
7014 telemetry::event!("SSH Project Opened");
7015
7016 let mut workspace =
7017 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
7018 workspace.set_serialized_ssh_project(serialized_ssh_project);
7019 workspace.update_history(cx);
7020 workspace
7021 });
7022 })?;
7023
7024 window
7025 .update(cx, |_, window, cx| {
7026 window.activate_window();
7027 open_items(serialized_workspace, project_paths_to_open, window, cx)
7028 })?
7029 .await?;
7030
7031 window.update(cx, |workspace, _, cx| {
7032 for error in project_path_errors {
7033 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
7034 if let Some(path) = error.error_tag("path") {
7035 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
7036 }
7037 } else {
7038 workspace.show_error(&error, cx)
7039 }
7040 }
7041 })?;
7042
7043 Ok(())
7044}
7045
7046fn serialize_ssh_project(
7047 connection_options: SshConnectionOptions,
7048 paths: Vec<PathBuf>,
7049 cx: &AsyncApp,
7050) -> Task<
7051 Result<(
7052 SerializedSshProject,
7053 WorkspaceId,
7054 Option<SerializedWorkspace>,
7055 )>,
7056> {
7057 cx.background_spawn(async move {
7058 let serialized_ssh_project = persistence::DB
7059 .get_or_create_ssh_project(
7060 connection_options.host.clone(),
7061 connection_options.port,
7062 paths
7063 .iter()
7064 .map(|path| path.to_string_lossy().to_string())
7065 .collect::<Vec<_>>(),
7066 connection_options.username.clone(),
7067 )
7068 .await?;
7069
7070 let serialized_workspace =
7071 persistence::DB.workspace_for_ssh_project(&serialized_ssh_project);
7072
7073 let workspace_id = if let Some(workspace_id) =
7074 serialized_workspace.as_ref().map(|workspace| workspace.id)
7075 {
7076 workspace_id
7077 } else {
7078 persistence::DB.next_id().await?
7079 };
7080
7081 Ok((serialized_ssh_project, workspace_id, serialized_workspace))
7082 })
7083}
7084
7085pub fn join_in_room_project(
7086 project_id: u64,
7087 follow_user_id: u64,
7088 app_state: Arc<AppState>,
7089 cx: &mut App,
7090) -> Task<Result<()>> {
7091 let windows = cx.windows();
7092 cx.spawn(async move |cx| {
7093 let existing_workspace = windows.into_iter().find_map(|window_handle| {
7094 window_handle
7095 .downcast::<Workspace>()
7096 .and_then(|window_handle| {
7097 window_handle
7098 .update(cx, |workspace, _window, cx| {
7099 if workspace.project().read(cx).remote_id() == Some(project_id) {
7100 Some(window_handle)
7101 } else {
7102 None
7103 }
7104 })
7105 .unwrap_or(None)
7106 })
7107 });
7108
7109 let workspace = if let Some(existing_workspace) = existing_workspace {
7110 existing_workspace
7111 } else {
7112 let active_call = cx.update(|cx| ActiveCall::global(cx))?;
7113 let room = active_call
7114 .read_with(cx, |call, _| call.room().cloned())?
7115 .context("not in a call")?;
7116 let project = room
7117 .update(cx, |room, cx| {
7118 room.join_project(
7119 project_id,
7120 app_state.languages.clone(),
7121 app_state.fs.clone(),
7122 cx,
7123 )
7124 })?
7125 .await?;
7126
7127 let window_bounds_override = window_bounds_env_override();
7128 cx.update(|cx| {
7129 let mut options = (app_state.build_window_options)(None, cx);
7130 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
7131 cx.open_window(options, |window, cx| {
7132 cx.new(|cx| {
7133 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
7134 })
7135 })
7136 })??
7137 };
7138
7139 workspace.update(cx, |workspace, window, cx| {
7140 cx.activate(true);
7141 window.activate_window();
7142
7143 if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
7144 let follow_peer_id = room
7145 .read(cx)
7146 .remote_participants()
7147 .iter()
7148 .find(|(_, participant)| participant.user.id == follow_user_id)
7149 .map(|(_, p)| p.peer_id)
7150 .or_else(|| {
7151 // If we couldn't follow the given user, follow the host instead.
7152 let collaborator = workspace
7153 .project()
7154 .read(cx)
7155 .collaborators()
7156 .values()
7157 .find(|collaborator| collaborator.is_host)?;
7158 Some(collaborator.peer_id)
7159 });
7160
7161 if let Some(follow_peer_id) = follow_peer_id {
7162 workspace.follow(follow_peer_id, window, cx);
7163 }
7164 }
7165 })?;
7166
7167 anyhow::Ok(())
7168 })
7169}
7170
7171pub fn reload(reload: &Reload, cx: &mut App) {
7172 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
7173 let mut workspace_windows = cx
7174 .windows()
7175 .into_iter()
7176 .filter_map(|window| window.downcast::<Workspace>())
7177 .collect::<Vec<_>>();
7178
7179 // If multiple windows have unsaved changes, and need a save prompt,
7180 // prompt in the active window before switching to a different window.
7181 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
7182
7183 let mut prompt = None;
7184 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
7185 prompt = window
7186 .update(cx, |_, window, cx| {
7187 window.prompt(
7188 PromptLevel::Info,
7189 "Are you sure you want to restart?",
7190 None,
7191 &["Restart", "Cancel"],
7192 cx,
7193 )
7194 })
7195 .ok();
7196 }
7197
7198 let binary_path = reload.binary_path.clone();
7199 cx.spawn(async move |cx| {
7200 if let Some(prompt) = prompt {
7201 let answer = prompt.await?;
7202 if answer != 0 {
7203 return Ok(());
7204 }
7205 }
7206
7207 // If the user cancels any save prompt, then keep the app open.
7208 for window in workspace_windows {
7209 if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
7210 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
7211 }) {
7212 if !should_close.await? {
7213 return Ok(());
7214 }
7215 }
7216 }
7217
7218 cx.update(|cx| cx.restart(binary_path))
7219 })
7220 .detach_and_log_err(cx);
7221}
7222
7223fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
7224 let mut parts = value.split(',');
7225 let x: usize = parts.next()?.parse().ok()?;
7226 let y: usize = parts.next()?.parse().ok()?;
7227 Some(point(px(x as f32), px(y as f32)))
7228}
7229
7230fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
7231 let mut parts = value.split(',');
7232 let width: usize = parts.next()?.parse().ok()?;
7233 let height: usize = parts.next()?.parse().ok()?;
7234 Some(size(px(width as f32), px(height as f32)))
7235}
7236
7237pub fn client_side_decorations(
7238 element: impl IntoElement,
7239 window: &mut Window,
7240 cx: &mut App,
7241) -> Stateful<Div> {
7242 const BORDER_SIZE: Pixels = px(1.0);
7243 let decorations = window.window_decorations();
7244
7245 if matches!(decorations, Decorations::Client { .. }) {
7246 window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW);
7247 }
7248
7249 struct GlobalResizeEdge(ResizeEdge);
7250 impl Global for GlobalResizeEdge {}
7251
7252 div()
7253 .id("window-backdrop")
7254 .bg(transparent_black())
7255 .map(|div| match decorations {
7256 Decorations::Server => div,
7257 Decorations::Client { tiling, .. } => div
7258 .when(!(tiling.top || tiling.right), |div| {
7259 div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7260 })
7261 .when(!(tiling.top || tiling.left), |div| {
7262 div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7263 })
7264 .when(!(tiling.bottom || tiling.right), |div| {
7265 div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7266 })
7267 .when(!(tiling.bottom || tiling.left), |div| {
7268 div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7269 })
7270 .when(!tiling.top, |div| {
7271 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
7272 })
7273 .when(!tiling.bottom, |div| {
7274 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
7275 })
7276 .when(!tiling.left, |div| {
7277 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
7278 })
7279 .when(!tiling.right, |div| {
7280 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
7281 })
7282 .on_mouse_move(move |e, window, cx| {
7283 let size = window.window_bounds().get_bounds().size;
7284 let pos = e.position;
7285
7286 let new_edge =
7287 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
7288
7289 let edge = cx.try_global::<GlobalResizeEdge>();
7290 if new_edge != edge.map(|edge| edge.0) {
7291 window
7292 .window_handle()
7293 .update(cx, |workspace, _, cx| {
7294 cx.notify(workspace.entity_id());
7295 })
7296 .ok();
7297 }
7298 })
7299 .on_mouse_down(MouseButton::Left, move |e, window, _| {
7300 let size = window.window_bounds().get_bounds().size;
7301 let pos = e.position;
7302
7303 let edge = match resize_edge(
7304 pos,
7305 theme::CLIENT_SIDE_DECORATION_SHADOW,
7306 size,
7307 tiling,
7308 ) {
7309 Some(value) => value,
7310 None => return,
7311 };
7312
7313 window.start_window_resize(edge);
7314 }),
7315 })
7316 .size_full()
7317 .child(
7318 div()
7319 .cursor(CursorStyle::Arrow)
7320 .map(|div| match decorations {
7321 Decorations::Server => div,
7322 Decorations::Client { tiling } => div
7323 .border_color(cx.theme().colors().border)
7324 .when(!(tiling.top || tiling.right), |div| {
7325 div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7326 })
7327 .when(!(tiling.top || tiling.left), |div| {
7328 div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7329 })
7330 .when(!(tiling.bottom || tiling.right), |div| {
7331 div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7332 })
7333 .when(!(tiling.bottom || tiling.left), |div| {
7334 div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
7335 })
7336 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
7337 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
7338 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
7339 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
7340 .when(!tiling.is_tiled(), |div| {
7341 div.shadow(vec![gpui::BoxShadow {
7342 color: Hsla {
7343 h: 0.,
7344 s: 0.,
7345 l: 0.,
7346 a: 0.4,
7347 },
7348 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
7349 spread_radius: px(0.),
7350 offset: point(px(0.0), px(0.0)),
7351 }])
7352 }),
7353 })
7354 .on_mouse_move(|_e, _, cx| {
7355 cx.stop_propagation();
7356 })
7357 .size_full()
7358 .child(element),
7359 )
7360 .map(|div| match decorations {
7361 Decorations::Server => div,
7362 Decorations::Client { tiling, .. } => div.child(
7363 canvas(
7364 |_bounds, window, _| {
7365 window.insert_hitbox(
7366 Bounds::new(
7367 point(px(0.0), px(0.0)),
7368 window.window_bounds().get_bounds().size,
7369 ),
7370 HitboxBehavior::Normal,
7371 )
7372 },
7373 move |_bounds, hitbox, window, cx| {
7374 let mouse = window.mouse_position();
7375 let size = window.window_bounds().get_bounds().size;
7376 let Some(edge) =
7377 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
7378 else {
7379 return;
7380 };
7381 cx.set_global(GlobalResizeEdge(edge));
7382 window.set_cursor_style(
7383 match edge {
7384 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
7385 ResizeEdge::Left | ResizeEdge::Right => {
7386 CursorStyle::ResizeLeftRight
7387 }
7388 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
7389 CursorStyle::ResizeUpLeftDownRight
7390 }
7391 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
7392 CursorStyle::ResizeUpRightDownLeft
7393 }
7394 },
7395 Some(&hitbox),
7396 );
7397 },
7398 )
7399 .size_full()
7400 .absolute(),
7401 ),
7402 })
7403}
7404
7405fn resize_edge(
7406 pos: Point<Pixels>,
7407 shadow_size: Pixels,
7408 window_size: Size<Pixels>,
7409 tiling: Tiling,
7410) -> Option<ResizeEdge> {
7411 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
7412 if bounds.contains(&pos) {
7413 return None;
7414 }
7415
7416 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
7417 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
7418 if !tiling.top && top_left_bounds.contains(&pos) {
7419 return Some(ResizeEdge::TopLeft);
7420 }
7421
7422 let top_right_bounds = Bounds::new(
7423 Point::new(window_size.width - corner_size.width, px(0.)),
7424 corner_size,
7425 );
7426 if !tiling.top && top_right_bounds.contains(&pos) {
7427 return Some(ResizeEdge::TopRight);
7428 }
7429
7430 let bottom_left_bounds = Bounds::new(
7431 Point::new(px(0.), window_size.height - corner_size.height),
7432 corner_size,
7433 );
7434 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
7435 return Some(ResizeEdge::BottomLeft);
7436 }
7437
7438 let bottom_right_bounds = Bounds::new(
7439 Point::new(
7440 window_size.width - corner_size.width,
7441 window_size.height - corner_size.height,
7442 ),
7443 corner_size,
7444 );
7445 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
7446 return Some(ResizeEdge::BottomRight);
7447 }
7448
7449 if !tiling.top && pos.y < shadow_size {
7450 Some(ResizeEdge::Top)
7451 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
7452 Some(ResizeEdge::Bottom)
7453 } else if !tiling.left && pos.x < shadow_size {
7454 Some(ResizeEdge::Left)
7455 } else if !tiling.right && pos.x > window_size.width - shadow_size {
7456 Some(ResizeEdge::Right)
7457 } else {
7458 None
7459 }
7460}
7461
7462fn join_pane_into_active(
7463 active_pane: &Entity<Pane>,
7464 pane: &Entity<Pane>,
7465 window: &mut Window,
7466 cx: &mut App,
7467) {
7468 if pane == active_pane {
7469 return;
7470 } else if pane.read(cx).items_len() == 0 {
7471 pane.update(cx, |_, cx| {
7472 cx.emit(pane::Event::Remove {
7473 focus_on_pane: None,
7474 });
7475 })
7476 } else {
7477 move_all_items(pane, active_pane, window, cx);
7478 }
7479}
7480
7481fn move_all_items(
7482 from_pane: &Entity<Pane>,
7483 to_pane: &Entity<Pane>,
7484 window: &mut Window,
7485 cx: &mut App,
7486) {
7487 let destination_is_different = from_pane != to_pane;
7488 let mut moved_items = 0;
7489 for (item_ix, item_handle) in from_pane
7490 .read(cx)
7491 .items()
7492 .enumerate()
7493 .map(|(ix, item)| (ix, item.clone()))
7494 .collect::<Vec<_>>()
7495 {
7496 let ix = item_ix - moved_items;
7497 if destination_is_different {
7498 // Close item from previous pane
7499 from_pane.update(cx, |source, cx| {
7500 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
7501 });
7502 moved_items += 1;
7503 }
7504
7505 // This automatically removes duplicate items in the pane
7506 to_pane.update(cx, |destination, cx| {
7507 destination.add_item(item_handle, true, true, None, window, cx);
7508 window.focus(&destination.focus_handle(cx))
7509 });
7510 }
7511}
7512
7513pub fn move_item(
7514 source: &Entity<Pane>,
7515 destination: &Entity<Pane>,
7516 item_id_to_move: EntityId,
7517 destination_index: usize,
7518 activate: bool,
7519 window: &mut Window,
7520 cx: &mut App,
7521) {
7522 let Some((item_ix, item_handle)) = source
7523 .read(cx)
7524 .items()
7525 .enumerate()
7526 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
7527 .map(|(ix, item)| (ix, item.clone()))
7528 else {
7529 // Tab was closed during drag
7530 return;
7531 };
7532
7533 if source != destination {
7534 // Close item from previous pane
7535 source.update(cx, |source, cx| {
7536 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
7537 });
7538 }
7539
7540 // This automatically removes duplicate items in the pane
7541 destination.update(cx, |destination, cx| {
7542 destination.add_item_inner(
7543 item_handle,
7544 activate,
7545 activate,
7546 activate,
7547 Some(destination_index),
7548 window,
7549 cx,
7550 );
7551 if activate {
7552 window.focus(&destination.focus_handle(cx))
7553 }
7554 });
7555}
7556
7557pub fn move_active_item(
7558 source: &Entity<Pane>,
7559 destination: &Entity<Pane>,
7560 focus_destination: bool,
7561 close_if_empty: bool,
7562 window: &mut Window,
7563 cx: &mut App,
7564) {
7565 if source == destination {
7566 return;
7567 }
7568 let Some(active_item) = source.read(cx).active_item() else {
7569 return;
7570 };
7571 source.update(cx, |source_pane, cx| {
7572 let item_id = active_item.item_id();
7573 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
7574 destination.update(cx, |target_pane, cx| {
7575 target_pane.add_item(
7576 active_item,
7577 focus_destination,
7578 focus_destination,
7579 Some(target_pane.items_len()),
7580 window,
7581 cx,
7582 );
7583 });
7584 });
7585}
7586
7587#[derive(Debug)]
7588pub struct WorkspacePosition {
7589 pub window_bounds: Option<WindowBounds>,
7590 pub display: Option<Uuid>,
7591 pub centered_layout: bool,
7592}
7593
7594pub fn ssh_workspace_position_from_db(
7595 host: String,
7596 port: Option<u16>,
7597 user: Option<String>,
7598 paths_to_open: &[PathBuf],
7599 cx: &App,
7600) -> Task<Result<WorkspacePosition>> {
7601 let paths = paths_to_open
7602 .iter()
7603 .map(|path| path.to_string_lossy().to_string())
7604 .collect::<Vec<_>>();
7605
7606 cx.background_spawn(async move {
7607 let serialized_ssh_project = persistence::DB
7608 .get_or_create_ssh_project(host, port, paths, user)
7609 .await
7610 .context("fetching serialized ssh project")?;
7611 let serialized_workspace =
7612 persistence::DB.workspace_for_ssh_project(&serialized_ssh_project);
7613
7614 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
7615 (Some(WindowBounds::Windowed(bounds)), None)
7616 } else {
7617 let restorable_bounds = serialized_workspace
7618 .as_ref()
7619 .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
7620 .or_else(|| {
7621 let (display, window_bounds) = DB.last_window().log_err()?;
7622 Some((display?, window_bounds?))
7623 });
7624
7625 if let Some((serialized_display, serialized_status)) = restorable_bounds {
7626 (Some(serialized_status.0), Some(serialized_display))
7627 } else {
7628 (None, None)
7629 }
7630 };
7631
7632 let centered_layout = serialized_workspace
7633 .as_ref()
7634 .map(|w| w.centered_layout)
7635 .unwrap_or(false);
7636
7637 Ok(WorkspacePosition {
7638 window_bounds,
7639 display,
7640 centered_layout,
7641 })
7642 })
7643}
7644
7645pub fn with_active_or_new_workspace(
7646 cx: &mut App,
7647 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
7648) {
7649 match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
7650 Some(workspace) => {
7651 cx.defer(move |cx| {
7652 workspace
7653 .update(cx, |workspace, window, cx| f(workspace, window, cx))
7654 .log_err();
7655 });
7656 }
7657 None => {
7658 let app_state = AppState::global(cx);
7659 if let Some(app_state) = app_state.upgrade() {
7660 open_new(
7661 OpenOptions::default(),
7662 app_state,
7663 cx,
7664 move |workspace, window, cx| f(workspace, window, cx),
7665 )
7666 .detach_and_log_err(cx);
7667 }
7668 }
7669 }
7670}
7671
7672#[cfg(test)]
7673mod tests {
7674 use std::{cell::RefCell, rc::Rc};
7675
7676 use super::*;
7677 use crate::{
7678 dock::{PanelEvent, test::TestPanel},
7679 item::{
7680 ItemEvent,
7681 test::{TestItem, TestProjectItem},
7682 },
7683 };
7684 use fs::FakeFs;
7685 use gpui::{
7686 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
7687 UpdateGlobal, VisualTestContext, px,
7688 };
7689 use project::{Project, ProjectEntryId};
7690 use serde_json::json;
7691 use settings::SettingsStore;
7692
7693 #[gpui::test]
7694 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
7695 init_test(cx);
7696
7697 let fs = FakeFs::new(cx.executor());
7698 let project = Project::test(fs, [], cx).await;
7699 let (workspace, cx) =
7700 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7701
7702 // Adding an item with no ambiguity renders the tab without detail.
7703 let item1 = cx.new(|cx| {
7704 let mut item = TestItem::new(cx);
7705 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
7706 item
7707 });
7708 workspace.update_in(cx, |workspace, window, cx| {
7709 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
7710 });
7711 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
7712
7713 // Adding an item that creates ambiguity increases the level of detail on
7714 // both tabs.
7715 let item2 = cx.new_window_entity(|_window, cx| {
7716 let mut item = TestItem::new(cx);
7717 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
7718 item
7719 });
7720 workspace.update_in(cx, |workspace, window, cx| {
7721 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
7722 });
7723 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
7724 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
7725
7726 // Adding an item that creates ambiguity increases the level of detail only
7727 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
7728 // we stop at the highest detail available.
7729 let item3 = cx.new(|cx| {
7730 let mut item = TestItem::new(cx);
7731 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
7732 item
7733 });
7734 workspace.update_in(cx, |workspace, window, cx| {
7735 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
7736 });
7737 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
7738 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
7739 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
7740 }
7741
7742 #[gpui::test]
7743 async fn test_tracking_active_path(cx: &mut TestAppContext) {
7744 init_test(cx);
7745
7746 let fs = FakeFs::new(cx.executor());
7747 fs.insert_tree(
7748 "/root1",
7749 json!({
7750 "one.txt": "",
7751 "two.txt": "",
7752 }),
7753 )
7754 .await;
7755 fs.insert_tree(
7756 "/root2",
7757 json!({
7758 "three.txt": "",
7759 }),
7760 )
7761 .await;
7762
7763 let project = Project::test(fs, ["root1".as_ref()], cx).await;
7764 let (workspace, cx) =
7765 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7766 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7767 let worktree_id = project.update(cx, |project, cx| {
7768 project.worktrees(cx).next().unwrap().read(cx).id()
7769 });
7770
7771 let item1 = cx.new(|cx| {
7772 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
7773 });
7774 let item2 = cx.new(|cx| {
7775 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
7776 });
7777
7778 // Add an item to an empty pane
7779 workspace.update_in(cx, |workspace, window, cx| {
7780 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
7781 });
7782 project.update(cx, |project, cx| {
7783 assert_eq!(
7784 project.active_entry(),
7785 project
7786 .entry_for_path(&(worktree_id, "one.txt").into(), cx)
7787 .map(|e| e.id)
7788 );
7789 });
7790 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
7791
7792 // Add a second item to a non-empty pane
7793 workspace.update_in(cx, |workspace, window, cx| {
7794 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
7795 });
7796 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
7797 project.update(cx, |project, cx| {
7798 assert_eq!(
7799 project.active_entry(),
7800 project
7801 .entry_for_path(&(worktree_id, "two.txt").into(), cx)
7802 .map(|e| e.id)
7803 );
7804 });
7805
7806 // Close the active item
7807 pane.update_in(cx, |pane, window, cx| {
7808 pane.close_active_item(&Default::default(), window, cx)
7809 })
7810 .await
7811 .unwrap();
7812 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
7813 project.update(cx, |project, cx| {
7814 assert_eq!(
7815 project.active_entry(),
7816 project
7817 .entry_for_path(&(worktree_id, "one.txt").into(), cx)
7818 .map(|e| e.id)
7819 );
7820 });
7821
7822 // Add a project folder
7823 project
7824 .update(cx, |project, cx| {
7825 project.find_or_create_worktree("root2", true, cx)
7826 })
7827 .await
7828 .unwrap();
7829 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
7830
7831 // Remove a project folder
7832 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
7833 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
7834 }
7835
7836 #[gpui::test]
7837 async fn test_close_window(cx: &mut TestAppContext) {
7838 init_test(cx);
7839
7840 let fs = FakeFs::new(cx.executor());
7841 fs.insert_tree("/root", json!({ "one": "" })).await;
7842
7843 let project = Project::test(fs, ["root".as_ref()], cx).await;
7844 let (workspace, cx) =
7845 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7846
7847 // When there are no dirty items, there's nothing to do.
7848 let item1 = cx.new(TestItem::new);
7849 workspace.update_in(cx, |w, window, cx| {
7850 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
7851 });
7852 let task = workspace.update_in(cx, |w, window, cx| {
7853 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
7854 });
7855 assert!(task.await.unwrap());
7856
7857 // When there are dirty untitled items, prompt to save each one. If the user
7858 // cancels any prompt, then abort.
7859 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
7860 let item3 = cx.new(|cx| {
7861 TestItem::new(cx)
7862 .with_dirty(true)
7863 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
7864 });
7865 workspace.update_in(cx, |w, window, cx| {
7866 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
7867 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
7868 });
7869 let task = workspace.update_in(cx, |w, window, cx| {
7870 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
7871 });
7872 cx.executor().run_until_parked();
7873 cx.simulate_prompt_answer("Cancel"); // cancel save all
7874 cx.executor().run_until_parked();
7875 assert!(!cx.has_pending_prompt());
7876 assert!(!task.await.unwrap());
7877 }
7878
7879 #[gpui::test]
7880 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
7881 init_test(cx);
7882
7883 // Register TestItem as a serializable item
7884 cx.update(|cx| {
7885 register_serializable_item::<TestItem>(cx);
7886 });
7887
7888 let fs = FakeFs::new(cx.executor());
7889 fs.insert_tree("/root", json!({ "one": "" })).await;
7890
7891 let project = Project::test(fs, ["root".as_ref()], cx).await;
7892 let (workspace, cx) =
7893 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7894
7895 // When there are dirty untitled items, but they can serialize, then there is no prompt.
7896 let item1 = cx.new(|cx| {
7897 TestItem::new(cx)
7898 .with_dirty(true)
7899 .with_serialize(|| Some(Task::ready(Ok(()))))
7900 });
7901 let item2 = cx.new(|cx| {
7902 TestItem::new(cx)
7903 .with_dirty(true)
7904 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
7905 .with_serialize(|| Some(Task::ready(Ok(()))))
7906 });
7907 workspace.update_in(cx, |w, window, cx| {
7908 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
7909 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
7910 });
7911 let task = workspace.update_in(cx, |w, window, cx| {
7912 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
7913 });
7914 assert!(task.await.unwrap());
7915 }
7916
7917 #[gpui::test]
7918 async fn test_close_pane_items(cx: &mut TestAppContext) {
7919 init_test(cx);
7920
7921 let fs = FakeFs::new(cx.executor());
7922
7923 let project = Project::test(fs, None, cx).await;
7924 let (workspace, cx) =
7925 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
7926
7927 let item1 = cx.new(|cx| {
7928 TestItem::new(cx)
7929 .with_dirty(true)
7930 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
7931 });
7932 let item2 = cx.new(|cx| {
7933 TestItem::new(cx)
7934 .with_dirty(true)
7935 .with_conflict(true)
7936 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
7937 });
7938 let item3 = cx.new(|cx| {
7939 TestItem::new(cx)
7940 .with_dirty(true)
7941 .with_conflict(true)
7942 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
7943 });
7944 let item4 = cx.new(|cx| {
7945 TestItem::new(cx).with_dirty(true).with_project_items(&[{
7946 let project_item = TestProjectItem::new_untitled(cx);
7947 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
7948 project_item
7949 }])
7950 });
7951 let pane = workspace.update_in(cx, |workspace, window, cx| {
7952 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
7953 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
7954 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
7955 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
7956 workspace.active_pane().clone()
7957 });
7958
7959 let close_items = pane.update_in(cx, |pane, window, cx| {
7960 pane.activate_item(1, true, true, window, cx);
7961 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
7962 let item1_id = item1.item_id();
7963 let item3_id = item3.item_id();
7964 let item4_id = item4.item_id();
7965 pane.close_items(window, cx, SaveIntent::Close, move |id| {
7966 [item1_id, item3_id, item4_id].contains(&id)
7967 })
7968 });
7969 cx.executor().run_until_parked();
7970
7971 assert!(cx.has_pending_prompt());
7972 cx.simulate_prompt_answer("Save all");
7973
7974 cx.executor().run_until_parked();
7975
7976 // Item 1 is saved. There's a prompt to save item 3.
7977 pane.update(cx, |pane, cx| {
7978 assert_eq!(item1.read(cx).save_count, 1);
7979 assert_eq!(item1.read(cx).save_as_count, 0);
7980 assert_eq!(item1.read(cx).reload_count, 0);
7981 assert_eq!(pane.items_len(), 3);
7982 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
7983 });
7984 assert!(cx.has_pending_prompt());
7985
7986 // Cancel saving item 3.
7987 cx.simulate_prompt_answer("Discard");
7988 cx.executor().run_until_parked();
7989
7990 // Item 3 is reloaded. There's a prompt to save item 4.
7991 pane.update(cx, |pane, cx| {
7992 assert_eq!(item3.read(cx).save_count, 0);
7993 assert_eq!(item3.read(cx).save_as_count, 0);
7994 assert_eq!(item3.read(cx).reload_count, 1);
7995 assert_eq!(pane.items_len(), 2);
7996 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
7997 });
7998
7999 // There's a prompt for a path for item 4.
8000 cx.simulate_new_path_selection(|_| Some(Default::default()));
8001 close_items.await.unwrap();
8002
8003 // The requested items are closed.
8004 pane.update(cx, |pane, cx| {
8005 assert_eq!(item4.read(cx).save_count, 0);
8006 assert_eq!(item4.read(cx).save_as_count, 1);
8007 assert_eq!(item4.read(cx).reload_count, 0);
8008 assert_eq!(pane.items_len(), 1);
8009 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
8010 });
8011 }
8012
8013 #[gpui::test]
8014 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
8015 init_test(cx);
8016
8017 let fs = FakeFs::new(cx.executor());
8018 let project = Project::test(fs, [], cx).await;
8019 let (workspace, cx) =
8020 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8021
8022 // Create several workspace items with single project entries, and two
8023 // workspace items with multiple project entries.
8024 let single_entry_items = (0..=4)
8025 .map(|project_entry_id| {
8026 cx.new(|cx| {
8027 TestItem::new(cx)
8028 .with_dirty(true)
8029 .with_project_items(&[dirty_project_item(
8030 project_entry_id,
8031 &format!("{project_entry_id}.txt"),
8032 cx,
8033 )])
8034 })
8035 })
8036 .collect::<Vec<_>>();
8037 let item_2_3 = cx.new(|cx| {
8038 TestItem::new(cx)
8039 .with_dirty(true)
8040 .with_singleton(false)
8041 .with_project_items(&[
8042 single_entry_items[2].read(cx).project_items[0].clone(),
8043 single_entry_items[3].read(cx).project_items[0].clone(),
8044 ])
8045 });
8046 let item_3_4 = cx.new(|cx| {
8047 TestItem::new(cx)
8048 .with_dirty(true)
8049 .with_singleton(false)
8050 .with_project_items(&[
8051 single_entry_items[3].read(cx).project_items[0].clone(),
8052 single_entry_items[4].read(cx).project_items[0].clone(),
8053 ])
8054 });
8055
8056 // Create two panes that contain the following project entries:
8057 // left pane:
8058 // multi-entry items: (2, 3)
8059 // single-entry items: 0, 2, 3, 4
8060 // right pane:
8061 // single-entry items: 4, 1
8062 // multi-entry items: (3, 4)
8063 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
8064 let left_pane = workspace.active_pane().clone();
8065 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
8066 workspace.add_item_to_active_pane(
8067 single_entry_items[0].boxed_clone(),
8068 None,
8069 true,
8070 window,
8071 cx,
8072 );
8073 workspace.add_item_to_active_pane(
8074 single_entry_items[2].boxed_clone(),
8075 None,
8076 true,
8077 window,
8078 cx,
8079 );
8080 workspace.add_item_to_active_pane(
8081 single_entry_items[3].boxed_clone(),
8082 None,
8083 true,
8084 window,
8085 cx,
8086 );
8087 workspace.add_item_to_active_pane(
8088 single_entry_items[4].boxed_clone(),
8089 None,
8090 true,
8091 window,
8092 cx,
8093 );
8094
8095 let right_pane = workspace
8096 .split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx)
8097 .unwrap();
8098
8099 right_pane.update(cx, |pane, cx| {
8100 pane.add_item(
8101 single_entry_items[1].boxed_clone(),
8102 true,
8103 true,
8104 None,
8105 window,
8106 cx,
8107 );
8108 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
8109 });
8110
8111 (left_pane, right_pane)
8112 });
8113
8114 cx.focus(&right_pane);
8115
8116 let mut close = right_pane.update_in(cx, |pane, window, cx| {
8117 pane.close_all_items(&CloseAllItems::default(), window, cx)
8118 .unwrap()
8119 });
8120 cx.executor().run_until_parked();
8121
8122 let msg = cx.pending_prompt().unwrap().0;
8123 assert!(msg.contains("1.txt"));
8124 assert!(!msg.contains("2.txt"));
8125 assert!(!msg.contains("3.txt"));
8126 assert!(!msg.contains("4.txt"));
8127
8128 cx.simulate_prompt_answer("Cancel");
8129 close.await;
8130
8131 left_pane
8132 .update_in(cx, |left_pane, window, cx| {
8133 left_pane.close_item_by_id(
8134 single_entry_items[3].entity_id(),
8135 SaveIntent::Skip,
8136 window,
8137 cx,
8138 )
8139 })
8140 .await
8141 .unwrap();
8142
8143 close = right_pane.update_in(cx, |pane, window, cx| {
8144 pane.close_all_items(&CloseAllItems::default(), window, cx)
8145 .unwrap()
8146 });
8147 cx.executor().run_until_parked();
8148
8149 let details = cx.pending_prompt().unwrap().1;
8150 assert!(details.contains("1.txt"));
8151 assert!(!details.contains("2.txt"));
8152 assert!(details.contains("3.txt"));
8153 // ideally this assertion could be made, but today we can only
8154 // save whole items not project items, so the orphaned item 3 causes
8155 // 4 to be saved too.
8156 // assert!(!details.contains("4.txt"));
8157
8158 cx.simulate_prompt_answer("Save all");
8159
8160 cx.executor().run_until_parked();
8161 close.await;
8162 right_pane.read_with(cx, |pane, _| {
8163 assert_eq!(pane.items_len(), 0);
8164 });
8165 }
8166
8167 #[gpui::test]
8168 async fn test_autosave(cx: &mut gpui::TestAppContext) {
8169 init_test(cx);
8170
8171 let fs = FakeFs::new(cx.executor());
8172 let project = Project::test(fs, [], cx).await;
8173 let (workspace, cx) =
8174 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8175 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8176
8177 let item = cx.new(|cx| {
8178 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
8179 });
8180 let item_id = item.entity_id();
8181 workspace.update_in(cx, |workspace, window, cx| {
8182 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
8183 });
8184
8185 // Autosave on window change.
8186 item.update(cx, |item, cx| {
8187 SettingsStore::update_global(cx, |settings, cx| {
8188 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
8189 settings.autosave = Some(AutosaveSetting::OnWindowChange);
8190 })
8191 });
8192 item.is_dirty = true;
8193 });
8194
8195 // Deactivating the window saves the file.
8196 cx.deactivate_window();
8197 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
8198
8199 // Re-activating the window doesn't save the file.
8200 cx.update(|window, _| window.activate_window());
8201 cx.executor().run_until_parked();
8202 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
8203
8204 // Autosave on focus change.
8205 item.update_in(cx, |item, window, cx| {
8206 cx.focus_self(window);
8207 SettingsStore::update_global(cx, |settings, cx| {
8208 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
8209 settings.autosave = Some(AutosaveSetting::OnFocusChange);
8210 })
8211 });
8212 item.is_dirty = true;
8213 });
8214
8215 // Blurring the item saves the file.
8216 item.update_in(cx, |_, window, _| window.blur());
8217 cx.executor().run_until_parked();
8218 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
8219
8220 // Deactivating the window still saves the file.
8221 item.update_in(cx, |item, window, cx| {
8222 cx.focus_self(window);
8223 item.is_dirty = true;
8224 });
8225 cx.deactivate_window();
8226 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
8227
8228 // Autosave after delay.
8229 item.update(cx, |item, cx| {
8230 SettingsStore::update_global(cx, |settings, cx| {
8231 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
8232 settings.autosave = Some(AutosaveSetting::AfterDelay { milliseconds: 500 });
8233 })
8234 });
8235 item.is_dirty = true;
8236 cx.emit(ItemEvent::Edit);
8237 });
8238
8239 // Delay hasn't fully expired, so the file is still dirty and unsaved.
8240 cx.executor().advance_clock(Duration::from_millis(250));
8241 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
8242
8243 // After delay expires, the file is saved.
8244 cx.executor().advance_clock(Duration::from_millis(250));
8245 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
8246
8247 // Autosave on focus change, ensuring closing the tab counts as such.
8248 item.update(cx, |item, cx| {
8249 SettingsStore::update_global(cx, |settings, cx| {
8250 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
8251 settings.autosave = Some(AutosaveSetting::OnFocusChange);
8252 })
8253 });
8254 item.is_dirty = true;
8255 for project_item in &mut item.project_items {
8256 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
8257 }
8258 });
8259
8260 pane.update_in(cx, |pane, window, cx| {
8261 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
8262 })
8263 .await
8264 .unwrap();
8265 assert!(!cx.has_pending_prompt());
8266 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
8267
8268 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
8269 workspace.update_in(cx, |workspace, window, cx| {
8270 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
8271 });
8272 item.update_in(cx, |item, window, cx| {
8273 item.project_items[0].update(cx, |item, _| {
8274 item.entry_id = None;
8275 });
8276 item.is_dirty = true;
8277 window.blur();
8278 });
8279 cx.run_until_parked();
8280 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
8281
8282 // Ensure autosave is prevented for deleted files also when closing the buffer.
8283 let _close_items = pane.update_in(cx, |pane, window, cx| {
8284 pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
8285 });
8286 cx.run_until_parked();
8287 assert!(cx.has_pending_prompt());
8288 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
8289 }
8290
8291 #[gpui::test]
8292 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
8293 init_test(cx);
8294
8295 let fs = FakeFs::new(cx.executor());
8296
8297 let project = Project::test(fs, [], cx).await;
8298 let (workspace, cx) =
8299 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8300
8301 let item = cx.new(|cx| {
8302 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
8303 });
8304 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8305 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
8306 let toolbar_notify_count = Rc::new(RefCell::new(0));
8307
8308 workspace.update_in(cx, |workspace, window, cx| {
8309 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
8310 let toolbar_notification_count = toolbar_notify_count.clone();
8311 cx.observe_in(&toolbar, window, move |_, _, _, _| {
8312 *toolbar_notification_count.borrow_mut() += 1
8313 })
8314 .detach();
8315 });
8316
8317 pane.read_with(cx, |pane, _| {
8318 assert!(!pane.can_navigate_backward());
8319 assert!(!pane.can_navigate_forward());
8320 });
8321
8322 item.update_in(cx, |item, _, cx| {
8323 item.set_state("one".to_string(), cx);
8324 });
8325
8326 // Toolbar must be notified to re-render the navigation buttons
8327 assert_eq!(*toolbar_notify_count.borrow(), 1);
8328
8329 pane.read_with(cx, |pane, _| {
8330 assert!(pane.can_navigate_backward());
8331 assert!(!pane.can_navigate_forward());
8332 });
8333
8334 workspace
8335 .update_in(cx, |workspace, window, cx| {
8336 workspace.go_back(pane.downgrade(), window, cx)
8337 })
8338 .await
8339 .unwrap();
8340
8341 assert_eq!(*toolbar_notify_count.borrow(), 2);
8342 pane.read_with(cx, |pane, _| {
8343 assert!(!pane.can_navigate_backward());
8344 assert!(pane.can_navigate_forward());
8345 });
8346 }
8347
8348 #[gpui::test]
8349 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
8350 init_test(cx);
8351 let fs = FakeFs::new(cx.executor());
8352
8353 let project = Project::test(fs, [], cx).await;
8354 let (workspace, cx) =
8355 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8356
8357 let panel = workspace.update_in(cx, |workspace, window, cx| {
8358 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
8359 workspace.add_panel(panel.clone(), window, cx);
8360
8361 workspace
8362 .right_dock()
8363 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
8364
8365 panel
8366 });
8367
8368 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8369 pane.update_in(cx, |pane, window, cx| {
8370 let item = cx.new(TestItem::new);
8371 pane.add_item(Box::new(item), true, true, None, window, cx);
8372 });
8373
8374 // Transfer focus from center to panel
8375 workspace.update_in(cx, |workspace, window, cx| {
8376 workspace.toggle_panel_focus::<TestPanel>(window, cx);
8377 });
8378
8379 workspace.update_in(cx, |workspace, window, cx| {
8380 assert!(workspace.right_dock().read(cx).is_open());
8381 assert!(!panel.is_zoomed(window, cx));
8382 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8383 });
8384
8385 // Transfer focus from panel to center
8386 workspace.update_in(cx, |workspace, window, cx| {
8387 workspace.toggle_panel_focus::<TestPanel>(window, cx);
8388 });
8389
8390 workspace.update_in(cx, |workspace, window, cx| {
8391 assert!(workspace.right_dock().read(cx).is_open());
8392 assert!(!panel.is_zoomed(window, cx));
8393 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8394 });
8395
8396 // Close the dock
8397 workspace.update_in(cx, |workspace, window, cx| {
8398 workspace.toggle_dock(DockPosition::Right, window, cx);
8399 });
8400
8401 workspace.update_in(cx, |workspace, window, cx| {
8402 assert!(!workspace.right_dock().read(cx).is_open());
8403 assert!(!panel.is_zoomed(window, cx));
8404 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8405 });
8406
8407 // Open the dock
8408 workspace.update_in(cx, |workspace, window, cx| {
8409 workspace.toggle_dock(DockPosition::Right, window, cx);
8410 });
8411
8412 workspace.update_in(cx, |workspace, window, cx| {
8413 assert!(workspace.right_dock().read(cx).is_open());
8414 assert!(!panel.is_zoomed(window, cx));
8415 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8416 });
8417
8418 // Focus and zoom panel
8419 panel.update_in(cx, |panel, window, cx| {
8420 cx.focus_self(window);
8421 panel.set_zoomed(true, window, cx)
8422 });
8423
8424 workspace.update_in(cx, |workspace, window, cx| {
8425 assert!(workspace.right_dock().read(cx).is_open());
8426 assert!(panel.is_zoomed(window, cx));
8427 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8428 });
8429
8430 // Transfer focus to the center closes the dock
8431 workspace.update_in(cx, |workspace, window, cx| {
8432 workspace.toggle_panel_focus::<TestPanel>(window, cx);
8433 });
8434
8435 workspace.update_in(cx, |workspace, window, cx| {
8436 assert!(!workspace.right_dock().read(cx).is_open());
8437 assert!(panel.is_zoomed(window, cx));
8438 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8439 });
8440
8441 // Transferring focus back to the panel keeps it zoomed
8442 workspace.update_in(cx, |workspace, window, cx| {
8443 workspace.toggle_panel_focus::<TestPanel>(window, cx);
8444 });
8445
8446 workspace.update_in(cx, |workspace, window, cx| {
8447 assert!(workspace.right_dock().read(cx).is_open());
8448 assert!(panel.is_zoomed(window, cx));
8449 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8450 });
8451
8452 // Close the dock while it is zoomed
8453 workspace.update_in(cx, |workspace, window, cx| {
8454 workspace.toggle_dock(DockPosition::Right, window, cx)
8455 });
8456
8457 workspace.update_in(cx, |workspace, window, cx| {
8458 assert!(!workspace.right_dock().read(cx).is_open());
8459 assert!(panel.is_zoomed(window, cx));
8460 assert!(workspace.zoomed.is_none());
8461 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8462 });
8463
8464 // Opening the dock, when it's zoomed, retains focus
8465 workspace.update_in(cx, |workspace, window, cx| {
8466 workspace.toggle_dock(DockPosition::Right, window, cx)
8467 });
8468
8469 workspace.update_in(cx, |workspace, window, cx| {
8470 assert!(workspace.right_dock().read(cx).is_open());
8471 assert!(panel.is_zoomed(window, cx));
8472 assert!(workspace.zoomed.is_some());
8473 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
8474 });
8475
8476 // Unzoom and close the panel, zoom the active pane.
8477 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
8478 workspace.update_in(cx, |workspace, window, cx| {
8479 workspace.toggle_dock(DockPosition::Right, window, cx)
8480 });
8481 pane.update_in(cx, |pane, window, cx| {
8482 pane.toggle_zoom(&Default::default(), window, cx)
8483 });
8484
8485 // Opening a dock unzooms the pane.
8486 workspace.update_in(cx, |workspace, window, cx| {
8487 workspace.toggle_dock(DockPosition::Right, window, cx)
8488 });
8489 workspace.update_in(cx, |workspace, window, cx| {
8490 let pane = pane.read(cx);
8491 assert!(!pane.is_zoomed());
8492 assert!(!pane.focus_handle(cx).is_focused(window));
8493 assert!(workspace.right_dock().read(cx).is_open());
8494 assert!(workspace.zoomed.is_none());
8495 });
8496 }
8497
8498 #[gpui::test]
8499 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
8500 init_test(cx);
8501
8502 let fs = FakeFs::new(cx.executor());
8503
8504 let project = Project::test(fs, None, cx).await;
8505 let (workspace, cx) =
8506 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8507
8508 // Let's arrange the panes like this:
8509 //
8510 // +-----------------------+
8511 // | top |
8512 // +------+--------+-------+
8513 // | left | center | right |
8514 // +------+--------+-------+
8515 // | bottom |
8516 // +-----------------------+
8517
8518 let top_item = cx.new(|cx| {
8519 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
8520 });
8521 let bottom_item = cx.new(|cx| {
8522 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
8523 });
8524 let left_item = cx.new(|cx| {
8525 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
8526 });
8527 let right_item = cx.new(|cx| {
8528 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
8529 });
8530 let center_item = cx.new(|cx| {
8531 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
8532 });
8533
8534 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
8535 let top_pane_id = workspace.active_pane().entity_id();
8536 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
8537 workspace.split_pane(
8538 workspace.active_pane().clone(),
8539 SplitDirection::Down,
8540 window,
8541 cx,
8542 );
8543 top_pane_id
8544 });
8545 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
8546 let bottom_pane_id = workspace.active_pane().entity_id();
8547 workspace.add_item_to_active_pane(
8548 Box::new(bottom_item.clone()),
8549 None,
8550 false,
8551 window,
8552 cx,
8553 );
8554 workspace.split_pane(
8555 workspace.active_pane().clone(),
8556 SplitDirection::Up,
8557 window,
8558 cx,
8559 );
8560 bottom_pane_id
8561 });
8562 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
8563 let left_pane_id = workspace.active_pane().entity_id();
8564 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
8565 workspace.split_pane(
8566 workspace.active_pane().clone(),
8567 SplitDirection::Right,
8568 window,
8569 cx,
8570 );
8571 left_pane_id
8572 });
8573 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
8574 let right_pane_id = workspace.active_pane().entity_id();
8575 workspace.add_item_to_active_pane(
8576 Box::new(right_item.clone()),
8577 None,
8578 false,
8579 window,
8580 cx,
8581 );
8582 workspace.split_pane(
8583 workspace.active_pane().clone(),
8584 SplitDirection::Left,
8585 window,
8586 cx,
8587 );
8588 right_pane_id
8589 });
8590 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
8591 let center_pane_id = workspace.active_pane().entity_id();
8592 workspace.add_item_to_active_pane(
8593 Box::new(center_item.clone()),
8594 None,
8595 false,
8596 window,
8597 cx,
8598 );
8599 center_pane_id
8600 });
8601 cx.executor().run_until_parked();
8602
8603 workspace.update_in(cx, |workspace, window, cx| {
8604 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
8605
8606 // Join into next from center pane into right
8607 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
8608 });
8609
8610 workspace.update_in(cx, |workspace, window, cx| {
8611 let active_pane = workspace.active_pane();
8612 assert_eq!(right_pane_id, active_pane.entity_id());
8613 assert_eq!(2, active_pane.read(cx).items_len());
8614 let item_ids_in_pane =
8615 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
8616 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
8617 assert!(item_ids_in_pane.contains(&right_item.item_id()));
8618
8619 // Join into next from right pane into bottom
8620 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
8621 });
8622
8623 workspace.update_in(cx, |workspace, window, cx| {
8624 let active_pane = workspace.active_pane();
8625 assert_eq!(bottom_pane_id, active_pane.entity_id());
8626 assert_eq!(3, active_pane.read(cx).items_len());
8627 let item_ids_in_pane =
8628 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
8629 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
8630 assert!(item_ids_in_pane.contains(&right_item.item_id()));
8631 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
8632
8633 // Join into next from bottom pane into left
8634 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
8635 });
8636
8637 workspace.update_in(cx, |workspace, window, cx| {
8638 let active_pane = workspace.active_pane();
8639 assert_eq!(left_pane_id, active_pane.entity_id());
8640 assert_eq!(4, active_pane.read(cx).items_len());
8641 let item_ids_in_pane =
8642 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
8643 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
8644 assert!(item_ids_in_pane.contains(&right_item.item_id()));
8645 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
8646 assert!(item_ids_in_pane.contains(&left_item.item_id()));
8647
8648 // Join into next from left pane into top
8649 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
8650 });
8651
8652 workspace.update_in(cx, |workspace, window, cx| {
8653 let active_pane = workspace.active_pane();
8654 assert_eq!(top_pane_id, active_pane.entity_id());
8655 assert_eq!(5, active_pane.read(cx).items_len());
8656 let item_ids_in_pane =
8657 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
8658 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
8659 assert!(item_ids_in_pane.contains(&right_item.item_id()));
8660 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
8661 assert!(item_ids_in_pane.contains(&left_item.item_id()));
8662 assert!(item_ids_in_pane.contains(&top_item.item_id()));
8663
8664 // Single pane left: no-op
8665 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
8666 });
8667
8668 workspace.update(cx, |workspace, _cx| {
8669 let active_pane = workspace.active_pane();
8670 assert_eq!(top_pane_id, active_pane.entity_id());
8671 });
8672 }
8673
8674 fn add_an_item_to_active_pane(
8675 cx: &mut VisualTestContext,
8676 workspace: &Entity<Workspace>,
8677 item_id: u64,
8678 ) -> Entity<TestItem> {
8679 let item = cx.new(|cx| {
8680 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
8681 item_id,
8682 "item{item_id}.txt",
8683 cx,
8684 )])
8685 });
8686 workspace.update_in(cx, |workspace, window, cx| {
8687 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
8688 });
8689 return item;
8690 }
8691
8692 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
8693 return workspace.update_in(cx, |workspace, window, cx| {
8694 let new_pane = workspace.split_pane(
8695 workspace.active_pane().clone(),
8696 SplitDirection::Right,
8697 window,
8698 cx,
8699 );
8700 new_pane
8701 });
8702 }
8703
8704 #[gpui::test]
8705 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
8706 init_test(cx);
8707 let fs = FakeFs::new(cx.executor());
8708 let project = Project::test(fs, None, cx).await;
8709 let (workspace, cx) =
8710 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8711
8712 add_an_item_to_active_pane(cx, &workspace, 1);
8713 split_pane(cx, &workspace);
8714 add_an_item_to_active_pane(cx, &workspace, 2);
8715 split_pane(cx, &workspace); // empty pane
8716 split_pane(cx, &workspace);
8717 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
8718
8719 cx.executor().run_until_parked();
8720
8721 workspace.update(cx, |workspace, cx| {
8722 let num_panes = workspace.panes().len();
8723 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
8724 let active_item = workspace
8725 .active_pane()
8726 .read(cx)
8727 .active_item()
8728 .expect("item is in focus");
8729
8730 assert_eq!(num_panes, 4);
8731 assert_eq!(num_items_in_current_pane, 1);
8732 assert_eq!(active_item.item_id(), last_item.item_id());
8733 });
8734
8735 workspace.update_in(cx, |workspace, window, cx| {
8736 workspace.join_all_panes(window, cx);
8737 });
8738
8739 workspace.update(cx, |workspace, cx| {
8740 let num_panes = workspace.panes().len();
8741 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
8742 let active_item = workspace
8743 .active_pane()
8744 .read(cx)
8745 .active_item()
8746 .expect("item is in focus");
8747
8748 assert_eq!(num_panes, 1);
8749 assert_eq!(num_items_in_current_pane, 3);
8750 assert_eq!(active_item.item_id(), last_item.item_id());
8751 });
8752 }
8753 struct TestModal(FocusHandle);
8754
8755 impl TestModal {
8756 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
8757 Self(cx.focus_handle())
8758 }
8759 }
8760
8761 impl EventEmitter<DismissEvent> for TestModal {}
8762
8763 impl Focusable for TestModal {
8764 fn focus_handle(&self, _cx: &App) -> FocusHandle {
8765 self.0.clone()
8766 }
8767 }
8768
8769 impl ModalView for TestModal {}
8770
8771 impl Render for TestModal {
8772 fn render(
8773 &mut self,
8774 _window: &mut Window,
8775 _cx: &mut Context<TestModal>,
8776 ) -> impl IntoElement {
8777 div().track_focus(&self.0)
8778 }
8779 }
8780
8781 #[gpui::test]
8782 async fn test_panels(cx: &mut gpui::TestAppContext) {
8783 init_test(cx);
8784 let fs = FakeFs::new(cx.executor());
8785
8786 let project = Project::test(fs, [], cx).await;
8787 let (workspace, cx) =
8788 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8789
8790 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
8791 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, cx));
8792 workspace.add_panel(panel_1.clone(), window, cx);
8793 workspace.toggle_dock(DockPosition::Left, window, cx);
8794 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
8795 workspace.add_panel(panel_2.clone(), window, cx);
8796 workspace.toggle_dock(DockPosition::Right, window, cx);
8797
8798 let left_dock = workspace.left_dock();
8799 assert_eq!(
8800 left_dock.read(cx).visible_panel().unwrap().panel_id(),
8801 panel_1.panel_id()
8802 );
8803 assert_eq!(
8804 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
8805 panel_1.size(window, cx)
8806 );
8807
8808 left_dock.update(cx, |left_dock, cx| {
8809 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
8810 });
8811 assert_eq!(
8812 workspace
8813 .right_dock()
8814 .read(cx)
8815 .visible_panel()
8816 .unwrap()
8817 .panel_id(),
8818 panel_2.panel_id(),
8819 );
8820
8821 (panel_1, panel_2)
8822 });
8823
8824 // Move panel_1 to the right
8825 panel_1.update_in(cx, |panel_1, window, cx| {
8826 panel_1.set_position(DockPosition::Right, window, cx)
8827 });
8828
8829 workspace.update_in(cx, |workspace, window, cx| {
8830 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
8831 // Since it was the only panel on the left, the left dock should now be closed.
8832 assert!(!workspace.left_dock().read(cx).is_open());
8833 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
8834 let right_dock = workspace.right_dock();
8835 assert_eq!(
8836 right_dock.read(cx).visible_panel().unwrap().panel_id(),
8837 panel_1.panel_id()
8838 );
8839 assert_eq!(
8840 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
8841 px(1337.)
8842 );
8843
8844 // Now we move panel_2 to the left
8845 panel_2.set_position(DockPosition::Left, window, cx);
8846 });
8847
8848 workspace.update(cx, |workspace, cx| {
8849 // Since panel_2 was not visible on the right, we don't open the left dock.
8850 assert!(!workspace.left_dock().read(cx).is_open());
8851 // And the right dock is unaffected in its displaying of panel_1
8852 assert!(workspace.right_dock().read(cx).is_open());
8853 assert_eq!(
8854 workspace
8855 .right_dock()
8856 .read(cx)
8857 .visible_panel()
8858 .unwrap()
8859 .panel_id(),
8860 panel_1.panel_id(),
8861 );
8862 });
8863
8864 // Move panel_1 back to the left
8865 panel_1.update_in(cx, |panel_1, window, cx| {
8866 panel_1.set_position(DockPosition::Left, window, cx)
8867 });
8868
8869 workspace.update_in(cx, |workspace, window, cx| {
8870 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
8871 let left_dock = workspace.left_dock();
8872 assert!(left_dock.read(cx).is_open());
8873 assert_eq!(
8874 left_dock.read(cx).visible_panel().unwrap().panel_id(),
8875 panel_1.panel_id()
8876 );
8877 assert_eq!(
8878 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
8879 px(1337.)
8880 );
8881 // And the right dock should be closed as it no longer has any panels.
8882 assert!(!workspace.right_dock().read(cx).is_open());
8883
8884 // Now we move panel_1 to the bottom
8885 panel_1.set_position(DockPosition::Bottom, window, cx);
8886 });
8887
8888 workspace.update_in(cx, |workspace, window, cx| {
8889 // Since panel_1 was visible on the left, we close the left dock.
8890 assert!(!workspace.left_dock().read(cx).is_open());
8891 // The bottom dock is sized based on the panel's default size,
8892 // since the panel orientation changed from vertical to horizontal.
8893 let bottom_dock = workspace.bottom_dock();
8894 assert_eq!(
8895 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
8896 panel_1.size(window, cx),
8897 );
8898 // Close bottom dock and move panel_1 back to the left.
8899 bottom_dock.update(cx, |bottom_dock, cx| {
8900 bottom_dock.set_open(false, window, cx)
8901 });
8902 panel_1.set_position(DockPosition::Left, window, cx);
8903 });
8904
8905 // Emit activated event on panel 1
8906 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
8907
8908 // Now the left dock is open and panel_1 is active and focused.
8909 workspace.update_in(cx, |workspace, window, cx| {
8910 let left_dock = workspace.left_dock();
8911 assert!(left_dock.read(cx).is_open());
8912 assert_eq!(
8913 left_dock.read(cx).visible_panel().unwrap().panel_id(),
8914 panel_1.panel_id(),
8915 );
8916 assert!(panel_1.focus_handle(cx).is_focused(window));
8917 });
8918
8919 // Emit closed event on panel 2, which is not active
8920 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
8921
8922 // Wo don't close the left dock, because panel_2 wasn't the active panel
8923 workspace.update(cx, |workspace, cx| {
8924 let left_dock = workspace.left_dock();
8925 assert!(left_dock.read(cx).is_open());
8926 assert_eq!(
8927 left_dock.read(cx).visible_panel().unwrap().panel_id(),
8928 panel_1.panel_id(),
8929 );
8930 });
8931
8932 // Emitting a ZoomIn event shows the panel as zoomed.
8933 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
8934 workspace.read_with(cx, |workspace, _| {
8935 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
8936 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
8937 });
8938
8939 // Move panel to another dock while it is zoomed
8940 panel_1.update_in(cx, |panel, window, cx| {
8941 panel.set_position(DockPosition::Right, window, cx)
8942 });
8943 workspace.read_with(cx, |workspace, _| {
8944 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
8945
8946 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
8947 });
8948
8949 // This is a helper for getting a:
8950 // - valid focus on an element,
8951 // - that isn't a part of the panes and panels system of the Workspace,
8952 // - and doesn't trigger the 'on_focus_lost' API.
8953 let focus_other_view = {
8954 let workspace = workspace.clone();
8955 move |cx: &mut VisualTestContext| {
8956 workspace.update_in(cx, |workspace, window, cx| {
8957 if let Some(_) = workspace.active_modal::<TestModal>(cx) {
8958 workspace.toggle_modal(window, cx, TestModal::new);
8959 workspace.toggle_modal(window, cx, TestModal::new);
8960 } else {
8961 workspace.toggle_modal(window, cx, TestModal::new);
8962 }
8963 })
8964 }
8965 };
8966
8967 // If focus is transferred to another view that's not a panel or another pane, we still show
8968 // the panel as zoomed.
8969 focus_other_view(cx);
8970 workspace.read_with(cx, |workspace, _| {
8971 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
8972 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
8973 });
8974
8975 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
8976 workspace.update_in(cx, |_workspace, window, cx| {
8977 cx.focus_self(window);
8978 });
8979 workspace.read_with(cx, |workspace, _| {
8980 assert_eq!(workspace.zoomed, None);
8981 assert_eq!(workspace.zoomed_position, None);
8982 });
8983
8984 // If focus is transferred again to another view that's not a panel or a pane, we won't
8985 // show the panel as zoomed because it wasn't zoomed before.
8986 focus_other_view(cx);
8987 workspace.read_with(cx, |workspace, _| {
8988 assert_eq!(workspace.zoomed, None);
8989 assert_eq!(workspace.zoomed_position, None);
8990 });
8991
8992 // When the panel is activated, it is zoomed again.
8993 cx.dispatch_action(ToggleRightDock);
8994 workspace.read_with(cx, |workspace, _| {
8995 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
8996 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
8997 });
8998
8999 // Emitting a ZoomOut event unzooms the panel.
9000 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
9001 workspace.read_with(cx, |workspace, _| {
9002 assert_eq!(workspace.zoomed, None);
9003 assert_eq!(workspace.zoomed_position, None);
9004 });
9005
9006 // Emit closed event on panel 1, which is active
9007 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
9008
9009 // Now the left dock is closed, because panel_1 was the active panel
9010 workspace.update(cx, |workspace, cx| {
9011 let right_dock = workspace.right_dock();
9012 assert!(!right_dock.read(cx).is_open());
9013 });
9014 }
9015
9016 #[gpui::test]
9017 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
9018 init_test(cx);
9019
9020 let fs = FakeFs::new(cx.background_executor.clone());
9021 let project = Project::test(fs, [], cx).await;
9022 let (workspace, cx) =
9023 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9024 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9025
9026 let dirty_regular_buffer = cx.new(|cx| {
9027 TestItem::new(cx)
9028 .with_dirty(true)
9029 .with_label("1.txt")
9030 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
9031 });
9032 let dirty_regular_buffer_2 = cx.new(|cx| {
9033 TestItem::new(cx)
9034 .with_dirty(true)
9035 .with_label("2.txt")
9036 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
9037 });
9038 let dirty_multi_buffer_with_both = cx.new(|cx| {
9039 TestItem::new(cx)
9040 .with_dirty(true)
9041 .with_singleton(false)
9042 .with_label("Fake Project Search")
9043 .with_project_items(&[
9044 dirty_regular_buffer.read(cx).project_items[0].clone(),
9045 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
9046 ])
9047 });
9048 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
9049 workspace.update_in(cx, |workspace, window, cx| {
9050 workspace.add_item(
9051 pane.clone(),
9052 Box::new(dirty_regular_buffer.clone()),
9053 None,
9054 false,
9055 false,
9056 window,
9057 cx,
9058 );
9059 workspace.add_item(
9060 pane.clone(),
9061 Box::new(dirty_regular_buffer_2.clone()),
9062 None,
9063 false,
9064 false,
9065 window,
9066 cx,
9067 );
9068 workspace.add_item(
9069 pane.clone(),
9070 Box::new(dirty_multi_buffer_with_both.clone()),
9071 None,
9072 false,
9073 false,
9074 window,
9075 cx,
9076 );
9077 });
9078
9079 pane.update_in(cx, |pane, window, cx| {
9080 pane.activate_item(2, true, true, window, cx);
9081 assert_eq!(
9082 pane.active_item().unwrap().item_id(),
9083 multi_buffer_with_both_files_id,
9084 "Should select the multi buffer in the pane"
9085 );
9086 });
9087 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
9088 pane.close_inactive_items(
9089 &CloseInactiveItems {
9090 save_intent: Some(SaveIntent::Save),
9091 close_pinned: true,
9092 },
9093 window,
9094 cx,
9095 )
9096 });
9097 cx.background_executor.run_until_parked();
9098 assert!(!cx.has_pending_prompt());
9099 close_all_but_multi_buffer_task
9100 .await
9101 .expect("Closing all buffers but the multi buffer failed");
9102 pane.update(cx, |pane, cx| {
9103 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
9104 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
9105 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
9106 assert_eq!(pane.items_len(), 1);
9107 assert_eq!(
9108 pane.active_item().unwrap().item_id(),
9109 multi_buffer_with_both_files_id,
9110 "Should have only the multi buffer left in the pane"
9111 );
9112 assert!(
9113 dirty_multi_buffer_with_both.read(cx).is_dirty,
9114 "The multi buffer containing the unsaved buffer should still be dirty"
9115 );
9116 });
9117
9118 dirty_regular_buffer.update(cx, |buffer, cx| {
9119 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
9120 });
9121
9122 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
9123 pane.close_active_item(
9124 &CloseActiveItem {
9125 save_intent: Some(SaveIntent::Close),
9126 close_pinned: false,
9127 },
9128 window,
9129 cx,
9130 )
9131 });
9132 cx.background_executor.run_until_parked();
9133 assert!(
9134 cx.has_pending_prompt(),
9135 "Dirty multi buffer should prompt a save dialog"
9136 );
9137 cx.simulate_prompt_answer("Save");
9138 cx.background_executor.run_until_parked();
9139 close_multi_buffer_task
9140 .await
9141 .expect("Closing the multi buffer failed");
9142 pane.update(cx, |pane, cx| {
9143 assert_eq!(
9144 dirty_multi_buffer_with_both.read(cx).save_count,
9145 1,
9146 "Multi buffer item should get be saved"
9147 );
9148 // Test impl does not save inner items, so we do not assert them
9149 assert_eq!(
9150 pane.items_len(),
9151 0,
9152 "No more items should be left in the pane"
9153 );
9154 assert!(pane.active_item().is_none());
9155 });
9156 }
9157
9158 #[gpui::test]
9159 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
9160 cx: &mut TestAppContext,
9161 ) {
9162 init_test(cx);
9163
9164 let fs = FakeFs::new(cx.background_executor.clone());
9165 let project = Project::test(fs, [], cx).await;
9166 let (workspace, cx) =
9167 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9168 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9169
9170 let dirty_regular_buffer = cx.new(|cx| {
9171 TestItem::new(cx)
9172 .with_dirty(true)
9173 .with_label("1.txt")
9174 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
9175 });
9176 let dirty_regular_buffer_2 = cx.new(|cx| {
9177 TestItem::new(cx)
9178 .with_dirty(true)
9179 .with_label("2.txt")
9180 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
9181 });
9182 let clear_regular_buffer = cx.new(|cx| {
9183 TestItem::new(cx)
9184 .with_label("3.txt")
9185 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
9186 });
9187
9188 let dirty_multi_buffer_with_both = cx.new(|cx| {
9189 TestItem::new(cx)
9190 .with_dirty(true)
9191 .with_singleton(false)
9192 .with_label("Fake Project Search")
9193 .with_project_items(&[
9194 dirty_regular_buffer.read(cx).project_items[0].clone(),
9195 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
9196 clear_regular_buffer.read(cx).project_items[0].clone(),
9197 ])
9198 });
9199 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
9200 workspace.update_in(cx, |workspace, window, cx| {
9201 workspace.add_item(
9202 pane.clone(),
9203 Box::new(dirty_regular_buffer.clone()),
9204 None,
9205 false,
9206 false,
9207 window,
9208 cx,
9209 );
9210 workspace.add_item(
9211 pane.clone(),
9212 Box::new(dirty_multi_buffer_with_both.clone()),
9213 None,
9214 false,
9215 false,
9216 window,
9217 cx,
9218 );
9219 });
9220
9221 pane.update_in(cx, |pane, window, cx| {
9222 pane.activate_item(1, true, true, window, cx);
9223 assert_eq!(
9224 pane.active_item().unwrap().item_id(),
9225 multi_buffer_with_both_files_id,
9226 "Should select the multi buffer in the pane"
9227 );
9228 });
9229 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
9230 pane.close_active_item(
9231 &CloseActiveItem {
9232 save_intent: None,
9233 close_pinned: false,
9234 },
9235 window,
9236 cx,
9237 )
9238 });
9239 cx.background_executor.run_until_parked();
9240 assert!(
9241 cx.has_pending_prompt(),
9242 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
9243 );
9244 }
9245
9246 /// Tests that when `close_on_file_delete` is enabled, files are automatically
9247 /// closed when they are deleted from disk.
9248 #[gpui::test]
9249 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
9250 init_test(cx);
9251
9252 // Enable the close_on_disk_deletion setting
9253 cx.update_global(|store: &mut SettingsStore, cx| {
9254 store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
9255 settings.close_on_file_delete = Some(true);
9256 });
9257 });
9258
9259 let fs = FakeFs::new(cx.background_executor.clone());
9260 let project = Project::test(fs, [], cx).await;
9261 let (workspace, cx) =
9262 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9263 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9264
9265 // Create a test item that simulates a file
9266 let item = cx.new(|cx| {
9267 TestItem::new(cx)
9268 .with_label("test.txt")
9269 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
9270 });
9271
9272 // Add item to workspace
9273 workspace.update_in(cx, |workspace, window, cx| {
9274 workspace.add_item(
9275 pane.clone(),
9276 Box::new(item.clone()),
9277 None,
9278 false,
9279 false,
9280 window,
9281 cx,
9282 );
9283 });
9284
9285 // Verify the item is in the pane
9286 pane.read_with(cx, |pane, _| {
9287 assert_eq!(pane.items().count(), 1);
9288 });
9289
9290 // Simulate file deletion by setting the item's deleted state
9291 item.update(cx, |item, _| {
9292 item.set_has_deleted_file(true);
9293 });
9294
9295 // Emit UpdateTab event to trigger the close behavior
9296 cx.run_until_parked();
9297 item.update(cx, |_, cx| {
9298 cx.emit(ItemEvent::UpdateTab);
9299 });
9300
9301 // Allow the close operation to complete
9302 cx.run_until_parked();
9303
9304 // Verify the item was automatically closed
9305 pane.read_with(cx, |pane, _| {
9306 assert_eq!(
9307 pane.items().count(),
9308 0,
9309 "Item should be automatically closed when file is deleted"
9310 );
9311 });
9312 }
9313
9314 /// Tests that when `close_on_file_delete` is disabled (default), files remain
9315 /// open with a strikethrough when they are deleted from disk.
9316 #[gpui::test]
9317 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
9318 init_test(cx);
9319
9320 // Ensure close_on_disk_deletion is disabled (default)
9321 cx.update_global(|store: &mut SettingsStore, cx| {
9322 store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
9323 settings.close_on_file_delete = Some(false);
9324 });
9325 });
9326
9327 let fs = FakeFs::new(cx.background_executor.clone());
9328 let project = Project::test(fs, [], cx).await;
9329 let (workspace, cx) =
9330 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9331 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9332
9333 // Create a test item that simulates a file
9334 let item = cx.new(|cx| {
9335 TestItem::new(cx)
9336 .with_label("test.txt")
9337 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
9338 });
9339
9340 // Add item to workspace
9341 workspace.update_in(cx, |workspace, window, cx| {
9342 workspace.add_item(
9343 pane.clone(),
9344 Box::new(item.clone()),
9345 None,
9346 false,
9347 false,
9348 window,
9349 cx,
9350 );
9351 });
9352
9353 // Verify the item is in the pane
9354 pane.read_with(cx, |pane, _| {
9355 assert_eq!(pane.items().count(), 1);
9356 });
9357
9358 // Simulate file deletion
9359 item.update(cx, |item, _| {
9360 item.set_has_deleted_file(true);
9361 });
9362
9363 // Emit UpdateTab event
9364 cx.run_until_parked();
9365 item.update(cx, |_, cx| {
9366 cx.emit(ItemEvent::UpdateTab);
9367 });
9368
9369 // Allow any potential close operation to complete
9370 cx.run_until_parked();
9371
9372 // Verify the item remains open (with strikethrough)
9373 pane.read_with(cx, |pane, _| {
9374 assert_eq!(
9375 pane.items().count(),
9376 1,
9377 "Item should remain open when close_on_disk_deletion is disabled"
9378 );
9379 });
9380
9381 // Verify the item shows as deleted
9382 item.read_with(cx, |item, _| {
9383 assert!(
9384 item.has_deleted_file,
9385 "Item should be marked as having deleted file"
9386 );
9387 });
9388 }
9389
9390 /// Tests that dirty files are not automatically closed when deleted from disk,
9391 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
9392 /// unsaved changes without being prompted.
9393 #[gpui::test]
9394 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
9395 init_test(cx);
9396
9397 // Enable the close_on_file_delete setting
9398 cx.update_global(|store: &mut SettingsStore, cx| {
9399 store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
9400 settings.close_on_file_delete = Some(true);
9401 });
9402 });
9403
9404 let fs = FakeFs::new(cx.background_executor.clone());
9405 let project = Project::test(fs, [], cx).await;
9406 let (workspace, cx) =
9407 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9408 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9409
9410 // Create a dirty test item
9411 let item = cx.new(|cx| {
9412 TestItem::new(cx)
9413 .with_dirty(true)
9414 .with_label("test.txt")
9415 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
9416 });
9417
9418 // Add item to workspace
9419 workspace.update_in(cx, |workspace, window, cx| {
9420 workspace.add_item(
9421 pane.clone(),
9422 Box::new(item.clone()),
9423 None,
9424 false,
9425 false,
9426 window,
9427 cx,
9428 );
9429 });
9430
9431 // Simulate file deletion
9432 item.update(cx, |item, _| {
9433 item.set_has_deleted_file(true);
9434 });
9435
9436 // Emit UpdateTab event to trigger the close behavior
9437 cx.run_until_parked();
9438 item.update(cx, |_, cx| {
9439 cx.emit(ItemEvent::UpdateTab);
9440 });
9441
9442 // Allow any potential close operation to complete
9443 cx.run_until_parked();
9444
9445 // Verify the item remains open (dirty files are not auto-closed)
9446 pane.read_with(cx, |pane, _| {
9447 assert_eq!(
9448 pane.items().count(),
9449 1,
9450 "Dirty items should not be automatically closed even when file is deleted"
9451 );
9452 });
9453
9454 // Verify the item is marked as deleted and still dirty
9455 item.read_with(cx, |item, _| {
9456 assert!(
9457 item.has_deleted_file,
9458 "Item should be marked as having deleted file"
9459 );
9460 assert!(item.is_dirty, "Item should still be dirty");
9461 });
9462 }
9463
9464 /// Tests that navigation history is cleaned up when files are auto-closed
9465 /// due to deletion from disk.
9466 #[gpui::test]
9467 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
9468 init_test(cx);
9469
9470 // Enable the close_on_file_delete setting
9471 cx.update_global(|store: &mut SettingsStore, cx| {
9472 store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
9473 settings.close_on_file_delete = Some(true);
9474 });
9475 });
9476
9477 let fs = FakeFs::new(cx.background_executor.clone());
9478 let project = Project::test(fs, [], cx).await;
9479 let (workspace, cx) =
9480 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9481 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9482
9483 // Create test items
9484 let item1 = cx.new(|cx| {
9485 TestItem::new(cx)
9486 .with_label("test1.txt")
9487 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
9488 });
9489 let item1_id = item1.item_id();
9490
9491 let item2 = cx.new(|cx| {
9492 TestItem::new(cx)
9493 .with_label("test2.txt")
9494 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
9495 });
9496
9497 // Add items to workspace
9498 workspace.update_in(cx, |workspace, window, cx| {
9499 workspace.add_item(
9500 pane.clone(),
9501 Box::new(item1.clone()),
9502 None,
9503 false,
9504 false,
9505 window,
9506 cx,
9507 );
9508 workspace.add_item(
9509 pane.clone(),
9510 Box::new(item2.clone()),
9511 None,
9512 false,
9513 false,
9514 window,
9515 cx,
9516 );
9517 });
9518
9519 // Activate item1 to ensure it gets navigation entries
9520 pane.update_in(cx, |pane, window, cx| {
9521 pane.activate_item(0, true, true, window, cx);
9522 });
9523
9524 // Switch to item2 and back to create navigation history
9525 pane.update_in(cx, |pane, window, cx| {
9526 pane.activate_item(1, true, true, window, cx);
9527 });
9528 cx.run_until_parked();
9529
9530 pane.update_in(cx, |pane, window, cx| {
9531 pane.activate_item(0, true, true, window, cx);
9532 });
9533 cx.run_until_parked();
9534
9535 // Simulate file deletion for item1
9536 item1.update(cx, |item, _| {
9537 item.set_has_deleted_file(true);
9538 });
9539
9540 // Emit UpdateTab event to trigger the close behavior
9541 item1.update(cx, |_, cx| {
9542 cx.emit(ItemEvent::UpdateTab);
9543 });
9544 cx.run_until_parked();
9545
9546 // Verify item1 was closed
9547 pane.read_with(cx, |pane, _| {
9548 assert_eq!(
9549 pane.items().count(),
9550 1,
9551 "Should have 1 item remaining after auto-close"
9552 );
9553 });
9554
9555 // Check navigation history after close
9556 let has_item = pane.read_with(cx, |pane, cx| {
9557 let mut has_item = false;
9558 pane.nav_history().for_each_entry(cx, |entry, _| {
9559 if entry.item.id() == item1_id {
9560 has_item = true;
9561 }
9562 });
9563 has_item
9564 });
9565
9566 assert!(
9567 !has_item,
9568 "Navigation history should not contain closed item entries"
9569 );
9570 }
9571
9572 #[gpui::test]
9573 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
9574 cx: &mut TestAppContext,
9575 ) {
9576 init_test(cx);
9577
9578 let fs = FakeFs::new(cx.background_executor.clone());
9579 let project = Project::test(fs, [], cx).await;
9580 let (workspace, cx) =
9581 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9582 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
9583
9584 let dirty_regular_buffer = cx.new(|cx| {
9585 TestItem::new(cx)
9586 .with_dirty(true)
9587 .with_label("1.txt")
9588 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
9589 });
9590 let dirty_regular_buffer_2 = cx.new(|cx| {
9591 TestItem::new(cx)
9592 .with_dirty(true)
9593 .with_label("2.txt")
9594 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
9595 });
9596 let clear_regular_buffer = cx.new(|cx| {
9597 TestItem::new(cx)
9598 .with_label("3.txt")
9599 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
9600 });
9601
9602 let dirty_multi_buffer = cx.new(|cx| {
9603 TestItem::new(cx)
9604 .with_dirty(true)
9605 .with_singleton(false)
9606 .with_label("Fake Project Search")
9607 .with_project_items(&[
9608 dirty_regular_buffer.read(cx).project_items[0].clone(),
9609 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
9610 clear_regular_buffer.read(cx).project_items[0].clone(),
9611 ])
9612 });
9613 workspace.update_in(cx, |workspace, window, cx| {
9614 workspace.add_item(
9615 pane.clone(),
9616 Box::new(dirty_regular_buffer.clone()),
9617 None,
9618 false,
9619 false,
9620 window,
9621 cx,
9622 );
9623 workspace.add_item(
9624 pane.clone(),
9625 Box::new(dirty_regular_buffer_2.clone()),
9626 None,
9627 false,
9628 false,
9629 window,
9630 cx,
9631 );
9632 workspace.add_item(
9633 pane.clone(),
9634 Box::new(dirty_multi_buffer.clone()),
9635 None,
9636 false,
9637 false,
9638 window,
9639 cx,
9640 );
9641 });
9642
9643 pane.update_in(cx, |pane, window, cx| {
9644 pane.activate_item(2, true, true, window, cx);
9645 assert_eq!(
9646 pane.active_item().unwrap().item_id(),
9647 dirty_multi_buffer.item_id(),
9648 "Should select the multi buffer in the pane"
9649 );
9650 });
9651 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
9652 pane.close_active_item(
9653 &CloseActiveItem {
9654 save_intent: None,
9655 close_pinned: false,
9656 },
9657 window,
9658 cx,
9659 )
9660 });
9661 cx.background_executor.run_until_parked();
9662 assert!(
9663 !cx.has_pending_prompt(),
9664 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
9665 );
9666 close_multi_buffer_task
9667 .await
9668 .expect("Closing multi buffer failed");
9669 pane.update(cx, |pane, cx| {
9670 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
9671 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
9672 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
9673 assert_eq!(
9674 pane.items()
9675 .map(|item| item.item_id())
9676 .sorted()
9677 .collect::<Vec<_>>(),
9678 vec![
9679 dirty_regular_buffer.item_id(),
9680 dirty_regular_buffer_2.item_id(),
9681 ],
9682 "Should have no multi buffer left in the pane"
9683 );
9684 assert!(dirty_regular_buffer.read(cx).is_dirty);
9685 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
9686 });
9687 }
9688
9689 #[gpui::test]
9690 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
9691 init_test(cx);
9692 let fs = FakeFs::new(cx.executor());
9693 let project = Project::test(fs, [], cx).await;
9694 let (workspace, cx) =
9695 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
9696
9697 // Add a new panel to the right dock, opening the dock and setting the
9698 // focus to the new panel.
9699 let panel = workspace.update_in(cx, |workspace, window, cx| {
9700 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
9701 workspace.add_panel(panel.clone(), window, cx);
9702
9703 workspace
9704 .right_dock()
9705 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
9706
9707 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9708
9709 panel
9710 });
9711
9712 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
9713 // panel to the next valid position which, in this case, is the left
9714 // dock.
9715 cx.dispatch_action(MoveFocusedPanelToNextPosition);
9716 workspace.update(cx, |workspace, cx| {
9717 assert!(workspace.left_dock().read(cx).is_open());
9718 assert_eq!(panel.read(cx).position, DockPosition::Left);
9719 });
9720
9721 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
9722 // panel to the next valid position which, in this case, is the bottom
9723 // dock.
9724 cx.dispatch_action(MoveFocusedPanelToNextPosition);
9725 workspace.update(cx, |workspace, cx| {
9726 assert!(workspace.bottom_dock().read(cx).is_open());
9727 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
9728 });
9729
9730 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
9731 // around moving the panel to its initial position, the right dock.
9732 cx.dispatch_action(MoveFocusedPanelToNextPosition);
9733 workspace.update(cx, |workspace, cx| {
9734 assert!(workspace.right_dock().read(cx).is_open());
9735 assert_eq!(panel.read(cx).position, DockPosition::Right);
9736 });
9737
9738 // Remove focus from the panel, ensuring that, if the panel is not
9739 // focused, the `MoveFocusedPanelToNextPosition` action does not update
9740 // the panel's position, so the panel is still in the right dock.
9741 workspace.update_in(cx, |workspace, window, cx| {
9742 workspace.toggle_panel_focus::<TestPanel>(window, cx);
9743 });
9744
9745 cx.dispatch_action(MoveFocusedPanelToNextPosition);
9746 workspace.update(cx, |workspace, cx| {
9747 assert!(workspace.right_dock().read(cx).is_open());
9748 assert_eq!(panel.read(cx).position, DockPosition::Right);
9749 });
9750 }
9751
9752 #[gpui::test]
9753 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
9754 init_test(cx);
9755
9756 let fs = FakeFs::new(cx.executor());
9757 let project = Project::test(fs, [], cx).await;
9758 let (workspace, cx) =
9759 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
9760
9761 let item_1 = cx.new(|cx| {
9762 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
9763 });
9764 workspace.update_in(cx, |workspace, window, cx| {
9765 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
9766 workspace.move_item_to_pane_in_direction(
9767 &MoveItemToPaneInDirection {
9768 direction: SplitDirection::Right,
9769 focus: true,
9770 },
9771 window,
9772 cx,
9773 );
9774 workspace.move_item_to_pane_at_index(
9775 &MoveItemToPane {
9776 destination: 3,
9777 focus: true,
9778 },
9779 window,
9780 cx,
9781 );
9782
9783 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
9784 assert_eq!(
9785 pane_items_paths(&workspace.active_pane, cx),
9786 vec!["first.txt".to_string()],
9787 "Single item was not moved anywhere"
9788 );
9789 });
9790
9791 let item_2 = cx.new(|cx| {
9792 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
9793 });
9794 workspace.update_in(cx, |workspace, window, cx| {
9795 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
9796 assert_eq!(
9797 pane_items_paths(&workspace.panes[0], cx),
9798 vec!["first.txt".to_string(), "second.txt".to_string()],
9799 );
9800 workspace.move_item_to_pane_in_direction(
9801 &MoveItemToPaneInDirection {
9802 direction: SplitDirection::Right,
9803 focus: true,
9804 },
9805 window,
9806 cx,
9807 );
9808
9809 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
9810 assert_eq!(
9811 pane_items_paths(&workspace.panes[0], cx),
9812 vec!["first.txt".to_string()],
9813 "After moving, one item should be left in the original pane"
9814 );
9815 assert_eq!(
9816 pane_items_paths(&workspace.panes[1], cx),
9817 vec!["second.txt".to_string()],
9818 "New item should have been moved to the new pane"
9819 );
9820 });
9821
9822 let item_3 = cx.new(|cx| {
9823 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
9824 });
9825 workspace.update_in(cx, |workspace, window, cx| {
9826 let original_pane = workspace.panes[0].clone();
9827 workspace.set_active_pane(&original_pane, window, cx);
9828 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
9829 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
9830 assert_eq!(
9831 pane_items_paths(&workspace.active_pane, cx),
9832 vec!["first.txt".to_string(), "third.txt".to_string()],
9833 "New pane should be ready to move one item out"
9834 );
9835
9836 workspace.move_item_to_pane_at_index(
9837 &MoveItemToPane {
9838 destination: 3,
9839 focus: true,
9840 },
9841 window,
9842 cx,
9843 );
9844 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
9845 assert_eq!(
9846 pane_items_paths(&workspace.active_pane, cx),
9847 vec!["first.txt".to_string()],
9848 "After moving, one item should be left in the original pane"
9849 );
9850 assert_eq!(
9851 pane_items_paths(&workspace.panes[1], cx),
9852 vec!["second.txt".to_string()],
9853 "Previously created pane should be unchanged"
9854 );
9855 assert_eq!(
9856 pane_items_paths(&workspace.panes[2], cx),
9857 vec!["third.txt".to_string()],
9858 "New item should have been moved to the new pane"
9859 );
9860 });
9861 }
9862
9863 mod register_project_item_tests {
9864
9865 use super::*;
9866
9867 // View
9868 struct TestPngItemView {
9869 focus_handle: FocusHandle,
9870 }
9871 // Model
9872 struct TestPngItem {}
9873
9874 impl project::ProjectItem for TestPngItem {
9875 fn try_open(
9876 _project: &Entity<Project>,
9877 path: &ProjectPath,
9878 cx: &mut App,
9879 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
9880 if path.path.extension().unwrap() == "png" {
9881 Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
9882 } else {
9883 None
9884 }
9885 }
9886
9887 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
9888 None
9889 }
9890
9891 fn project_path(&self, _: &App) -> Option<ProjectPath> {
9892 None
9893 }
9894
9895 fn is_dirty(&self) -> bool {
9896 false
9897 }
9898 }
9899
9900 impl Item for TestPngItemView {
9901 type Event = ();
9902 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
9903 "".into()
9904 }
9905 }
9906 impl EventEmitter<()> for TestPngItemView {}
9907 impl Focusable for TestPngItemView {
9908 fn focus_handle(&self, _cx: &App) -> FocusHandle {
9909 self.focus_handle.clone()
9910 }
9911 }
9912
9913 impl Render for TestPngItemView {
9914 fn render(
9915 &mut self,
9916 _window: &mut Window,
9917 _cx: &mut Context<Self>,
9918 ) -> impl IntoElement {
9919 Empty
9920 }
9921 }
9922
9923 impl ProjectItem for TestPngItemView {
9924 type Item = TestPngItem;
9925
9926 fn for_project_item(
9927 _project: Entity<Project>,
9928 _pane: Option<&Pane>,
9929 _item: Entity<Self::Item>,
9930 _: &mut Window,
9931 cx: &mut Context<Self>,
9932 ) -> Self
9933 where
9934 Self: Sized,
9935 {
9936 Self {
9937 focus_handle: cx.focus_handle(),
9938 }
9939 }
9940 }
9941
9942 // View
9943 struct TestIpynbItemView {
9944 focus_handle: FocusHandle,
9945 }
9946 // Model
9947 struct TestIpynbItem {}
9948
9949 impl project::ProjectItem for TestIpynbItem {
9950 fn try_open(
9951 _project: &Entity<Project>,
9952 path: &ProjectPath,
9953 cx: &mut App,
9954 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
9955 if path.path.extension().unwrap() == "ipynb" {
9956 Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
9957 } else {
9958 None
9959 }
9960 }
9961
9962 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
9963 None
9964 }
9965
9966 fn project_path(&self, _: &App) -> Option<ProjectPath> {
9967 None
9968 }
9969
9970 fn is_dirty(&self) -> bool {
9971 false
9972 }
9973 }
9974
9975 impl Item for TestIpynbItemView {
9976 type Event = ();
9977 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
9978 "".into()
9979 }
9980 }
9981 impl EventEmitter<()> for TestIpynbItemView {}
9982 impl Focusable for TestIpynbItemView {
9983 fn focus_handle(&self, _cx: &App) -> FocusHandle {
9984 self.focus_handle.clone()
9985 }
9986 }
9987
9988 impl Render for TestIpynbItemView {
9989 fn render(
9990 &mut self,
9991 _window: &mut Window,
9992 _cx: &mut Context<Self>,
9993 ) -> impl IntoElement {
9994 Empty
9995 }
9996 }
9997
9998 impl ProjectItem for TestIpynbItemView {
9999 type Item = TestIpynbItem;
10000
10001 fn for_project_item(
10002 _project: Entity<Project>,
10003 _pane: Option<&Pane>,
10004 _item: Entity<Self::Item>,
10005 _: &mut Window,
10006 cx: &mut Context<Self>,
10007 ) -> Self
10008 where
10009 Self: Sized,
10010 {
10011 Self {
10012 focus_handle: cx.focus_handle(),
10013 }
10014 }
10015 }
10016
10017 struct TestAlternatePngItemView {
10018 focus_handle: FocusHandle,
10019 }
10020
10021 impl Item for TestAlternatePngItemView {
10022 type Event = ();
10023 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10024 "".into()
10025 }
10026 }
10027
10028 impl EventEmitter<()> for TestAlternatePngItemView {}
10029 impl Focusable for TestAlternatePngItemView {
10030 fn focus_handle(&self, _cx: &App) -> FocusHandle {
10031 self.focus_handle.clone()
10032 }
10033 }
10034
10035 impl Render for TestAlternatePngItemView {
10036 fn render(
10037 &mut self,
10038 _window: &mut Window,
10039 _cx: &mut Context<Self>,
10040 ) -> impl IntoElement {
10041 Empty
10042 }
10043 }
10044
10045 impl ProjectItem for TestAlternatePngItemView {
10046 type Item = TestPngItem;
10047
10048 fn for_project_item(
10049 _project: Entity<Project>,
10050 _pane: Option<&Pane>,
10051 _item: Entity<Self::Item>,
10052 _: &mut Window,
10053 cx: &mut Context<Self>,
10054 ) -> Self
10055 where
10056 Self: Sized,
10057 {
10058 Self {
10059 focus_handle: cx.focus_handle(),
10060 }
10061 }
10062 }
10063
10064 #[gpui::test]
10065 async fn test_register_project_item(cx: &mut TestAppContext) {
10066 init_test(cx);
10067
10068 cx.update(|cx| {
10069 register_project_item::<TestPngItemView>(cx);
10070 register_project_item::<TestIpynbItemView>(cx);
10071 });
10072
10073 let fs = FakeFs::new(cx.executor());
10074 fs.insert_tree(
10075 "/root1",
10076 json!({
10077 "one.png": "BINARYDATAHERE",
10078 "two.ipynb": "{ totally a notebook }",
10079 "three.txt": "editing text, sure why not?"
10080 }),
10081 )
10082 .await;
10083
10084 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10085 let (workspace, cx) =
10086 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10087
10088 let worktree_id = project.update(cx, |project, cx| {
10089 project.worktrees(cx).next().unwrap().read(cx).id()
10090 });
10091
10092 let handle = workspace
10093 .update_in(cx, |workspace, window, cx| {
10094 let project_path = (worktree_id, "one.png");
10095 workspace.open_path(project_path, None, true, window, cx)
10096 })
10097 .await
10098 .unwrap();
10099
10100 // Now we can check if the handle we got back errored or not
10101 assert_eq!(
10102 handle.to_any().entity_type(),
10103 TypeId::of::<TestPngItemView>()
10104 );
10105
10106 let handle = workspace
10107 .update_in(cx, |workspace, window, cx| {
10108 let project_path = (worktree_id, "two.ipynb");
10109 workspace.open_path(project_path, None, true, window, cx)
10110 })
10111 .await
10112 .unwrap();
10113
10114 assert_eq!(
10115 handle.to_any().entity_type(),
10116 TypeId::of::<TestIpynbItemView>()
10117 );
10118
10119 let handle = workspace
10120 .update_in(cx, |workspace, window, cx| {
10121 let project_path = (worktree_id, "three.txt");
10122 workspace.open_path(project_path, None, true, window, cx)
10123 })
10124 .await;
10125 assert!(handle.is_err());
10126 }
10127
10128 #[gpui::test]
10129 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
10130 init_test(cx);
10131
10132 cx.update(|cx| {
10133 register_project_item::<TestPngItemView>(cx);
10134 register_project_item::<TestAlternatePngItemView>(cx);
10135 });
10136
10137 let fs = FakeFs::new(cx.executor());
10138 fs.insert_tree(
10139 "/root1",
10140 json!({
10141 "one.png": "BINARYDATAHERE",
10142 "two.ipynb": "{ totally a notebook }",
10143 "three.txt": "editing text, sure why not?"
10144 }),
10145 )
10146 .await;
10147 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10148 let (workspace, cx) =
10149 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10150 let worktree_id = project.update(cx, |project, cx| {
10151 project.worktrees(cx).next().unwrap().read(cx).id()
10152 });
10153
10154 let handle = workspace
10155 .update_in(cx, |workspace, window, cx| {
10156 let project_path = (worktree_id, "one.png");
10157 workspace.open_path(project_path, None, true, window, cx)
10158 })
10159 .await
10160 .unwrap();
10161
10162 // This _must_ be the second item registered
10163 assert_eq!(
10164 handle.to_any().entity_type(),
10165 TypeId::of::<TestAlternatePngItemView>()
10166 );
10167
10168 let handle = workspace
10169 .update_in(cx, |workspace, window, cx| {
10170 let project_path = (worktree_id, "three.txt");
10171 workspace.open_path(project_path, None, true, window, cx)
10172 })
10173 .await;
10174 assert!(handle.is_err());
10175 }
10176 }
10177
10178 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
10179 pane.read(cx)
10180 .items()
10181 .flat_map(|item| {
10182 item.project_paths(cx)
10183 .into_iter()
10184 .map(|path| path.path.to_string_lossy().to_string())
10185 })
10186 .collect()
10187 }
10188
10189 pub fn init_test(cx: &mut TestAppContext) {
10190 cx.update(|cx| {
10191 let settings_store = SettingsStore::test(cx);
10192 cx.set_global(settings_store);
10193 theme::init(theme::LoadThemes::JustBase, cx);
10194 language::init(cx);
10195 crate::init_settings(cx);
10196 Project::init_settings(cx);
10197 });
10198 }
10199
10200 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
10201 let item = TestProjectItem::new(id, path, cx);
10202 item.update(cx, |item, _| {
10203 item.is_dirty = true;
10204 });
10205 item
10206 }
10207}